]> granicus.if.org Git - openjpeg/commitdiff
[trunk] FolderReorgProposal task: add JP3D
authorMathieu Malaterre <mathieu.malaterre@gmail.com>
Fri, 28 Sep 2012 08:32:34 +0000 (08:32 +0000)
committerMathieu Malaterre <mathieu.malaterre@gmail.com>
Fri, 28 Sep 2012 08:32:34 +0000 (08:32 +0000)
Update issue 177

55 files changed:
CMakeLists.txt
src/bin/jp3d/CMakeLists.txt [new file with mode: 0644]
src/bin/jp3d/Makefile.am [new file with mode: 0644]
src/bin/jp3d/convert.c [new file with mode: 0755]
src/bin/jp3d/convert.h [new file with mode: 0755]
src/bin/jp3d/getopt.c [new file with mode: 0755]
src/bin/jp3d/getopt.h [new file with mode: 0755]
src/bin/jp3d/jp3d_to_volume.c [new file with mode: 0755]
src/bin/jp3d/tcltk/LPI_JP3D_VM.tcl [new file with mode: 0755]
src/bin/jp3d/tcltk/README [new file with mode: 0644]
src/bin/jp3d/tcltk/Thumbs.db [new file with mode: 0755]
src/bin/jp3d/tcltk/decoder.tcl [new file with mode: 0755]
src/bin/jp3d/tcltk/encoder.tcl [new file with mode: 0755]
src/bin/jp3d/tcltk/logoLPI.gif [new file with mode: 0755]
src/bin/jp3d/volume_to_jp3d.c [new file with mode: 0755]
src/bin/jp3d/windirent.h [new file with mode: 0644]
src/lib/openjp3d/CMakeLists.txt [new file with mode: 0644]
src/lib/openjp3d/Makefile.am [new file with mode: 0644]
src/lib/openjp3d/bio.c [new file with mode: 0755]
src/lib/openjp3d/bio.h [new file with mode: 0755]
src/lib/openjp3d/cio.c [new file with mode: 0755]
src/lib/openjp3d/cio.h [new file with mode: 0755]
src/lib/openjp3d/dwt.c [new file with mode: 0755]
src/lib/openjp3d/dwt.h [new file with mode: 0755]
src/lib/openjp3d/event.c [new file with mode: 0755]
src/lib/openjp3d/event.h [new file with mode: 0755]
src/lib/openjp3d/fix.h [new file with mode: 0755]
src/lib/openjp3d/int.h [new file with mode: 0755]
src/lib/openjp3d/jp3d.c [new file with mode: 0755]
src/lib/openjp3d/jp3d.h [new file with mode: 0755]
src/lib/openjp3d/jp3d_lib.c [new file with mode: 0755]
src/lib/openjp3d/jp3d_lib.h [new file with mode: 0755]
src/lib/openjp3d/mct.c [new file with mode: 0755]
src/lib/openjp3d/mct.h [new file with mode: 0755]
src/lib/openjp3d/mqc.c [new file with mode: 0755]
src/lib/openjp3d/mqc.h [new file with mode: 0755]
src/lib/openjp3d/openjp3d.c [new file with mode: 0755]
src/lib/openjp3d/openjp3d.h [new file with mode: 0755]
src/lib/openjp3d/opj_includes.h [new file with mode: 0755]
src/lib/openjp3d/pi.c [new file with mode: 0755]
src/lib/openjp3d/pi.h [new file with mode: 0755]
src/lib/openjp3d/raw.c [new file with mode: 0755]
src/lib/openjp3d/raw.h [new file with mode: 0755]
src/lib/openjp3d/t1.c [new file with mode: 0755]
src/lib/openjp3d/t1.h [new file with mode: 0755]
src/lib/openjp3d/t1_3d.c [new file with mode: 0755]
src/lib/openjp3d/t1_3d.h [new file with mode: 0755]
src/lib/openjp3d/t2.c [new file with mode: 0755]
src/lib/openjp3d/t2.h [new file with mode: 0755]
src/lib/openjp3d/tcd.c [new file with mode: 0755]
src/lib/openjp3d/tcd.h [new file with mode: 0755]
src/lib/openjp3d/tgt.c [new file with mode: 0755]
src/lib/openjp3d/tgt.h [new file with mode: 0755]
src/lib/openjp3d/volume.c [new file with mode: 0755]
src/lib/openjp3d/volume.h [new file with mode: 0755]

index 7c7267bbba0e31571b83138a2c9d126a1db45213..b2fbaaa8d370ecb92b05aada8b1553606100d3d9 100644 (file)
@@ -198,8 +198,10 @@ if(BUILD_JPIP)
 endif()
 option(BUILD_VIEWER "Build the OPJViewer executable (C++)" OFF)
 option(BUILD_JAVA "Build the openjpeg jar (Java)" OFF)
+option(BUILD_JP3D "Build the JP3D comp" OFF)
 mark_as_advanced(BUILD_VIEWER)
 mark_as_advanced(BUILD_JAVA)
+mark_as_advanced(BUILD_JP3D)
 
 if(BUILD_CODEC OR BUILD_MJ2)
   # OFF: It will only build 3rd party libs if they are not found on the system
diff --git a/src/bin/jp3d/CMakeLists.txt b/src/bin/jp3d/CMakeLists.txt
new file mode 100644 (file)
index 0000000..a4742b7
--- /dev/null
@@ -0,0 +1,39 @@
+# Build the demo app, small examples
+
+# First thing define the common source:
+SET(common_SRCS
+  convert.c
+  )
+
+# Headers file are located here:
+include_directories(
+  ${OPENJPEG_SOURCE_DIR}/src/lib/openjp3d
+  ${LCMS_INCLUDE_DIRNAME}
+  ${OPENJPEG_SOURCE_DIR}/src/bin/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 jp3d_to_volume volume_to_jp3d)
+  ADD_EXECUTABLE(${exe} ${exe}.c ${common_SRCS})
+  TARGET_LINK_LIBRARIES(${exe} openjp3d)
+  # 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 OpenJP3DTargets
+    DESTINATION ${OPENJPEG_INSTALL_BIN_DIR} COMPONENT Applications
+  )
+ENDFOREACH(exe)
diff --git a/src/bin/jp3d/Makefile.am b/src/bin/jp3d/Makefile.am
new file mode 100644 (file)
index 0000000..bf6ff1e
--- /dev/null
@@ -0,0 +1,23 @@
+
+MAINTAINERCLEANFILES = Makefile.in
+
+bin_PROGRAMS = jp3d_to_volume volume_to_jp3d
+LDADD = $(USERLIBS) ../libjp3dvm/libopenjp3dvm.la
+
+jp3d_to_volume_CPPFLAGS =
+jp3d_to_volume_CFLAGS =
+jp3d_to_volume_LDADD = $(top_builddir)/jp3d/libjp3dvm/libopenjp3dvm.la -lm
+jp3d_to_volume_SOURCES = getopt.c convert.c jp3d_to_volume.c convert.h
+
+volume_to_jp3d_CPPFLAGS =
+volume_to_jp3d_CFLAGS =
+volume_to_jp3d_LDADD = $(top_builddir)/jp3d/libjp3dvm/libopenjp3dvm.la
+volume_to_jp3d_SOURCES = getopt.c convert.c volume_to_jp3d.c convert.h
+
+EXTRA_DIST = \
+CMakeLists.txt \
+windirent.h
+
+install-data-hook:
+       @echo -e " (B)\t$(bindir)/jp3d_to_volume$(EXEEXT)" >> $(top_builddir)/report.txt
+       @echo -e " (B)\t$(bindir)/volume_to_jp3d$(EXEEXT)" >> $(top_builddir)/report.txt
diff --git a/src/bin/jp3d/convert.c b/src/bin/jp3d/convert.c
new file mode 100755 (executable)
index 0000000..e613138
--- /dev/null
@@ -0,0 +1,997 @@
+/*
+ * 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) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain
+ * 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 "openjp3d.h"
+#ifdef _WIN32
+#include "windirent.h"
+#else
+#include <dirent.h>
+#endif /* _WIN32 */
+
+
+
+void dump_volume(FILE *fd, opj_volume_t * vol) {
+       int compno;
+       fprintf(fd, "volume {\n");
+       fprintf(fd, "  x0=%d, y0=%d, z0=%d, x1=%d, y1=%d, z1=%d\n", vol->x0, vol->y0, vol->z0,vol->x1, vol->y1,  vol->z1);
+       fprintf(fd, "  numcomps=%d\n", vol->numcomps);
+       for (compno = 0; compno < vol->numcomps; compno++) {
+               opj_volume_comp_t *comp = &vol->comps[compno];
+               fprintf(fd, "  comp %d {\n", compno);
+               fprintf(fd, "    dx=%d, dy=%d, dz=%d\n", comp->dx, comp->dy, comp->dz);
+               fprintf(fd, "    prec=%d\n", comp->prec);
+               fprintf(fd, "    sgnd=%d\n", comp->sgnd);
+               fprintf(fd, "  }\n");
+       }
+       fprintf(fd, "}\n");
+}
+
+/*
+ * 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;
+}
+
+/*
+ * Divide an integer by a power of 2 and round upwards.
+ *
+ * a divided by 2^b
+ */
+static int int_ceildivpow2(int a, int b) {
+       return (a + (1 << b) - 1) >> b;
+}
+
+/*
+ * Divide an integer and round upwards.
+ *
+ * a divided by b
+ */
+static int int_ceildiv(int a, int b) {
+       return (a + b - 1) / b;
+}
+
+
+/* -->> -->> -->> -->>
+
+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;
+}
+/*****************************************/
+static unsigned short ShortSwap(unsigned short v)
+{
+  unsigned char c1, c2;
+  c1 = v & 0xff;
+  c2 = (v >> 8) & 0xff;
+  return (c1 << 8) + c2;
+}
+
+static unsigned int LongSwap (unsigned int i)
+{
+  unsigned char b1, b2, b3, b4;
+  b1 = i & 255;
+  b2 = ( i >> 8 ) & 255;
+  b3 = ( i>>16 ) & 255;
+  b4 = ( i>>24 ) & 255;
+  return ((int)b1 << 24) + ((int)b2 << 16) + ((int)b3 << 8) + b4;
+}
+/*****************************************/
+
+opj_volume_t* pgxtovolume(char *relpath, opj_cparameters_t *parameters) {
+       
+       FILE *f = NULL;
+       int w, h, prec;
+       unsigned long offset;
+       int i, s, numcomps, maxvalue, sliceno, slicepos, maxslice = 0;
+       
+       OPJ_COLOR_SPACE color_space;
+       opj_volume_cmptparm_t cmptparm; // maximum of 1 component 
+       opj_volume_t * volume = NULL;
+
+       char endian1,endian2,sign;
+       char signtmp[32];
+       char temp[32];
+       opj_volume_comp_t *comp = NULL;
+
+               DIR *dirp;
+    struct dirent *direntp;
+       
+       char *tmp = NULL, *tmp2 = NULL,
+               *point = NULL, *pgx = NULL;
+       char tmpdirpath[MAX_PATH];
+       char dirpath[MAX_PATH];
+       char pattern[MAX_PATH];
+       char pgxfiles[MAX_SLICES][MAX_PATH];
+       int pgxslicepos[MAX_SLICES];
+       char tmpno[3];
+       
+       numcomps = 1;
+       color_space = CLRSPC_GRAY;
+       sliceno = 0;
+       maxvalue = 0;
+       memset(pgxfiles, 0, MAX_SLICES * MAX_PATH * sizeof(char));
+       memset(&cmptparm, 0, sizeof(opj_volume_cmptparm_t));
+       
+       /* Separación del caso de un único slice frente al de muchos */
+       if ((tmp = strrchr(relpath,'-')) == NULL){ 
+               //fprintf(stdout,"[INFO] A volume of only one slice....\n");
+               sliceno = 1;
+               maxslice = 1;
+               strcpy(pgxfiles[0],relpath);
+       
+       } else {
+               //Fetch only the path 
+               strcpy(tmpdirpath,relpath);
+               if ((tmp = strrchr(tmpdirpath,'/')) != NULL){
+                       tmp++; *tmp='\0';
+                       strcpy(dirpath,tmpdirpath);
+               } else {
+                       strcpy(dirpath,"./");
+               }
+
+               //Fetch the pattern of the volume slices
+               if ((tmp = strrchr (relpath,'/')) != NULL) 
+                       tmp++;  
+               else 
+                       tmp = relpath;
+        if ((tmp2 = strrchr(tmp,'-')) != NULL)
+            *tmp2='\0';
+               else{ 
+                       fprintf(stdout, "[ERROR] tmp2 ha dado null. no ha encontrado el * %s %s",tmp,relpath);
+                       return NULL;
+               }
+        strcpy(pattern,tmp);
+
+               dirp = opendir( dirpath );
+               if (dirp == NULL){
+                       fprintf(stdout, "[ERROR] Infile must be a .pgx file or a directory that contain pgx files");
+                       return NULL;
+               }
+
+               /*Read all .pgx files of directory */
+               while ( (direntp = readdir( dirp )) != NULL )
+               {
+                       /* Found a directory, but ignore . and .. */
+                       if(strcmp(".",direntp->d_name) == 0 || strcmp("..",direntp->d_name) == 0)
+                                       continue;
+                       
+                       if( ((pgx = strstr(direntp->d_name,pattern)) != NULL) && ((tmp2 = strstr(direntp->d_name,".pgx")) != NULL) ){
+                       
+                               strcpy(tmp,dirpath);
+                               tmp = strcat(tmp,direntp->d_name);
+                                               
+                               //Obtenemos el index de la secuencia de slices
+                               if ((tmp2 = strpbrk (direntp->d_name, "0123456789")) == NULL) 
+                                       continue;
+                               i = 0;
+                               while (tmp2 != NULL) {                                  
+                                       tmpno[i++] = *tmp2;
+                                       point = tmp2;
+                                       tmp2 = strpbrk (tmp2+1,"0123456789");
+                               }tmpno[i]='\0';
+
+                               //Comprobamos que no estamos leyendo algo raro como pattern.jp3d
+                               if ((point = strpbrk (point,".")) == NULL){
+                                       break;
+                               }
+                               //Slicepos --> index de slice; Sliceno --> no de slices hasta el momento
+                               slicepos = atoi(tmpno);
+                               pgxslicepos[sliceno] = slicepos - 1;
+                               sliceno++;
+                               if (slicepos>maxslice)
+                                       maxslice = slicepos;
+                               
+                               //Colocamos el slices en su posicion correspondiente
+                               strcpy(pgxfiles[slicepos-1],tmp);
+                       }
+               }
+       
+       }/* else if pattern*.pgx */
+
+       if (!sliceno) {
+               fprintf(stdout,"[ERROR] No slices with this pattern founded !! Please check input volume name\n");
+               return NULL;
+       }
+       /*if ( maxslice != sliceno) {
+               fprintf(stdout,"[ERROR] Slices are not sequentially numbered !! Please rename them accordingly\n");
+               return NULL;
+       }*/
+       
+       for (s=0;s<sliceno;s++)
+       {
+                       int pos = maxslice == sliceno ? s: pgxslicepos[s];
+                       f = fopen(pgxfiles[pos], "rb");
+                       if (!f) {
+                               fprintf(stdout, "[ERROR] Failed to open %s for reading !\n", pgxfiles[s]);
+                               return NULL;
+                       }
+                       fprintf(stdout, "[INFO] Loading %s \n",pgxfiles[pos]);
+
+                       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') {
+                               cmptparm.bigendian = 1;
+                       } else if (endian2=='M' && endian1=='L') {
+                               cmptparm.bigendian = 0;
+                       } else {
+                               fprintf(stdout, "[ERROR] Bad pgx header, please check input file\n");
+                               return NULL;
+                       }
+
+                       if (s==0){
+                               /* initialize volume component */
+
+                               cmptparm.x0 = parameters->volume_offset_x0;
+                               cmptparm.y0 = parameters->volume_offset_y0;
+                               cmptparm.z0 = parameters->volume_offset_z0;
+                               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;
+                               cmptparm.l = !cmptparm.z0 ? (sliceno - 1) * parameters->subsampling_dz + 1 : cmptparm.z0 + (sliceno - 1) * parameters->subsampling_dz + 1;
+                               
+                               if (sign == '-') {
+                                       cmptparm.sgnd = 1;
+                               } else {
+                                       cmptparm.sgnd = 0;
+                               }
+                               cmptparm.prec = prec;
+                               cmptparm.bpp = prec;
+                               cmptparm.dcoffset = parameters->dcoffset;
+                               cmptparm.dx = parameters->subsampling_dx;
+                               cmptparm.dy = parameters->subsampling_dy;
+                               cmptparm.dz = parameters->subsampling_dz;
+                               
+                               /* create the volume */
+                               volume = opj_volume_create(numcomps, &cmptparm, color_space);
+                               if(!volume) {
+                                       fclose(f);
+                                       return NULL;
+                               }
+                               /* set volume offset and reference grid */
+                               volume->x0 = cmptparm.x0;
+                               volume->y0 = cmptparm.y0;
+                               volume->z0 = cmptparm.z0;
+                               volume->x1 = cmptparm.w;
+                               volume->y1 = cmptparm.h;
+                               volume->z1 = cmptparm.l;
+                               
+                               /* set volume data :only one component, that is a volume*/
+                               comp = &volume->comps[0];
+                       
+                       }//if sliceno==1
+                       
+                       offset = w * h * s;
+                       
+                       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, cmptparm.bigendian);
+                                       } else {
+                                               v = (short) readushort(f, cmptparm.bigendian);
+                                       }
+                               } else {
+                                       if (!comp->sgnd) {
+                                               v = readuint(f, cmptparm.bigendian);
+                                       } else {
+                                               v = (int) readuint(f, cmptparm.bigendian);
+                                       }
+                               }                               
+                               if (v > maxvalue)
+                                       maxvalue = v;
+                               comp->data[i + offset] = v;
+                               
+                       }
+                       fclose(f);
+       } // for s --> sliceno
+       comp->bpp = int_floorlog2(maxvalue) + 1;
+       if (sliceno != 1)
+               closedir( dirp );
+       //dump_volume(stdout, volume);
+       return volume;
+}
+
+
+int volumetopgx(opj_volume_t * volume, char *outfile) {
+       int w, wr, wrr, h, hr, hrr, l, lr, lrr;
+       int i, j, compno, offset, sliceno;
+       FILE *fdest = NULL;
+
+       for (compno = 0; compno < volume->numcomps; compno++) {
+               opj_volume_comp_t *comp = &volume->comps[compno];
+               char name[256];
+               int nbytes = 0;
+               char *tmp = outfile;
+               while (*tmp) {
+                       tmp++;
+               }
+               while (*tmp!='.') {
+                       tmp--;
+               }
+               *tmp='\0';
+               for(sliceno = 0; sliceno < volume->z1 - volume->z0; sliceno++) {
+
+                       if (volume->numcomps > 1) {
+                               sprintf(name, "%s%d-%d.pgx", outfile, sliceno+1, compno);
+                       } else if ((volume->z1 - volume->z0) > 1) {
+                               sprintf(name, "%s%d.pgx", outfile, sliceno+1);
+                       } else {
+                               sprintf(name, "%s.pgx", outfile);
+                       }
+
+                       fdest = fopen(name, "wb");
+                       if (!fdest) {
+                               fprintf(stdout, "[ERROR] Failed to open %s for writing \n", name);
+                               return 1;
+                       }
+
+                       fprintf(stdout,"[INFO] Writing in %s (%s)\n",name,volume->comps[0].bigendian ? "Bigendian" : "Little-endian");
+
+                       w = int_ceildiv(volume->x1 - volume->x0, volume->comps[compno].dx);
+                       wr = volume->comps[compno].w;
+                       wrr = int_ceildivpow2(volume->comps[compno].w, volume->comps[compno].factor[0]);
+                       
+                       h = int_ceildiv(volume->y1 - volume->y0, volume->comps[compno].dy);
+                       hr = volume->comps[compno].h;
+                       hrr = int_ceildivpow2(volume->comps[compno].h, volume->comps[compno].factor[1]);
+                       
+                       l = int_ceildiv(volume->z1 - volume->z0, volume->comps[compno].dz);
+                       lr = volume->comps[compno].l;
+                       lrr = int_ceildivpow2(volume->comps[compno].l, volume->comps[compno].factor[2]);
+
+                       fprintf(fdest, "PG %c%c %c%d %d %d\n", comp->bigendian ? 'M':'L', comp->bigendian ? 'L':'M',comp->sgnd ? '-' : '+', comp->prec, wr, hr);
+                       if (comp->prec <= 8) {
+                               nbytes = 1;
+                       } else if (comp->prec <= 16) {
+                               nbytes = 2;
+                       } else {
+                               nbytes = 4;
+                       }
+
+                       offset = (sliceno / lrr * l) + (sliceno % lrr);
+                       offset = wrr * hrr * offset;
+                       //fprintf(stdout,"%d %d %d %d\n",offset,wrr*hrr,wrr,w);
+                       for (i = 0; i < wrr * hrr; i++) {
+                               int v = volume->comps[0].data[(i / wrr * w) + (i % wrr) + offset];
+                               if (volume->comps[0].bigendian) {
+                                       for (j = nbytes - 1; j >= 0; j--) {
+                        char byte = (char) ((v >> (j * 8)) & 0xff);
+                        fwrite(&byte, 1, 1, fdest);
+                                       }
+                               } else {
+                                       for (j = 0; j <= nbytes - 1; j++) {
+                        char byte = (char) ((v >> (j * 8)) & 0xff);
+                                               fwrite(&byte, 1, 1, fdest);
+                                       }
+                               }
+                       }
+
+                       fclose(fdest);
+               }//for sliceno
+       }//for compno
+
+       return 0;
+}
+
+/* -->> -->> -->> -->>
+
+BIN IMAGE FORMAT
+
+<<-- <<-- <<-- <<-- */
+
+opj_volume_t* bintovolume(char *filename, char *fileimg, opj_cparameters_t *parameters) {
+       int subsampling_dx =  parameters->subsampling_dx;
+       int subsampling_dy =  parameters->subsampling_dy;
+       int subsampling_dz =  parameters->subsampling_dz;
+       
+       int i, compno, w, h, l, numcomps = 1;
+       int prec, max = 0;
+
+//     char temp[32];
+       char line[100];
+       int bigendian;
+       
+       FILE *f = NULL;
+       FILE *fimg = NULL;
+       OPJ_COLOR_SPACE color_space;
+       opj_volume_cmptparm_t cmptparm; /* maximum of 1 component */
+       opj_volume_t * volume = NULL;
+       opj_volume_comp_t *comp = NULL;
+
+       bigendian = 0;
+       color_space = CLRSPC_GRAY;
+
+       fimg = fopen(fileimg,"r");
+       if (!fimg) { 
+               fprintf(stdout, "[ERROR] Failed to open %s for reading !!\n", fileimg);
+               return 0;
+       }
+
+       fseek(fimg, 0, SEEK_SET);
+       while (!feof(fimg)) {
+        fgets(line,100,fimg);
+               //fprintf(stdout,"%s %d \n",line,feof(fimg));
+               if (strncmp(line,"Bpp",3) == 0){
+                       sscanf(line,"%*s%*[ \t]%d",&prec);
+               } else if (strncmp(line,"Color",5) == 0){
+                       sscanf(line, "%*s%*[ \t]%d",&color_space);
+               } else if (strncmp(line,"Dim",3) == 0){
+                       sscanf(line, "%*s%*[ \t]%d%*[ \t]%d%*[ \t]%d",&w,&h,&l);
+               }
+       }
+       //fscanf(fimg, "Bpp%[ \t]%d%[ \t\n]",temp,&prec,temp);
+       //fscanf(fimg, "Color Map%[ \t]%d%[ \n\t]Dimensions%[ \t]%d%[ \t]%d%[ \t]%d%[ \n\t]",temp,&color_space,temp,temp,&w,temp,&h,temp,&l,temp);
+       //fscanf(fimg, "Resolution(mm)%[ \t]%d%[ \t]%d%[ \t]%d%[ \n\t]",temp,&subsampling_dx,temp,&subsampling_dy,temp,&subsampling_dz,temp);
+
+       #ifdef VERBOSE
+               fprintf(stdout, "[INFO] %d \t %d %d %d \t %3.2f %2.2f %2.2f \t %d \n",color_space,w,h,l,subsampling_dx,subsampling_dy,subsampling_dz,prec);
+       #endif
+       fclose(fimg);
+       
+       /* initialize volume components */
+       memset(&cmptparm, 0, sizeof(opj_volume_cmptparm_t));
+       
+       cmptparm.prec = prec;
+       cmptparm.bpp = prec;
+       cmptparm.sgnd = 0;
+       cmptparm.bigendian = bigendian;
+       cmptparm.dcoffset = parameters->dcoffset;
+       cmptparm.dx = subsampling_dx;
+       cmptparm.dy = subsampling_dy;
+       cmptparm.dz = subsampling_dz;
+       cmptparm.w = w;
+       cmptparm.h = h;
+       cmptparm.l = l;
+       
+       /* create the volume */
+       volume = opj_volume_create(numcomps, &cmptparm, color_space);
+       if(!volume) {
+               fprintf(stdout,"[ERROR] Unable to create volume");      
+               fclose(f);
+               return NULL;
+       }
+       
+       /* set volume offset and reference grid */
+       volume->x0 = parameters->volume_offset_x0;
+       volume->y0 = parameters->volume_offset_y0;
+       volume->z0 = parameters->volume_offset_z0;
+       volume->x1 = parameters->volume_offset_x0 + (w - 1) *   subsampling_dx + 1;
+       volume->y1 = parameters->volume_offset_y0 + (h - 1) *   subsampling_dy + 1;
+       volume->z1 = parameters->volume_offset_z0 + (l - 1) *   subsampling_dz + 1;
+       
+       /* set volume data */
+       f = fopen(filename, "rb");
+       if (!f) {
+               fprintf(stdout, "[ERROR] Failed to open %s for reading !!\n", filename);
+               return 0;
+       }
+       
+       /* BINARY */
+       for (compno = 0; compno < volume->numcomps; compno++) {
+               int whl = w * h * l;
+               /* set volume data */
+               comp = &volume->comps[compno];
+               
+               /*if (comp->prec <= 8) {
+                       if (!comp->sgnd) {
+                unsigned char *data = (unsigned char *) malloc(whl * sizeof(unsigned char));
+                               fread(data, 1, whl, f);
+                               for (i = 0; i < whl; i++) {
+                                       comp->data[i] = data[i];
+                                       if (comp->data[i] > max)
+                                               max = comp->data[i];
+                               }
+                               free(data);
+                       } else {
+                               char *data = (char *) malloc(whl);
+                               fread(data, 1, whl, f);
+                               for (i = 0; i < whl; i++) {
+                                       comp->data[i] = data[i];
+                                       if (comp->data[i] > max)
+                                               max = comp->data[i];
+                               }
+                               free(data);
+                       }
+               } else if (comp->prec <= 16) {
+                       if (!comp->sgnd) {
+                unsigned short *data = (unsigned short *) malloc(whl * sizeof(unsigned short));
+                               int leido = fread(data, 2, whl, f);
+                               if (!leido)     {
+                                       free(data);     fclose(f);
+                                       return NULL;
+                               }
+                               
+                               for (i = 0; i < whl; i++) {
+                                       if (bigendian)  //(c1 << 8) + c2;
+                                               comp->data[i] = data[i];
+                                       else{                   //(c2 << 8) + c1;
+                                               comp->data[i] = ShortSwap(data[i]);
+                                       }
+                                       if (comp->data[i] > max)
+                                               max = comp->data[i];
+                               }
+                               free(data);
+                       } else {
+                               short *data = (short *) malloc(whl);
+                               int leido = fread(data, 2, whl, f);
+                               if (!leido)     {
+                                       free(data);     fclose(f);
+                                       return NULL;
+                               }
+                               for (i = 0; i < whl; i++) {
+                                       if (bigendian){ //(c1 << 8) + c2;
+                                               comp->data[i] = data[i];
+                                       }else{                  //(c2 << 8) + c1;
+                                               comp->data[i] = (short) ShortSwap((unsigned short) data[i]);
+                                       }
+                                       if (comp->data[i] > max)
+                                               max = comp->data[i];
+                               }
+                               free(data);
+                       }
+               } else {
+                       if (!comp->sgnd) {
+                unsigned int *data = (unsigned int *) malloc(whl * sizeof(unsigned int));
+                               int leido = fread(data, 4, whl, f);
+                               if (!leido)     {
+                                       free(data);     fclose(f);
+                                       return NULL;
+                               }                               for (i = 0; i < whl; i++) {
+                                       if (!bigendian)
+                                               comp->data[i] = LongSwap(data[i]);
+                                       else
+                                               comp->data[i] = data[i];
+                                       if (comp->data[i] > max)
+                                               max = comp->data[i];
+                               }
+                               free(data);
+                       } else {
+                               int leido = fread(comp->data, 4, whl, f);
+                               if (!leido)     {
+                                       fclose(f);
+                                       return NULL;
+                               }                               
+                               for (i = 0; i < whl; i++) {
+                                       if (!bigendian) 
+                                               comp->data[i] = (int) LongSwap((unsigned int) comp->data[i]);
+                                       if (comp->data[i] > max)
+                                               max = comp->data[i];
+                               }
+                       }
+               }*/
+               
+               for (i = 0; i < whl; 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;
+               }
+               comp->bpp = int_floorlog2(max) + 1;
+       }
+       fclose(f);
+       return volume;
+}
+
+int volumetobin(opj_volume_t * volume, char *outfile) {
+       int w, wr, wrr, h, hr, hrr, l, lr, lrr, max;
+       int i,j, compno, nbytes;
+       int offset, sliceno;
+       FILE *fdest = NULL;
+       FILE *fimgdest = NULL;
+//     char *imgtemp;
+       char name[256];
+
+       for (compno = 0; compno < 1; compno++) { //Only one component
+               
+               fdest = fopen(outfile, "wb");
+               if (!fdest) {
+                       fprintf(stdout, "[ERROR] Failed to open %s for writing\n", outfile);
+                       return 1;
+               }
+        fprintf(stdout,"[INFO] Writing outfile %s (%s) \n",outfile, volume->comps[0].bigendian ? "Bigendian" : "Little-endian");
+
+               w = int_ceildiv(volume->x1 - volume->x0, volume->comps[compno].dx);
+               wr = volume->comps[compno].w;
+               wrr = int_ceildivpow2(volume->comps[compno].w, volume->comps[compno].factor[0]);
+               
+               h = int_ceildiv(volume->y1 - volume->y0, volume->comps[compno].dy);
+               hr = volume->comps[compno].h;
+               hrr = int_ceildivpow2(volume->comps[compno].h, volume->comps[compno].factor[1]);
+               
+               l = int_ceildiv(volume->z1 - volume->z0, volume->comps[compno].dz);
+               lr = volume->comps[compno].l;
+               lrr = int_ceildivpow2(volume->comps[compno].l, volume->comps[compno].factor[2]);
+
+               max = (volume->comps[compno].prec <= 8) ? 255 : (1 << volume->comps[compno].prec) - 1;
+               
+               volume->comps[compno].x0 = int_ceildivpow2(volume->comps[compno].x0 - int_ceildiv(volume->x0, volume->comps[compno].dx), volume->comps[compno].factor[0]);
+               volume->comps[compno].y0 = int_ceildivpow2(volume->comps[compno].y0 - int_ceildiv(volume->y0, volume->comps[compno].dy), volume->comps[compno].factor[1]);
+               volume->comps[compno].z0 = int_ceildivpow2(volume->comps[compno].z0 - int_ceildiv(volume->z0, volume->comps[compno].dz), volume->comps[compno].factor[2]);
+               
+               if (volume->comps[0].prec <= 8) {
+                       nbytes = 1;
+               } else if (volume->comps[0].prec <= 16) {
+                       nbytes = 2;
+               } else {
+                       nbytes = 4;
+               }
+
+               //fprintf(stdout,"w %d wr %d wrr %d h %d hr %d hrr %d l %d lr %d lrr %d max %d nbytes %d\n Factor %d %d %d",w,wr,wrr,h,hr,hrr,l,lr,lrr,max,nbytes,volume->comps[compno].factor[0],volume->comps[compno].factor[1],volume->comps[compno].factor[2]);
+
+               for(sliceno = 0; sliceno < lrr; sliceno++) {
+                       offset = (sliceno / lrr * l) + (sliceno % lrr);
+            offset = wrr * hrr * offset;
+                       for (i = 0; i < wrr * hrr; i++) {
+                               int v = volume->comps[0].data[(i / wrr * w) + (i % wrr) + offset];
+                               if (volume->comps[0].bigendian) {
+                                       for (j = nbytes - 1; j >= 0; j--) {
+                        char byte = (char) ((v >> (j * 8)) & 0xff);
+                        fwrite(&byte, 1, 1, fdest);
+                                       }
+                               } else {
+                                       for (j = 0; j <= nbytes - 1; j++) {
+                        char byte = (char) ((v >> (j * 8)) & 0xff);
+                                               fwrite(&byte, 1, 1, fdest);
+                                       }
+                               }
+                       }
+               }
+       
+       }
+       
+       fclose(fdest);
+
+       sprintf(name,"%s.img",outfile);
+       fimgdest = fopen(name, "w");
+               if (!fimgdest) {
+                       fprintf(stdout, "[ERROR] Failed to open %s for writing\n", name);
+                       return 1;
+               }
+       fprintf(fimgdest, "Bpp\t%d\nColor Map\t2\nDimensions\t%d\t%d\t%d\nResolution(mm)\t%d\t%d\t%d\t\n",
+               volume->comps[0].prec,wrr,hrr,lrr,volume->comps[0].dx,volume->comps[0].dy,volume->comps[0].dz);
+
+       fclose(fimgdest);
+       return 0;
+}
+/* -->> -->> -->> -->>
+
+IMG IMAGE FORMAT
+
+<<-- <<-- <<-- <<-- */
+opj_volume_t* imgtovolume(char *fileimg, opj_cparameters_t *parameters) {
+       int subsampling_dx =  parameters->subsampling_dx;
+       int subsampling_dy =  parameters->subsampling_dy;
+       int subsampling_dz =  parameters->subsampling_dz;
+       
+       int i, compno, w, h, l, numcomps = 1;
+       int prec, max = 0, min = 0;
+       float dx, dy, dz;
+       char filename[100], tmpdirpath[100], dirpath[100], *tmp;
+       char line[100], datatype[100];
+       int bigendian;
+       
+       FILE *f = NULL;
+       FILE *fimg = NULL;
+       OPJ_COLOR_SPACE color_space;
+       opj_volume_cmptparm_t cmptparm; /* maximum of 1 component */
+       opj_volume_t * volume = NULL;
+       opj_volume_comp_t *comp = NULL;
+
+       bigendian = 0;
+       color_space = CLRSPC_GRAY;
+
+       fimg = fopen(fileimg,"r");
+       if (!fimg) { 
+               fprintf(stderr, "[ERROR] Failed to open %s for reading !!\n", fileimg);
+               return 0;
+       }
+
+       //Fetch only the path 
+       strcpy(tmpdirpath,fileimg);
+       if ((tmp = strrchr(tmpdirpath,'/')) != NULL){
+               tmp++; *tmp='\0';
+               strcpy(dirpath,tmpdirpath);
+       } else {
+               strcpy(dirpath,"./");
+       }
+
+       fseek(fimg, 0, SEEK_SET);
+       while (!feof(fimg)) {
+        fgets(line,100,fimg);
+               //fprintf(stdout,"%s %d \n",line,feof(fimg));
+               if (strncmp(line,"Image",5) == 0){
+                       sscanf(line,"%*s%*[ \t]%s",datatype);
+               } else if (strncmp(line,"File",4) == 0){
+                       sscanf(line,"%*s %*s%*[ \t]%s",filename);
+                       strcat(dirpath, filename);
+                       strcpy(filename,dirpath);
+               } else if (strncmp(line,"Min",3) == 0){
+                       sscanf(line,"%*s %*s%*[ \t]%d%*[ \t]%d",&min,&max);
+                       prec = int_floorlog2(max - min + 1);
+               } else if (strncmp(line,"Bpp",3) == 0){
+                       sscanf(line,"%*s%*[ \t]%d",&prec);
+               } else if (strncmp(line,"Color",5) == 0){
+                       sscanf(line, "%*s %*s%*[ \t]%d",&color_space);
+               } else if (strncmp(line,"Dim",3) == 0){
+                       sscanf(line, "%*s%*[ \t]%d%*[ \t]%d%*[ \t]%d",&w,&h,&l);
+               } else if (strncmp(line,"Res",3) == 0){
+                       sscanf(line,"%*s%*[ \t]%f%*[ \t]%f%*[ \t]%f",&dx,&dy,&dz);
+               }
+
+       }
+       #ifdef VERBOSE
+               fprintf(stdout, "[INFO] %s %d \t %d %d %d \t %f %f %f \t %d %d %d \n",filename,color_space,w,h,l,dx,dy,dz,max,min,prec);
+       #endif
+       fclose(fimg);
+
+       /* error control */
+       if ( !prec || !w || !h || !l ){
+               fprintf(stderr,"[ERROR] Unable to read IMG file correctly. Found some null values.");   
+               return NULL;
+       }
+
+       /* initialize volume components */
+       memset(&cmptparm, 0, sizeof(opj_volume_cmptparm_t));
+       
+       cmptparm.prec = prec;
+       cmptparm.bpp = prec;
+       cmptparm.sgnd = 0;
+       cmptparm.bigendian = bigendian;
+       cmptparm.dcoffset = parameters->dcoffset;
+       cmptparm.dx = subsampling_dx;
+       cmptparm.dy = subsampling_dy;
+       cmptparm.dz = subsampling_dz;
+       cmptparm.w = w;
+       cmptparm.h = h;
+       cmptparm.l = l;
+       
+       /* create the volume */
+       volume = opj_volume_create(numcomps, &cmptparm, color_space);
+       if(!volume) {
+               fprintf(stdout,"[ERROR] Unable to create volume");      
+               return NULL;
+       }
+       
+       /* set volume offset and reference grid */
+       volume->x0 = parameters->volume_offset_x0;
+       volume->y0 = parameters->volume_offset_y0;
+       volume->z0 = parameters->volume_offset_z0;
+       volume->x1 = parameters->volume_offset_x0 + (w - 1) *   subsampling_dx + 1;
+       volume->y1 = parameters->volume_offset_y0 + (h - 1) *   subsampling_dy + 1;
+       volume->z1 = parameters->volume_offset_z0 + (l - 1) *   subsampling_dz + 1;
+       
+       max = 0;
+       /* set volume data */
+       f = fopen(filename, "rb");
+       if (!f) {
+               fprintf(stderr, "[ERROR] Failed to open %s for reading !!\n", filename);
+               fclose(f);
+               return 0;
+       }
+       
+       /* BINARY */
+       for (compno = 0; compno < volume->numcomps; compno++) {
+               int whl = w * h * l;
+               /* set volume data */
+               comp = &volume->comps[compno];
+               
+               /*if (comp->prec <= 8) {
+                       if (!comp->sgnd) {
+                unsigned char *data = (unsigned char *) malloc(whl * sizeof(unsigned char));
+                               fread(data, 1, whl, f);
+                               for (i = 0; i < whl; i++) {
+                                       comp->data[i] = data[i];
+                                       if (comp->data[i] > max)
+                                               max = comp->data[i];
+                               }
+                               free(data);
+                       } else {
+                               char *data = (char *) malloc(whl);
+                               fread(data, 1, whl, f);
+                               for (i = 0; i < whl; i++) {
+                                       comp->data[i] = data[i];
+                                       if (comp->data[i] > max)
+                                               max = comp->data[i];
+                               }
+                               free(data);
+                       }
+               } else if (comp->prec <= 16) {
+                       if (!comp->sgnd) {
+                unsigned short *data = (unsigned short *) malloc(whl * sizeof(unsigned short));
+                               int leido = fread(data, 2, whl, f);
+                               if (!leido)     {
+                                       free(data);     fclose(f);
+                                       return NULL;
+                               }
+                               
+                               for (i = 0; i < whl; i++) {
+                                       if (bigendian)  //(c1 << 8) + c2;
+                                               comp->data[i] = data[i];
+                                       else{                   //(c2 << 8) + c1;
+                                               comp->data[i] = ShortSwap(data[i]);
+                                       }
+                                       if (comp->data[i] > max)
+                                               max = comp->data[i];
+                               }
+                               free(data);
+                       } else {
+                               short *data = (short *) malloc(whl);
+                               int leido = fread(data, 2, whl, f);
+                               if (!leido)     {
+                                       free(data);     fclose(f);
+                                       return NULL;
+                               }
+                               for (i = 0; i < whl; i++) {
+                                       if (bigendian){ //(c1 << 8) + c2;
+                                               comp->data[i] = data[i];
+                                       }else{                  //(c2 << 8) + c1;
+                                               comp->data[i] = (short) ShortSwap((unsigned short) data[i]);
+                                       }
+                                       if (comp->data[i] > max)
+                                               max = comp->data[i];
+                               }
+                               free(data);
+                       }
+               } else {
+                       if (!comp->sgnd) {
+                unsigned int *data = (unsigned int *) malloc(whl * sizeof(unsigned int));
+                               int leido = fread(data, 4, whl, f);
+                               if (!leido)     {
+                                       free(data);     fclose(f);
+                                       return NULL;
+                               }                               for (i = 0; i < whl; i++) {
+                                       if (!bigendian)
+                                               comp->data[i] = LongSwap(data[i]);
+                                       else
+                                               comp->data[i] = data[i];
+                                       if (comp->data[i] > max)
+                                               max = comp->data[i];
+                               }
+                               free(data);
+                       } else {
+                               int leido = fread(comp->data, 4, whl, f);
+                               if (!leido)     {
+                                       fclose(f);
+                                       return NULL;
+                               }                               
+                               for (i = 0; i < whl; i++) {
+                                       if (!bigendian) 
+                                               comp->data[i] = (int) LongSwap((unsigned int) comp->data[i]);
+                                       if (comp->data[i] > max)
+                                               max = comp->data[i];
+                               }
+                       }
+               }*/
+               
+               for (i = 0; i < whl; 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;
+               }
+               comp->bpp = int_floorlog2(max) + 1;
+       }
+       fclose(f);
+       return volume;
+}
+
diff --git a/src/bin/jp3d/convert.h b/src/bin/jp3d/convert.h
new file mode 100755 (executable)
index 0000000..8588556
--- /dev/null
@@ -0,0 +1,51 @@
+/*\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) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain\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
+#ifndef __JP3D_CONVERT_H\r
+#define __JP3D_CONVERT_H\r
+\r
+/**\r
+Load a single volume component encoded in PGX file format\r
+@param filename Name of the PGX file to load\r
+@param parameters *List ?*\r
+@return Returns a greyscale volume if successful, returns NULL otherwise\r
+*/\r
+opj_volume_t* pgxtovolume(char *filename, opj_cparameters_t *parameters);\r
+\r
+int volumetopgx(opj_volume_t *volume, char *outfile);\r
+\r
+opj_volume_t* bintovolume(char *filename,char *fileimg, opj_cparameters_t *parameters);\r
+\r
+int volumetobin(opj_volume_t *volume, char *outfile);\r
+\r
+opj_volume_t* imgtovolume(char *fileimg, opj_cparameters_t *parameters);\r
+\r
+#endif /* __J2K_CONVERT_H */\r
+\r
diff --git a/src/bin/jp3d/getopt.c b/src/bin/jp3d/getopt.c
new file mode 100755 (executable)
index 0000000..69addc9
--- /dev/null
@@ -0,0 +1,109 @@
+/*\r
+ * Copyright (c) 1987, 1993, 1994\r
+ *     The Regents of the University of California.  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
+ * 3. All advertising materials mentioning features or use of this software\r
+ *    must display the following acknowledgement:\r
+ *     This product includes software developed by the University of\r
+ *     California, Berkeley and its contributors.\r
+ * 4. Neither the name of the University nor the names of its contributors\r
+ *    may be used to endorse or promote products derived from this software\r
+ *    without specific prior written permission.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\r
+ * 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 REGENTS OR CONTRIBUTORS BE LIABLE\r
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\r
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\r
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\r
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\r
+ * SUCH DAMAGE.\r
+ */\r
+\r
+/* last review : october 29th, 2002 */\r
+\r
+#if defined(LIBC_SCCS) && !defined(lint)\r
+static char sccsid[] = "@(#)getopt.c   8.3 (Berkeley) 4/27/95";\r
+#endif                         /* LIBC_SCCS and not lint */\r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+\r
+int opterr = 1,                        /* if error message should be printed */\r
+ optind = 1,                   /* index into parent argv vector */\r
+ optopt,                               /* character checked for validity */\r
+ optreset;                             /* reset getopt */\r
+char *optarg;                  /* argument associated with option */\r
+\r
+#define        BADCH   (int)'?'\r
+#define        BADARG  (int)':'\r
+#define        EMSG    ""\r
+\r
+/*\r
+ * getopt --\r
+ *     Parse argc/argv argument vector.\r
+ */\r
+int getopt(int nargc, char *const *nargv, const char *ostr) {\r
+       \r
+  #  define __progname nargv[0] /* program name */\r
+       \r
+  static char *place = EMSG;   /* option letter processing */\r
+  char *oli;                                   /* option letter list index */\r
+\r
+  if (optreset || !*place) {   /* update scanning pointer */\r
+    optreset = 0;\r
+    if (optind >= nargc || *(place = nargv[optind]) != '-') {\r
+      place = EMSG;\r
+      return (-1);\r
+    }\r
+    if (place[1] && *++place == '-') { /* found "--" */\r
+      ++optind;\r
+      place = EMSG;\r
+      return (-1);\r
+    }\r
+  }    /* option letter okay? */\r
+  \r
+  if ((optopt = (int) *place++) == (int) ':' || !(oli = strchr(ostr, optopt))) {\r
+    /* if the user didn't specify '-' as an option, assume it means -1. */\r
+    if (optopt == (int) '-')\r
+      return (-1);\r
+    if (!*place)\r
+      ++optind;\r
+    if (opterr && *ostr != ':')\r
+      (void) fprintf(stdout,"[ERROR] %s: illegal option -- %c\n", __progname, optopt);\r
+    return (BADCH);\r
+  }\r
+\r
+  if (*++oli != ':') {         /* don't need argument */\r
+    optarg = NULL;\r
+    if (!*place)\r
+      ++optind;\r
+  } else {                                     /* need an argument */\r
+    if (*place)                                                /* no white space */\r
+      optarg = place;\r
+    else if (nargc <= ++optind) {      /* no arg */\r
+      place = EMSG;\r
+      if (*ostr == ':')\r
+               return (BADARG);\r
+      if (opterr)\r
+               (void) fprintf(stdout, "[ERROR] %s: option requires an argument -- %c\n", __progname, optopt);\r
+      return (BADCH);\r
+    } else                                                     /* white space */\r
+      optarg = nargv[optind];\r
+    place = EMSG;\r
+    ++optind;\r
+  }\r
+  return (optopt);             /* dump back option letter */\r
+}\r
diff --git a/src/bin/jp3d/getopt.h b/src/bin/jp3d/getopt.h
new file mode 100755 (executable)
index 0000000..23299d1
--- /dev/null
@@ -0,0 +1,14 @@
+/* last review : october 29th, 2002 */\r
+\r
+#ifndef _GETOPT_H_\r
+#define _GETOPT_H_\r
+\r
+extern int opterr;\r
+extern int optind;\r
+extern int optopt;\r
+extern int optreset;\r
+extern char *optarg;\r
+\r
+extern int getopt(int nargc, char *const *nargv, const char *ostr);\r
+\r
+#endif                         /* _GETOPT_H_ */\r
diff --git a/src/bin/jp3d/jp3d_to_volume.c b/src/bin/jp3d/jp3d_to_volume.c
new file mode 100755 (executable)
index 0000000..7afb448
--- /dev/null
@@ -0,0 +1,540 @@
+/*\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) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain\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 <math.h>\r
+\r
+#include "openjp3d.h"\r
+#include "getopt.h"\r
+#include "convert.h"\r
+\r
+#ifdef _WIN32\r
+#include <windows.h>\r
+#else\r
+#define stricmp strcasecmp\r
+#define strnicmp strncasecmp\r
+#endif /* _WIN32 */\r
+\r
+/* ----------------------------------------------------------------------- */\r
+static double calc_PSNR(opj_volume_t *original, opj_volume_t *decoded)\r
+{\r
+       int max, i, k, compno = 0, size;\r
+       double sum, total = 0;\r
+       int global = 1;\r
+    \r
+       max = (original->comps[compno].prec <= 8) ? 255 : (1 << original->comps[compno].prec) - 1;\r
+       if (global) {\r
+               size = (original->x1 - original->x0) * (original->y1 - original->y0) * (original->z1 - original->z0);\r
+\r
+               for (compno = 0; compno < original->numcomps; compno++) {\r
+                       for(sum = 0, i = 0; i < size; ++i) {\r
+                               if ((decoded->comps[compno].data[i] < 0) || (decoded->comps[compno].data[i] > max))\r
+                                       fprintf(stdout,"[WARNING] Data out of range during PSNR computing...\n");\r
+                               else\r
+                                       sum += (original->comps[compno].data[i] - decoded->comps[compno].data[i]) * (original->comps[compno].data[i] - decoded->comps[compno].data[i]);        \r
+                       }\r
+               }\r
+               sum /= size;\r
+               total = ((sum==0.0) ? 0.0 : 10 * log10(max * max / sum));\r
+       } else {\r
+               size = (original->x1 - original->x0) * (original->y1 - original->y0);\r
+\r
+               for (k = 0; k < original->z1 - original->z0; k++) {\r
+                       int offset = k * size;\r
+                       for (sum = 0, compno = 0; compno < original->numcomps; compno++) {\r
+                               for(i = 0; i < size; ++i) {\r
+                                       if ((decoded->comps[compno].data[i + offset] < 0) || (decoded->comps[compno].data[i + offset] > max))\r
+                                               fprintf(stdout,"[WARNING] Data out of range during PSNR computing...\n");\r
+                                       else\r
+                                               sum += (original->comps[compno].data[i + offset] - decoded->comps[compno].data[i + offset]) * (original->comps[compno].data[i + offset] - decoded->comps[compno].data[i + offset]);        \r
+                               }\r
+                       }\r
+                       sum /= size;\r
+                       total = total + ((sum==0.0) ? 0.0 : 10 * log10(max * max / sum));\r
+               }\r
+\r
+       }\r
+       if(total == 0) /* perfect reconstruction, PSNR should return infinity */\r
+               return -1.0;\r
+       \r
+       return total;\r
+       //return 20 * log10((max - 1) / sqrt(sum));\r
+}\r
+\r
+static double calc_SSIM(opj_volume_t *original, opj_volume_t *decoded)\r
+{\r
+       int max, i, compno = 0, size, sizeM;\r
+       double sum;\r
+       double mux = 0.0, muy = 0.0, sigmax = 0.0, sigmay = 0.0,\r
+               sigmaxy = 0.0, structx = 0.0, structy = 0.0;\r
+       double lcomp,ccomp,scomp;\r
+       double C1,C2,C3;\r
+\r
+       max = (original->comps[compno].prec <= 8) ? 255 : (1 << original->comps[compno].prec) - 1;\r
+       size = (original->x1 - original->x0) * (original->y1 - original->y0) * (original->z1 - original->z0);\r
+\r
+       //MSSIM\r
+\r
+//     sizeM = size / (original->z1 - original->z0);\r
+\r
+       sizeM = size;   \r
+       for(sum = 0, i = 0; i < sizeM; ++i) {\r
+               // First, the luminance of each signal is compared.\r
+               mux += original->comps[compno].data[i];\r
+               muy += decoded->comps[compno].data[i];\r
+       }\r
+       mux /= sizeM;\r
+       muy /= sizeM;\r
+       \r
+       //We use the standard deviation (the square root of variance) as an estimate of the signal contrast.\r
+    for(sum = 0, i = 0; i < sizeM; ++i) {\r
+               // First, the luminance of each signal is compared.\r
+               sigmax += (original->comps[compno].data[i] - mux) * (original->comps[compno].data[i] - mux);\r
+               sigmay += (decoded->comps[compno].data[i] - muy) * (decoded->comps[compno].data[i] - muy);\r
+               sigmaxy += (original->comps[compno].data[i] - mux) * (decoded->comps[compno].data[i] - muy);\r
+       }\r
+       sigmax /= sizeM - 1;\r
+       sigmay /= sizeM - 1;\r
+       sigmaxy /= sizeM - 1;\r
+       \r
+       sigmax = sqrt(sigmax);\r
+       sigmay = sqrt(sigmay);\r
+       sigmaxy = sqrt(sigmaxy);\r
+\r
+       //Third, the signal is normalized (divided) by its own standard deviation, \r
+       //so that the two signals being compared have unit standard deviation.\r
+\r
+       //Luminance comparison\r
+       C1 = (0.01 * max) * (0.01 * max);\r
+       lcomp = ((2 * mux * muy) + C1)/((mux*mux) + (muy*mux) + C1);\r
+       //Constrast comparison\r
+       C2 = (0.03 * max) * (0.03 * max);\r
+       ccomp = ((2 * sigmax * sigmay) + C2)/((sigmax*sigmax) + (sigmay*sigmay) + C2);\r
+       //Structure comparison\r
+       C3 = C2 / 2;\r
+       scomp = (sigmaxy + C3) / (sigmax * sigmay + C3);\r
+       //Similarity measure\r
+\r
+       sum = lcomp * ccomp * scomp;\r
+       return sum;\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
+       fprintf(stdout,"List of parameters for the JPEG 2000 encoder:\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout," Required arguments \n");\r
+       fprintf(stdout," ---------------------------- \n");\r
+       fprintf(stdout,"  -i <compressed file> ( *.jp3d, *.j3d )\n");\r
+       fprintf(stdout,"    Currently accepts J3D-files. The file type is identified based on its suffix.\n");\r
+       fprintf(stdout,"  -o <decompressed file> ( *.pgx, *.bin )\n");\r
+       fprintf(stdout,"    Currently accepts PGX-files and BIN-files. Binary data is written to the file (not ascii). \n");\r
+       fprintf(stdout,"    If a PGX filename is given, there will be as many output files as slices; \n");\r
+       fprintf(stdout,"    an indice starting from 0 will then be appended to the output filename,\n");\r
+       fprintf(stdout,"    just before the \"pgx\" extension.\n");\r
+       fprintf(stdout,"  -m <characteristics file> ( *.img ) \n");\r
+       fprintf(stdout,"    Required only for BIN-files. Ascii data of volume characteristics is written. \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout," Optional  \n");\r
+       fprintf(stdout," ---------------------------- \n");\r
+       fprintf(stdout,"  -h \n ");\r
+       fprintf(stdout,"    Display the help information\n");\r
+       fprintf(stdout,"  -r <RFx,RFy,RFz>\n");\r
+       fprintf(stdout,"    Set the number of highest resolution levels to be discarded on each dimension. \n");\r
+       fprintf(stdout,"    The volume 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
+       fprintf(stdout,"  -O original-file \n");\r
+    fprintf(stdout,"    This option offers the possibility to compute some quality results  \n");\r
+       fprintf(stdout,"    for the decompressed volume, like the PSNR value achieved or the global SSIM value.  \n");\r
+       fprintf(stdout,"    Needs the original file in order to compare with the new one.\n");\r
+    fprintf(stdout,"    NOTE: Only valid when -r option is 0,0,0 (both original and decompressed volumes have same resolutions) \n");\r
+    fprintf(stdout,"    NOTE: If original file is .BIN file, the volume characteristics file shall be defined with the -m option. \n");\r
+       fprintf(stdout,"    (i.e. -O original-BIN-file -m original-IMG-file) \n");\r
+       fprintf(stdout,"  -BE \n");\r
+       fprintf(stdout,"    Define that the recovered volume data will be saved with big endian byte order.\n");\r
+       fprintf(stdout,"    By default, little endian byte order is used.\n");\r
+       fprintf(stdout,"\n");\r
+}\r
+\r
+/* -------------------------------------------------------------------------- */\r
+\r
+int get_file_format(char *filename) {\r
+       int i;\r
+       static const char *extension[] = {"pgx", "bin", "j3d", "jp3d", "j2k", "img"};\r
+       static const int format[] = { PGX_DFMT, BIN_DFMT, J3D_CFMT, J3D_CFMT, J2K_CFMT, IMG_DFMT};\r
+       char * ext = strrchr(filename, '.');\r
+       if(ext) {\r
+               ext++;\r
+               for(i = 0; i < sizeof(format) / sizeof(format[0]); 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
+int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters) {\r
+       /* parse the command line */\r
+\r
+       while (1) {\r
+               int c = getopt(argc, argv, "i:o:O:r:l:B:m:h");\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 J3D_CFMT:\r
+                                       case J2K_CFMT:\r
+                                               break;\r
+                                       default:\r
+                                               fprintf(stdout, "[ERROR] Unknown format for infile %s [only *.j3d]!! \n", infile);\r
+                                               return 1;\r
+                                               break;\r
+                               }\r
+                               strncpy(parameters->infile, infile, MAX_PATH);\r
+                               fprintf(stdout, "[INFO] Infile: %s \n", parameters->infile);\r
+\r
+                       }\r
+                       break;\r
+\r
+                       case 'm':                       /* img file */\r
+                       {\r
+                               char *imgfile = optarg;\r
+                               int imgformat = get_file_format(imgfile);\r
+                               switch(imgformat) {\r
+                                       case IMG_DFMT:\r
+                                               break;\r
+                                       default:\r
+                                               fprintf(stdout, "[ERROR] Unrecognized format for imgfile : %s [accept only *.img] !!\n\n", imgfile);\r
+                                               return 1;\r
+                                               break;\r
+                               }\r
+                               strncpy(parameters->imgfile, imgfile, MAX_PATH);\r
+                               fprintf(stdout, "[INFO] Imgfile: %s Format: %d\n", parameters->imgfile, imgformat);\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 BIN_DFMT:\r
+                                               break;\r
+                                       default:\r
+                                               fprintf(stdout, "[ERROR] Unrecognized format for outfile : %s [accept only *.pgx or *.bin] !!\n\n", outfile);\r
+                                               return 1;\r
+                                               break;\r
+                               }\r
+                               strncpy(parameters->outfile, outfile, MAX_PATH);\r
+                               fprintf(stdout, "[INFO] Outfile: %s \n", parameters->outfile);\r
+\r
+                       }\r
+                       break;\r
+                       \r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'O':               /* Original image for PSNR computing */\r
+                       {\r
+                               char *original = optarg;\r
+                               parameters->orig_format = get_file_format(original);\r
+                               switch(parameters->orig_format) {\r
+                                       case PGX_DFMT:\r
+                                       case BIN_DFMT:\r
+                                               break;\r
+                                       default:\r
+                                               fprintf(stdout, "[ERROR] Unrecognized format for original file : %s [accept only *.pgx or *.bin] !!\n\n", original);\r
+                                               return 1;\r
+                                               break;\r
+                               }\r
+                               strncpy(parameters->original, original, MAX_PATH);\r
+                               fprintf(stdout, "[INFO] Original file: %s \n", parameters->original);\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+           \r
+                       case 'r':               /* reduce option */\r
+                       {\r
+                               //sscanf(optarg, "%d, %d, %d", &parameters->cp_reduce[0], &parameters->cp_reduce[1], &parameters->cp_reduce[2]);\r
+                               int aux;\r
+                               aux = sscanf(optarg, "%d,%d,%d", &parameters->cp_reduce[0], &parameters->cp_reduce[1], &parameters->cp_reduce[2]);\r
+                               if (aux == 2) \r
+                                       parameters->cp_reduce[2] = 0;\r
+                               else if (aux == 1) {\r
+                                       parameters->cp_reduce[1] = parameters->cp_reduce[0];\r
+                                       parameters->cp_reduce[2] = 0;\r
+                               }else if (aux == 0){\r
+                                       parameters->cp_reduce[0] = 0;\r
+                                       parameters->cp_reduce[1] = 0;\r
+                                       parameters->cp_reduce[2] = 0;\r
+                               }\r
+                       }\r
+                       break;\r
+                       \r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'l':               /* layering option */\r
+                       {\r
+                               sscanf(optarg, "%d", &parameters->cp_layer);\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'B':               /* BIGENDIAN vs. LITTLEENDIAN */\r
+                       {\r
+                               parameters->bigendian = 1;\r
+                       }\r
+                       break;\r
+                       \r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'L':               /* BIGENDIAN vs. LITTLEENDIAN */\r
+                       {\r
+                               parameters->decod_format = LSE_CFMT;\r
+                       }\r
+                       break;\r
+                       \r
+                       /* ----------------------------------------------------- */\r
+                       \r
+                       case 'h':                       /* display an help description */\r
+                       {\r
+                               decode_help_display();\r
+                               return 1;\r
+                       }\r
+                       break;\r
+            \r
+                               /* ----------------------------------------------------- */\r
+                       \r
+                       default:\r
+                               fprintf(stdout,"[WARNING] This option is not valid \"-%c %s\"\n",c, optarg);\r
+                               break;\r
+               }\r
+       }\r
+\r
+       /* check for possible errors */\r
+\r
+       if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {\r
+               fprintf(stdout,"[ERROR] At least one required argument is missing\n Check jp3d_to_volume -help for usage information\n");\r
+               return 1;\r
+       }\r
+\r
+       return 0;\r
+}\r
+\r
+/* -------------------------------------------------------------------------- */\r
+\r
+/**\r
+sample error callback expecting a FILE* client object\r
+*/\r
+void error_callback(const char *msg, void *client_data) {\r
+       FILE *stream = (FILE*)client_data;\r
+       fprintf(stream, "[ERROR] %s", msg);\r
+}\r
+/**\r
+sample warning callback expecting a FILE* client object\r
+*/\r
+void warning_callback(const char *msg, void *client_data) {\r
+       FILE *stream = (FILE*)client_data;\r
+       fprintf(stream, "[WARNING] %s", msg);\r
+}\r
+/**\r
+sample debug callback expecting no client object\r
+*/\r
+void info_callback(const char *msg, void *client_data) {\r
+       fprintf(stdout, "[INFO] %s", msg);\r
+}\r
+\r
+/* -------------------------------------------------------------------------- */\r
+\r
+int main(int argc, char **argv) {\r
+\r
+       opj_dparameters_t parameters;   /* decompression parameters */\r
+       opj_event_mgr_t event_mgr;              /* event manager */\r
+       opj_volume_t *volume = NULL;\r
+\r
+       opj_volume_t *original = NULL;\r
+       opj_cparameters_t cparameters;  /* original parameters */\r
+\r
+       FILE *fsrc = NULL;\r
+       unsigned char *src = NULL; \r
+       int file_length;\r
+       int decodeok;\r
+       double psnr, ssim;\r
+\r
+       opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */\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 = error_callback;\r
+       event_mgr.warning_handler = warning_callback;\r
+       event_mgr.info_handler = info_callback;\r
+\r
+       /* set decoding parameters to default values */\r
+       opj_set_default_decoder_parameters(&parameters);\r
+\r
+    /* parse input and get user decoding parameters */\r
+       strcpy(parameters.original,"NULL");\r
+       strcpy(parameters.imgfile,"NULL");\r
+       if(parse_cmdline_decoder(argc, argv, &parameters) == 1) {\r
+               return 0;\r
+       }\r
+       \r
+       /* read the input file and put it in memory */\r
+       /* ---------------------------------------- */\r
+       fprintf(stdout, "[INFO] Loading %s file \n",parameters.decod_format==J3D_CFMT ? ".jp3d" : ".j2k");\r
+       fsrc = fopen(parameters.infile, "rb");\r
+       if (!fsrc) {\r
+               fprintf(stdout, "[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
+       \r
+       /* decode the code-stream */\r
+       /* ---------------------- */\r
+       if (parameters.decod_format == J3D_CFMT || parameters.decod_format == J2K_CFMT) {               \r
+               /* get a JP3D or J2K decoder handle */\r
+               if (parameters.decod_format == J3D_CFMT) \r
+                       dinfo = opj_create_decompress(CODEC_J3D);\r
+               else if (parameters.decod_format == J2K_CFMT) \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, 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, file_length);\r
+\r
+               /* decode the stream and fill the volume structure */\r
+               volume = opj_decode(dinfo, cio);\r
+               if(!volume) {\r
+                       fprintf(stdout, "[ERROR] jp3d_to_volume: failed to decode volume!\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
+       /* free the memory containing the code-stream */\r
+       free(src);\r
+       src = NULL;\r
+\r
+       /* create output volume */\r
+       /* ------------------- */\r
+\r
+       switch (parameters.cod_format) {\r
+               case PGX_DFMT:                  /* PGX */\r
+                       decodeok = volumetopgx(volume, parameters.outfile);\r
+                       if (decodeok)\r
+                               fprintf(stdout,"[ERROR] Unable to write decoded volume into pgx files\n");\r
+                       break;\r
+               \r
+               case BIN_DFMT:                  /* BMP */\r
+                       decodeok = volumetobin(volume, parameters.outfile);\r
+                       if (decodeok)\r
+                               fprintf(stdout,"[ERROR] Unable to write decoded volume into pgx files\n");\r
+                       break;\r
+       }\r
+       switch (parameters.orig_format) {\r
+               case PGX_DFMT:                  /* PGX */\r
+                       if (strcmp("NULL",parameters.original) != 0){\r
+                               fprintf(stdout,"Loading original file %s \n",parameters.original);\r
+                               cparameters.subsampling_dx = 1; cparameters.subsampling_dy = 1; cparameters.subsampling_dz = 1;\r
+                               cparameters.volume_offset_x0 = 0;cparameters.volume_offset_y0 = 0;cparameters.volume_offset_z0 = 0;\r
+                               original = pgxtovolume(parameters.original,&cparameters);\r
+                       }\r
+                       break;\r
+               \r
+               case BIN_DFMT:                  /* BMP */\r
+                       if (strcmp("NULL",parameters.original) != 0 && strcmp("NULL",parameters.imgfile) != 0){\r
+                               fprintf(stdout,"Loading original file %s %s\n",parameters.original,parameters.imgfile);\r
+                               cparameters.subsampling_dx = 1; cparameters.subsampling_dy = 1; cparameters.subsampling_dz = 1;\r
+                               cparameters.volume_offset_x0 = 0;cparameters.volume_offset_y0 = 0;cparameters.volume_offset_z0 = 0;\r
+                               original = bintovolume(parameters.original,parameters.imgfile,&cparameters);\r
+                       }\r
+                       break;\r
+       }\r
+\r
+       fprintf(stdout, "[RESULT] Volume: %d x %d x %d (x %d bpv)\n ", \r
+                        (volume->comps[0].w >> volume->comps[0].factor[0]),\r
+                        (volume->comps[0].h >> volume->comps[0].factor[1]),\r
+                        (volume->comps[0].l >> volume->comps[0].factor[2]),volume->comps[0].prec);\r
+\r
+       if(original){\r
+               psnr = calc_PSNR(original,volume);\r
+               ssim = calc_SSIM(original,volume);\r
+               if (psnr < 0.0)\r
+                       fprintf(stdout, "  PSNR: Inf , SSMI %f -- Perfect reconstruction!\n",ssim);\r
+               else\r
+                       fprintf(stdout, "  PSNR: %f , SSIM %f \n",psnr,ssim);\r
+       }\r
+       /* free remaining structures */\r
+       if(dinfo) {\r
+               opj_destroy_decompress(dinfo);\r
+       }\r
+\r
+       /* free volume data structure */\r
+       opj_volume_destroy(volume);\r
+   \r
+       return 0;\r
+}\r
+\r
diff --git a/src/bin/jp3d/tcltk/LPI_JP3D_VM.tcl b/src/bin/jp3d/tcltk/LPI_JP3D_VM.tcl
new file mode 100755 (executable)
index 0000000..37657b2
--- /dev/null
@@ -0,0 +1,115 @@
+#!/bin/sh
+# The next line is executed by /bin/sh, but not tcl \
+exec wish "$0" ${1+"$@"}
+lappend auto_path /usr/share/tcltk/bwidget1.9.2
+
+namespace eval jp3dVM {
+
+    variable _progress 0
+    variable _afterid  ""
+    variable _status "Compute in progress..."
+    variable notebook
+    variable mainframe
+    variable dataout "Process execution information"
+    variable status
+    variable prgtext
+    variable prgindic
+
+    set pwd [pwd]
+    cd [file dirname [info script]]
+    variable VMDIR [pwd]
+    cd $pwd
+
+    foreach script {encoder.tcl decoder.tcl} {
+       namespace inscope :: source $VMDIR/$script
+    }
+}
+
+
+proc jp3dVM::create { } {
+    variable notebook
+    variable mainframe
+    variable dataout
+
+    bind all <F12> { catch {console show} }
+
+    # Menu description
+    set descmenu {
+        "&File" {} {} 0 {
+            {command "E&xit" {} "Exit BWidget jp3dVM" {} -command exit}
+        }
+        "&Options" {} {} 0 {
+            {command "&Encode" {} "Show encoder" {}
+                -command  {$jp3dVM::notebook raise [$jp3dVM::notebook page 0]}
+            }
+            {command "&Decode" {} "Show decoder" {}
+                -command  {$jp3dVM::notebook raise [$jp3dVM::notebook page 1]}
+            }
+        }
+       "&Help" {} {} 0 {
+            {command "&About authors..." {} "Show info about authors" {} 
+               -command {MessageDlg .msgdlg -parent . -title "About authors" -message " Copyright @ LPI-UVA 2006 " -type ok -icon info}}
+        }
+    }
+
+    set mainframe [MainFrame .mainframe \
+                       -menu         $descmenu \
+                       -textvariable jp3dVM::status \
+                       -progressvar  jp3dVM::prgindic]
+
+    $mainframe addindicator -text "JP3D Verification Model 1.0.0"
+
+    # NoteBook creation
+    set frame    [$mainframe getframe]
+    set notebook [NoteBook $frame.nb]
+
+    set logo [frame $frame.logo]
+    #creo imagen logo
+    image create photo LPIimg -file logoLPI.gif
+    set logoimg [Label $logo.logoimg -image LPIimg]
+    
+    set f0  [VMEncoder::create $notebook]
+    set f1  [VMDecoder::create $notebook]
+
+       set tfinfo [TitleFrame $frame.codinfo -text "Program Execution"]
+       set codinfo [$tfinfo getframe]
+       set sw [ScrolledWindow $codinfo.sw -relief sunken -borderwidth 2 -scrollbar both]
+       set sf [ScrollableFrame $codinfo.sf ]
+       $sw setwidget $sf
+       set subf [$sf getframe]
+       set labinfo [label $subf.labinfo -textvariable jp3dVM::dataout -justify left]
+
+       pack $labinfo -side left 
+       pack $sw 
+
+    $notebook compute_size
+    $notebook raise [$notebook page 0]
+
+    pack $logoimg -side left -fill x -expand yes 
+    pack $notebook -expand yes 
+    pack $logo $tfinfo -side left -expand yes 
+    pack $mainframe -fill both -expand yes
+    update idletasks
+}
+
+
+proc jp3dVM::main {} {
+    variable VMDIR
+
+    lappend ::auto_path [file dirname $VMDIR]
+    namespace inscope :: package require BWidget
+
+    option add *TitleFrame.l.font {helvetica 11 bold italic}
+
+    wm withdraw .
+    wm title . "JP3D Verification Model @ LPI"
+
+    jp3dVM::create
+    BWidget::place . 0 0 center
+    wm deiconify .
+    raise .
+    focus -force .
+}
+
+jp3dVM::main
+wm geom . [wm geom .]
diff --git a/src/bin/jp3d/tcltk/README b/src/bin/jp3d/tcltk/README
new file mode 100644 (file)
index 0000000..f4e2e35
--- /dev/null
@@ -0,0 +1,13 @@
+HOWTO USE THE TCL/TK APP IN 'jp3d/tcltk'
+----------------------------------------
+1. Download the 'BWidget-1.9.2'
+    http://www.sourceforge.net/projects/tcllib/
+
+2. Install it e.g. in '/usr/local/BWidget-1.9.2/'
+3. Add the lappend command in line 4
+  to jp3d/tcltk/LPI_JP3D_VM.tcl:
+
+#!/bin/sh
+# The next line is executed by /bin/sh, but not tcl \
+exec wish "$0" ${1+"$@"}
+lappend auto_path /usr/local/BWidget-1.9.2
diff --git a/src/bin/jp3d/tcltk/Thumbs.db b/src/bin/jp3d/tcltk/Thumbs.db
new file mode 100755 (executable)
index 0000000..5d6ffdf
Binary files /dev/null and b/src/bin/jp3d/tcltk/Thumbs.db differ
diff --git a/src/bin/jp3d/tcltk/decoder.tcl b/src/bin/jp3d/tcltk/decoder.tcl
new file mode 100755 (executable)
index 0000000..98edcde
--- /dev/null
@@ -0,0 +1,272 @@
+\r
+namespace eval VMDecoder {\r
+       variable var\r
+       variable JP3Ddecoder "../bin/jp3d_to_volume.exe"\r
+       #variable JP3Ddecoder "jp3d_to_volume.exe"\r
+}\r
+\r
+\r
+proc VMDecoder::create { nb } {\r
+       variable var\r
+\r
+       set frameD [$nb insert end VMDecoder -text "Decoder"]\r
+       set topfD       [frame $frameD.topfD]\r
+       set medfD       [frame $frameD.medfD]\r
+       set bottomfD    [frame $frameD.bottomfD]\r
+       set srcfD [TitleFrame $topfD.srcfD -text "Source"]\r
+       set dstfD [TitleFrame $topfD.dstfD -text "Destination"]\r
+       set paramfD [TitleFrame $medfD.paramfD -text "Decoding parameters"]\r
+       set infofD [TitleFrame $medfD.infofD -text "Distortion measures"]\r
+\r
+       set frame1 [$srcfD getframe]\r
+       _sourceD  $frame1\r
+       set frame2  [$dstfD getframe]\r
+       _destinationD  $frame2\r
+       set frame3  [$infofD getframe]\r
+       _originalD $frame3\r
+       set frame4  [$paramfD getframe]\r
+       _paramsD $frame4\r
+\r
+       set butD   [Button $bottomfD.butD -text "Decode!" \\r
+                  -command  "VMDecoder::_decode $frame1 $frame2 $frame3" \\r
+                  -helptext "Decoding trigger button"]\r
+       set butR   [Button $bottomfD.butR -text "Save info" \\r
+                  -command  "VMDecoder::_save $frame3" \\r
+                  -helptext "Save information"]\r
+       \r
+       pack $srcfD $dstfD -side left -fill both -padx 10 -ipadx 5 -expand yes\r
+       pack $topfD -pady 4 -fill x\r
+       \r
+       pack $paramfD $infofD -side left -fill both -padx 10 -pady 2 -ipadx 5 -expand yes\r
+       pack $medfD -pady 4 -fill x \r
+\r
+       pack $butD $butR -side left -padx 4 -pady 5 -expand yes\r
+       pack $bottomfD -pady 4 -fill x\r
+\r
+return $frameD\r
+}\r
+\r
+\r
+proc fileDialogD {w ent operation} {\r
+\r
+       variable file\r
+       \r
+       if {$operation == "open"} {\r
+               #-----Type names---------Extension(s)---\r
+               set types {\r
+               {"JP3D Files"      {.jp3d}      }\r
+               {"All files"            *}\r
+               }\r
+               set file [tk_getOpenFile -filetypes $types -parent $w ]\r
+       } elseif {$operation == "original"} {\r
+               #-----Type names---------Extension(s)---\r
+               set types {\r
+               {"BIN Raw Image Files"  {.bin}  }\r
+               {"PGX Raw Image Files"  {.pgx}  }\r
+               {"All files"            *}\r
+               }\r
+               set file [tk_getOpenFile -filetypes $types -parent $w ]\r
+       } else {\r
+               #-----Type names---------Extension(s)---\r
+               set types {\r
+               {"BIN Raw Image Files"  {.bin}  }\r
+               {"PGX Raw Image Files"  {.pgx}  }\r
+               {"All files"            *}\r
+               }\r
+               set file [tk_getSaveFile -filetypes $types -parent $w -initialfile Untitled -defaultextension "*.bin"]\r
+       }\r
+       if {[string compare $file ""]} {\r
+               $ent delete 0 end\r
+               $ent insert end $file\r
+               $ent xview moveto 1\r
+       }\r
+}\r
+\r
+proc VMDecoder::_sourceD { parent } {\r
+       \r
+       variable var\r
+       \r
+       set labsrcD [LabelFrame $parent.labsrcD -text "Select compressed file: " -side top \\r
+                       -anchor w -relief flat -borderwidth 0]\r
+       set subsrcD [$labsrcD getframe]\r
+       set listD [entry $subsrcD.entrysrcD -width 40 -textvariable VMDecoder::var(sourceD)]\r
+       \r
+       set labbrw [LabelFrame $parent.labbrw -side top -anchor w -relief flat -borderwidth 0]\r
+       set subbrw [$labbrw getframe]\r
+       set butbrw [button $subbrw.butbrw -image [Bitmap::get open] \\r
+               -relief raised -borderwidth 1 -padx 1 -pady 1 \\r
+               -command "fileDialogD . $subsrcD.entrysrcD open"]\r
+       \r
+       pack $listD -side top\r
+       pack $butbrw -side top\r
+       pack $labsrcD $labbrw -side left -fill both -expand yes\r
+\r
+\r
+}\r
+\r
+proc VMDecoder::_destinationD { parent } {\r
+       \r
+       variable var\r
+       \r
+       set labdstD [LabelFrame $parent.labdstD -text "Save decompressed volume file(s) as: " -side top \\r
+                       -anchor w -relief flat -borderwidth 0]\r
+       set subdstD [$labdstD getframe]\r
+       set listD [entry $subdstD.entrydstD -width 40 -textvariable VMDecoder::var(destinationD)]\r
+       \r
+       set labbrw [LabelFrame $parent.labbrw -side top -anchor w -relief flat -borderwidth 0]\r
+       set subbrw [$labbrw getframe]\r
+       set butbrw [button $subbrw.butbrw -image [Bitmap::get save] \\r
+               -relief raised -borderwidth 1 -padx 1 -pady 1 \\r
+               -command "fileDialogD . $subdstD.entrydstD save"]\r
+\r
+       pack $listD -side top\r
+       pack $butbrw -side top\r
+       pack $labdstD $labbrw -side left -fill both -expand yes\r
+}\r
+\r
+proc VMDecoder::_originalD { parent } {\r
+       \r
+       variable var\r
+       \r
+       set laborgD [LabelFrame $parent.laborgD -text "Select original file: " -side top \\r
+                       -anchor w -relief flat -borderwidth 0]\r
+       set suborgD [$laborgD getframe]\r
+       set listorgD [entry $suborgD.entryorgD -width 30 -textvariable VMDecoder::var(originalD)]\r
+       \r
+       set labbrw2 [LabelFrame $parent.labbrw2 -side top -anchor w -relief flat -borderwidth 0]\r
+       set subbrw2 [$labbrw2 getframe]\r
+       set butbrw2 [button $subbrw2.butbrw2 -image [Bitmap::get open] \\r
+               -relief raised -borderwidth 1 -padx 1 -pady 1 \\r
+               -command "fileDialogD . $suborgD.entryorgD original"]\r
+       \r
+       set infoD [Label $parent.infoD -relief sunken -textvariable VMDecoder::var(decodinfo) -justify left]\r
+\r
+       pack $listorgD -side left -anchor n\r
+       pack $butbrw2 -side left -anchor n\r
+       pack $infoD -side bottom -anchor nw -pady 4 -ipadx 150 -ipady 20 -expand yes\r
+       pack $laborgD $labbrw2 -side left -fill both \r
+\r
+\r
+}\r
+\r
+proc VMDecoder::_paramsD { parent } {\r
+       \r
+       variable var\r
+       \r
+       ########### DECODING  #############\r
+       set labcod [LabelFrame $parent.labcod -side top -anchor w -relief sunken -borderwidth 1]\r
+       set subcod  [$labcod getframe]\r
+\r
+               set frameres [frame $subcod.frameres -borderwidth 1]\r
+               set labres [LabelEntry $frameres.labres -label "Resolutions to discard: " -labelwidth 20 -labelanchor w \\r
+                   -textvariable VMDecoder::var(resdiscard) -editable 1 \\r
+                   -helptext "Number of highest resolution levels to be discarded on each dimension" ]\r
+       set VMDecoder::var(resdiscard) "0,0,0"\r
+       \r
+               set framelayer [frame $subcod.framelayer -borderwidth 1]\r
+               set lablayer [LabelEntry $framelayer.lablayer -label "Layers to decode: " -labelwidth 20 -labelanchor w \\r
+                   -textvariable VMDecoder::var(layer) -editable 1 \\r
+                   -helptext "Maximum number of quality layers to decode" ]\r
+       set VMDecoder::var(layer) "All"\r
+\r
+       set framebe [frame $subcod.framebe -borderwidth 1]\r
+       set chkbe [checkbutton $framebe.chkbe -text "Write decoded file with BigEndian byte order" \\r
+                  -variable VMDecoder::var(be) -onvalue 1 -offvalue 0 ]\r
+\r
+               pack $labres -side left -padx 2 -anchor n\r
+               pack $lablayer -side left -padx 2 -anchor n\r
+               pack $chkbe -side left -padx 2 -anchor w\r
+               pack $frameres $framelayer $framebe -side top -anchor w\r
+\r
+       pack $subcod -anchor n\r
+       pack $labcod -side left -fill both -padx 4 -expand yes\r
+}\r
+\r
+\r
+proc VMDecoder::_decode { framesrc framedst frameinfo} {\r
+\r
+       variable var\r
+\r
+       set sourceD [$framesrc.labsrcD.f.entrysrcD get ]\r
+       set destinationD [$framedst.labdstD.f.entrydstD get ]\r
+       set originD [$frameinfo.laborgD.f.entryorgD get ]\r
+       set cond1 [string match *.pgx [string tolower $destinationD]]\r
+       set cond2 [string match *\**.pgx [string tolower $destinationD]]\r
+       set cond3 [string match *.bin [string tolower $destinationD]]\r
+       \r
+       #comprobamos datos son correctos\r
+       if {($cond1 == 1) && ($cond2 == 0)} {\r
+               set pgx "*.pgx"\r
+               set pattern [string range $destinationD 0 [expr [string length $destinationD]-5]]\r
+               set destinationD $pattern$img\r
+       } elseif {$sourceD == ""} {\r
+         MessageDlg .msgdlg -parent . -message "Error : Source file is not defined !" -type ok -icon error \r
+       } elseif {$destinationD == ""} {\r
+         MessageDlg .msgdlg -parent . -message "Error : Destination file is not defined !" -type ok -icon error \r
+       } else {\r
+\r
+               #creamos datain a partir de los parametros de entrada\r
+               #set dirJP3Ddecoder [mk_relativepath $VMDecoder::JP3Ddecoder]\r
+               set dirJP3Ddecoder $VMDecoder::JP3Ddecoder\r
+               set datain [concat " $dirJP3Ddecoder -i [mk_relativepath $sourceD] "]\r
+               set datain [concat " $datain -o [mk_relativepath $destinationD] "]\r
+               if {$originD != ""} {\r
+                       set datain [concat " $datain -O [mk_relativepath $originD] "]\r
+                       if {$cond3 == 1} {\r
+                               set img ".img"\r
+                               set pattern [string range $originD 0 [expr [string length $originD]-5]]\r
+                               set pattern $pattern$img\r
+                               if {[file exists $pattern]} {\r
+                                 set datain [concat " $datain -m [mk_relativepath $pattern] "]\r
+                               } else {\r
+                                 MessageDlg .msgdlg -parent . -message "Error : IMG file associated to original BIN volume file not found in same directory !" -type ok -icon info \r
+                               }\r
+                       }\r
+               }\r
+               if {$VMDecoder::var(resdiscard) != "0,0,0"} {\r
+                       set datain [concat " $datain -r $VMDecoder::var(resdiscard) "]\r
+               }\r
+               if {$VMDecoder::var(layer) != "All" && $VMDecoder::var(layer) > 0} {\r
+                       set datain [concat " $datain -l $VMDecoder::var(layer) "]\r
+               }\r
+               if {$VMDecoder::var(be) == 1} {\r
+                       set datain [concat " $datain -BE"]\r
+               }\r
+               \r
+               set VMDecoder::var(progval) 10\r
+               ProgressDlg .progress -parent . -title "Wait..." \\r
+                       -type         infinite \\r
+                       -width        20 \\r
+                       -textvariable "Compute in progress..."\\r
+                       -variable     VMDecoder::progval \\r
+                       -stop         "Stop" \\r
+                       -command      {destroy .progress}\r
+\r
+               after 200 set VMDecoder::var(progval) 2\r
+\r
+               set fp [open "| $datain " r+] \r
+               fconfigure $fp -buffering line \r
+               set jp3dVM::dataout [concat "EXECUTED PROGRAM:\n\t$datain"]\r
+               while {-1 != [gets $fp tmp]} {\r
+                       set jp3dVM::dataout [concat "$jp3dVM::dataout\n$tmp"]\r
+               }\r
+               close $fp\r
+               destroy .progress\r
+               set cond [string first "ERROR" $jp3dVM::dataout]\r
+               set cond2 [string first "PSNR" $jp3dVM::dataout]\r
+               set cond3 [string first "RESULT" $jp3dVM::dataout]\r
+               if {$cond != -1} {\r
+                  MessageDlg .msgdlg -parent . -message [string range $jp3dVM::dataout [expr $cond-1] end] -type ok -icon error\r
+               } elseif {$cond3 != -1} {\r
+                       if {$cond2 != -1} {\r
+                               set VMDecoder::var(decodinfo) [string range $jp3dVM::dataout [expr $cond2-1] end]\r
+                       }\r
+                       MessageDlg .msgdlg -parent . -message [string range $jp3dVM::dataout [expr $cond3-1] end] -type ok -icon info\r
+               }\r
+       }\r
+}\r
+\r
+proc VMDecoder::_save { frameinfo } {\r
+\r
+}\r
+\r
diff --git a/src/bin/jp3d/tcltk/encoder.tcl b/src/bin/jp3d/tcltk/encoder.tcl
new file mode 100755 (executable)
index 0000000..6c4a508
--- /dev/null
@@ -0,0 +1,470 @@
+
+namespace eval VMEncoder {
+       variable var
+       variable JP3Dencoder "../bin/bin/volume_to_jp3d"
+}
+
+proc VMEncoder::create { nb } {
+
+       set frame [$nb insert end VMEncoder -text "Encoder"]
+       set topf        [frame $frame.topf]
+       set midf        [frame $frame.midf]
+       set bottomf     [frame $frame.bottomf]
+       set srcf [TitleFrame $topf.srcf -text "Source"]
+       set dstf [TitleFrame $topf.dstf -text "Destination"]
+       set Tparf [TitleFrame $midf.parfT -text "Transform Parameters"]
+       set Cparf [TitleFrame $midf.parfC -text "Coding Parameters"]
+
+       set frame1 [$srcf getframe]
+               VMEncoder::_sourceE  $frame1
+       
+       set frame2  [$dstf getframe]
+               VMEncoder::_destinationE  $frame2
+       
+       set frame3  [$Tparf getframe]
+               VMEncoder::_transformE $frame3
+
+       set frame4  [$Cparf getframe]
+               VMEncoder::_codingE $frame4
+       
+       set butE  [Button $bottomf.butE -text "Encode!" \
+                  -command  "VMEncoder::_encode $frame1 $frame2" \
+                  -helptext "Encoding trigger button"]
+       set butR  [Button $bottomf.butR -text "Restore defaults" \
+                  -command  "VMEncoder::_reset $frame1 $frame2 $frame3 $frame4" \
+                  -helptext "Reset to default values"]
+
+       pack $srcf $dstf -side left -fill y -padx 4 -expand yes
+       pack $topf -pady 2 -fill x
+
+       pack $Tparf $Cparf -side left -fill both -padx 4 -expand yes
+       pack $midf -pady 2 -fill x
+       
+       pack $butE $butR -side left -padx 40 -pady 5 -fill y -expand yes
+       pack $bottomf -pady 2 -fill x
+
+       return $frame
+}
+
+proc VMEncoder::_sourceE { parent } {
+
+       variable var
+
+       set labsrc [LabelFrame $parent.labsrc -text "Select volume file to encode: " -side top \
+                       -anchor w -relief flat -borderwidth 0]
+       set subsrc [$labsrc getframe]
+       set list [entry $subsrc.entrysrc -width 30 -textvariable VMDecoder::var(source)]
+       
+       set labbrw [LabelFrame $parent.labbrw -side top -anchor w -relief flat -borderwidth 0]
+       set subbrw [$labbrw getframe]
+       set butbrw [button $subbrw.butbrw -image [Bitmap::get open] \
+               -relief raised -borderwidth 1 -padx 1 -pady 1 \
+               -command "fileDialogE . $subsrc.entrysrc open"]
+       
+       pack $list -side top
+       pack $butbrw -side top
+       pack $labsrc $labbrw -side left -fill both -expand yes
+}
+
+proc VMEncoder::_destinationE { parent } {
+
+       variable var
+
+       set labdst [LabelFrame $parent.labdst -text "Save compressed volume as: " -side top \
+                       -anchor w -relief flat -borderwidth 0]
+       set subdst [$labdst getframe]
+       set list [entry $subdst.entrydst -width 30 -textvariable VMDecoder::var(destination)]
+       
+       set labbrw [LabelFrame $parent.labbrw -side top -anchor w -relief flat -borderwidth 0]
+       set subbrw [$labbrw getframe]
+       set butbrw [button $subbrw.butbrw -image [Bitmap::get save] \
+               -relief raised -borderwidth 1 -padx 1 -pady 1 \
+               -command "fileDialogE . $subdst.entrydst save"]
+       
+       pack $list -side top
+       pack $butbrw -side top
+       pack $labdst $labbrw -side left -fill both -expand yes
+}
+
+proc VMEncoder::_codingE { parent } {
+
+       
+       ########### CODING  #############
+       set labcod [LabelFrame $parent.labcod -side top -anchor w -relief sunken -borderwidth 1]
+       set subcod  [$labcod getframe]
+
+               set framerate [frame $subcod.framerate -borderwidth 1]
+               set labrate [LabelEntry $framerate.labrate -label "Rates: " -labelwidth 9 -labelanchor w \
+                   -textvariable VMEncoder::var(rate) -editable 1 \
+                   -helptext "Compression ratios for different layers (R1, R2, R3,...). If R=1, lossless coding" ]
+       set VMEncoder::var(rate) "1"
+
+               set framecblk [frame $subcod.framecblk -borderwidth 1]
+               set labcblk [LabelEntry $framecblk.labcblk -label "Codeblock: " -labelwidth 9 -labelanchor w \
+                   -textvariable VMEncoder::var(cblksize) -editable 1 \
+                   -helptext "Codeblock size (X, Y, Z)" ]
+       set VMEncoder::var(cblksize) "64,64,64"
+
+               set frametile [frame $subcod.frametile -borderwidth 1]
+               set labtile [LabelEntry $frametile.labtile -label "Tile size: " -labelwidth 9 -labelanchor w \
+                   -textvariable VMEncoder::var(tilesize) -editable 1 \
+                   -helptext "Tile size (X, Y, Z)" ]
+       set VMEncoder::var(tilesize) "512,512,512"
+
+               set framesop [frame $subcod.framesop -borderwidth 1]
+               set chksop [checkbutton $framesop.chksop -text "Write SOP marker" \
+                          -variable VMEncoder::var(sop) -onvalue 1 -offvalue 0 ]
+               set frameeph [frame $subcod.frameeph -borderwidth 1]
+               set chkeph [checkbutton $frameeph.chkeph -text "Write EPH marker" \
+                          -variable VMEncoder::var(eph) -onvalue 1 -offvalue 0 ]
+       
+               set framepoc [frame $subcod.framepoc -borderwidth 1]
+               set labpoc [label $framepoc.labpoc -text "Progression order: " ]
+               set progorder [ComboBox $framepoc.progorder \
+                          -text {Choose a progression order} \
+                          -width 10 \
+                          -textvariable VMEncoder::var(progorder) \
+                          -values {"LRCP" "RLCP" "RPCL" "PCRL" "CPRL"} \
+                          -helptext "Progression order"]
+               set VMEncoder::var(progorder) "LRCP"
+
+               pack $labrate -side left -padx 2 -anchor n
+               pack $labcblk -side left -padx 2 -anchor n
+               pack $labpoc $progorder -side left -padx 2 -anchor w
+               #pack $labtile -side left -padx 2 -anchor n
+               pack $chksop -side left -padx 2 -anchor w
+               pack $chkeph -side left -padx 2 -anchor w
+       ########### ENTROPY CODING  #############
+       set labent [LabelFrame $parent.labent -text "Entropy Coding" -side top -anchor w -relief sunken -borderwidth 1]
+       set subent  [$labent getframe]
+               foreach entval {2EB 3EB} entropy {2D_EBCOT 3D_EBCOT} {
+                       set rad [radiobutton $subent.$entval \
+                               -text $entropy \
+                               -variable VMEncoder::var(encoding) \
+                               -command "disableGR $entval $labcblk $progorder $labrate $chksop $chkeph" \
+                               -value $entval ]
+                       pack $rad -anchor w
+               }
+               $subent.2EB select 
+
+       pack $subent -padx 2 -anchor n
+
+       pack $framerate $framecblk $framepoc $framesop $frameeph -side top -anchor w
+       pack $subcod -anchor n
+
+       pack $labent $labcod -side left -fill both -padx 4 -expand yes
+
+
+}
+
+proc VMEncoder::_transformE { parent } {
+
+       variable var
+
+       ########### TRANSFORM  #############
+       set labtrf [LabelFrame $parent.labtrf -text "Transform" -side top -anchor w -relief sunken -borderwidth 1]
+       set subtrf  [$labtrf getframe]
+       set labres [LabelFrame $parent.labres -side top -anchor w -relief sunken -borderwidth 1]
+       set subres [$labres getframe]
+               
+               ########### ATK #############
+               set frameatk [frame $subres.frameatk -borderwidth 1]
+               set labatk [label $frameatk.labatk -text "Wavelet kernel:  " -anchor w]
+               set atk [ComboBox $frameatk.atk \
+                               -textvariable VMEncoder::var(atk) \
+                               -width 20 \
+                               -text {Choose a wavelet kernel} \
+                               -editable false \
+                               -values {"R5.3" "I9.7"} ]
+               set VMEncoder::var(atk) "R5.3"
+               pack $labatk $atk -side left -anchor w
+               ########### RESOLUTIONS #############
+               set frameres1 [frame $subres.frameres1 -borderwidth 1]
+               set labresolution [label $frameres1.labresol -text "Resolutions: " -anchor w ]
+               set frameres2 [frame $subres.frameres2 -borderwidth 1]
+               set labresX [label $frameres2.labresX -text "  X" -anchor w ]
+               set labresY [label $frameres2.labresY -text "  Y" -anchor w ]
+               set labresZ [label $frameres2.labresZ -text "  Z" -anchor w ]
+               
+
+               set resX [SpinBox $frameres2.spinresX \
+                               -range {1 6 1} -textvariable VMEncoder::var(resX) \
+                               -helptext "Number of resolutions in X" \
+                               -width 3 \
+                               -editable false ]
+               set resY [SpinBox $frameres2.spinresY \
+                               -range {1 6 1} -textvariable VMEncoder::var(resY) \
+                               -helptext "Number of resolutions in Y" \
+                               -width 3 \
+                               -editable false ]
+               set resZ [SpinBox $frameres2.spinresZ \
+                               -range {1 6 1} -textvariable VMEncoder::var(resZ) \
+                               -helptext "Number of resolutions in Z" \
+                               -width 3 \
+                               -editable false \
+                               -state disabled ]
+               set VMEncoder::var(resX) 3
+               set VMEncoder::var(resY) 3
+               set VMEncoder::var(resZ) 3
+
+               ########### TRF  #############
+               foreach trfval {2DWT 3DWT} trf {2D-DWT 3D-DWT} {
+                       set rad [radiobutton $subtrf.$trfval -text $trf \
+                                       -variable VMEncoder::var(transform) \
+                                       -command "disable3RLS $trfval $atk $resX $resY $resZ"\
+                                       -value $trfval ]
+                       pack $rad -anchor w
+               }
+               $subtrf.2DWT select
+               
+       pack $subtrf -side left -padx 2 -pady 4
+       
+               pack $labresolution -padx 2 -side left -anchor w
+               pack $labresX $resX -padx 2 -side left -anchor w
+               pack $labresY $resY -padx 2 -side left -anchor w
+               pack $labresZ $resZ -padx 2 -side left -anchor w
+
+               pack $frameres1 -side top -fill x
+               pack $frameres2 $frameatk -side top -padx 2 -pady 4 -anchor n
+
+       pack $subres -side left -padx 2 -pady 4
+       pack $labtrf $labres -side left -fill both -padx 4 -expand yes
+}
+
+
+proc VMEncoder::_encode { framesrc framedst } {
+
+       variable var
+
+       set source [$framesrc.labsrc.f.entrysrc get ]
+       set destination [$framedst.labdst.f.entrydst get ]
+       set cond1 [string match *.pgx [string tolower $source]]
+       set cond2 [string match *-*.pgx [string tolower $source]]
+       set cond3 [string match *.bin [string tolower $source]]
+
+       set img ".img"
+       set pattern [string range $source 0 [expr [string length $source]-5]]
+       set pattern $pattern$img
+       set exist [file exists $pattern]
+       
+       #comprobamos datos son correctos
+       if {($cond1 == 1) && ($cond2 == 0)} {
+         MessageDlg .msgdlg -parent . -message "Info : Really want to encode an slice instead of a volume?.\n For a group of .pgx slices, name must contain a - denoting a sequential index!" -type ok -icon info
+       } 
+       
+       if {$source == ""} {
+         MessageDlg .msgdlg -parent . -message "Error : Source file is not defined !" -type ok -icon error 
+       } elseif {$destination == ""} {
+         MessageDlg .msgdlg -parent . -message "Error : Destination file is not defined !" -type ok -icon error 
+       } elseif { ($VMEncoder::var(transform) != "3RLS") && ($VMEncoder::var(atk) == "Choose a wavelet transformation kernel") } {
+         MessageDlg .msgdlg -parent . -title "Info" -message "Please choose a wavelet transformation kernel"\
+                       -type ok -icon warning
+       } elseif {($exist == 0) && ($cond1 == 0) && ($cond3 == 1)} {
+                 MessageDlg .msgdlg -parent . -message "Error : IMG file associated to BIN volume file not found in same directory !" -type ok -icon info 
+       } else {
+
+               #creamos datain a partir de los parametros de entrada
+#              set dirJP3Dencoder [mk_relativepath $VMEncoder::JP3Dencoder]
+               set dirJP3Dencoder $VMEncoder::JP3Dencoder
+               set datain [concat " $dirJP3Dencoder -i [mk_relativepath $source] "]
+               if {$cond3 == 1} {
+                  set datain [concat " $datain -m [mk_relativepath $pattern] "]
+               }
+               set datain [concat " $datain -o [mk_relativepath $destination] "]
+               if {$VMEncoder::var(encoding) != "2EB"} {
+                       set datain [concat " $datain -C $VMEncoder::var(encoding) "]
+               }
+               if {$VMEncoder::var(transform) == "2DWT"} {
+                       set datain [concat " $datain -n $VMEncoder::var(resX),$VMEncoder::var(resY) "]
+               } elseif {$VMEncoder::var(transform) == "3DWT"} {
+                       set datain [concat " $datain -n $VMEncoder::var(resX),$VMEncoder::var(resY),$VMEncoder::var(resZ) "]
+               }
+               
+               set datain [concat " $datain -r $VMEncoder::var(rate) "]
+               
+               if {$VMEncoder::var(atk) == "I9.7"} {
+                       set datain [concat " $datain -I "]
+               } 
+               if {$VMEncoder::var(sop) == 1} {
+                       set datain [concat " $datain -SOP "]
+               }
+               if {$VMEncoder::var(eph) == 1} {
+                       set datain [concat " $datain -EPH "]
+               }
+               if {$VMEncoder::var(progorder) != "LRCP"} {
+                       set datain [concat " $datain -p $VMEncoder::var(progorder) "]
+               }
+               if {$VMEncoder::var(cblksize) != "64,64,64"} {
+                       set datain [concat " $datain -b $VMEncoder::var(cblksize) "]
+               }
+
+               
+               #Making this work would be great !!! 
+               set VMEncoder::var(progval) 10
+               ProgressDlg .progress -parent . -title "Wait..." \
+                       -type         infinite \
+                       -width        20 \
+                       -textvariable "Compute in progress..."\
+                       -variable     VMEncoder::progval \
+                       -stop         "Stop" \
+                       -command      {destroy .progress}
+               after 200 set VMEncoder::var(progval) 2
+               set fp [open "| $datain " r+] 
+               fconfigure $fp -buffering line 
+               set jp3dVM::dataout [concat "EXECUTED PROGRAM:\n\t$datain"]
+               while {-1 != [gets $fp tmp]} {
+                       set jp3dVM::dataout [concat "$jp3dVM::dataout\n$tmp"]
+               }
+               destroy .progress
+               set cond [string first "ERROR" $jp3dVM::dataout]
+               set cond2 [string first "RESULT" $jp3dVM::dataout]
+               if {$cond != -1} {
+                  MessageDlg .msgdlg -parent . -message [string range $jp3dVM::dataout [expr $cond-1] end] -type ok -icon error
+               } elseif {$cond2 != -1} {
+                  MessageDlg .msgdlg -parent . -message [string range $jp3dVM::dataout [expr $cond2+7] end] -type ok -icon info
+                  close $fp
+               } else {
+                  #Must do something with this !!! [pid $fp]
+                  close $fp
+               }
+       }
+}
+
+proc VMEncoder::_reset { framesrc framedst frametrf framecod} {
+
+       variable var
+
+       #Restore defaults values
+       set VMEncoder::var(transform) 2DWT
+       set VMEncoder::var(encoding) 2EB
+       set VMEncoder::var(atk) "R5.3"
+       set VMEncoder::var(progorder) "LRCP"
+       set atk $frametrf.labres.f.frameatk.atk
+       set resX $frametrf.labres.f.frameres2.spinresX
+       set resY $frametrf.labres.f.frameres2.spinresY
+       set resZ $frametrf.labres.f.frameres2.spinresZ
+       disable3RLS 2DWT $atk $resX $resY $resZ 
+       set labcblk $framecod.labcod.f.framecblk.labcblk
+       set progorder $framecod.labcod.f.framepoc.progorder
+       set labrate $framecod.labcod.f.framerate.labrate
+       set chksop $framecod.labcod.f.framesop.chksop
+       set chkeph $framecod.labcod.f.frameeph.chkeph
+       disableGR 3EB $labcblk $progorder $labrate $chksop $chkeph
+
+       $framesrc.labsrc.f.entrysrc delete 0 end
+       $framedst.labdst.f.entrydst delete 0 end
+}
+
+proc fileDialogE {w ent operation} {
+
+       variable file
+       variable i j
+
+       if {$operation == "open"} {
+               set types {
+                       {"Source Image Files"   {.pgx .bin}     }
+                       {"All files"            *}
+               }
+               set file [tk_getOpenFile -filetypes $types -parent $w]
+               if {[string compare $file ""]} {
+                       $ent delete 0 end
+                       $ent insert end $file
+                       $ent xview moveto 1
+               }
+       } else {
+               set types {
+                       {"JP3D Files"              {.jp3d}      }
+                       {"JPEG2000 Files"          {.j2k}       }
+                       {"All files"            *}
+               }
+               set file [tk_getSaveFile -filetypes $types -parent $w \
+                       -initialfile Untitled -defaultextension .jp3d]
+               if {[string compare $file ""]} {
+                       $ent delete 0 end
+                       $ent insert end $file
+                       $ent xview moveto 1
+               }
+       }
+}
+
+proc mk_relativepath {abspath} {
+
+       set mydir [split [string trimleft [pwd] {/}] {/}]
+       set abspathcomps [split [string trimleft $abspath {/}] {/}]
+
+       set i 0
+       while {$i<[llength $mydir]} {
+               if {![string compare [lindex $abspathcomps $i] [lindex $mydir $i]]} {
+                       incr i
+               } else {
+                       break
+               }
+       }
+       set h [expr [llength $mydir]-$i]
+       set j [expr [llength $abspathcomps]-$i]
+
+       if {!$h} {
+               set relpath "./"
+       } else {
+               set relpath ""
+               while { $h > 0 } {
+                       set relpath "../$relpath"
+                       incr h -1
+               }
+       }
+
+       set h [llength $abspathcomps]
+       while { $h > $i } {
+               set relpath [concat $relpath[lindex $abspathcomps [expr [llength $abspathcomps]-$j]]/]
+               incr h -1
+               incr j -1
+       }
+       return [string trim $relpath {/}]
+}
+
+proc disable3RLS {flag atk resX resY resZ}  {
+
+       if {$flag == "3RLS"} {
+               $atk configure -state disabled
+               $resX configure -state disabled
+               $resY configure -state disabled
+               $resZ configure -state disabled
+       } elseif {$flag == "2DWT"} {
+               $atk configure -state normal
+               $resX configure -state normal
+               $resY configure -state normal
+               $resZ configure -state disabled
+       } elseif {$flag == "3DWT"} {
+               $atk configure -state normal
+               $resX configure -state normal
+               $resY configure -state normal
+               $resZ configure -state normal
+       }
+}
+
+proc disableGR {flag labcblk progorder labrate chksop chkeph} {
+       
+       if {$flag == "2EB"} {
+               $labcblk configure -state normal
+               $progorder configure -state normal
+               $labrate configure -state normal
+               $chksop configure -state normal
+               $chkeph configure -state normal
+               set VMEncoder::var(cblksize) "64,64,64"
+               set VMEncoder::var(tilesize) "512,512,512"
+       } elseif {$flag == "3EB"} {
+               $labcblk configure -state normal
+               $progorder configure -state normal
+               $labrate configure -state normal
+               $chksop configure -state normal
+               $chkeph configure -state normal
+               set VMEncoder::var(cblksize) "64,64,64"
+               set VMEncoder::var(tilesize) "512,512,512"
+       } else {
+               $labcblk configure -state disabled
+               $progorder configure -state disabled
+               $labrate configure -state disabled
+               $chksop configure -state disabled
+               $chkeph configure -state disabled
+       }
+}
diff --git a/src/bin/jp3d/tcltk/logoLPI.gif b/src/bin/jp3d/tcltk/logoLPI.gif
new file mode 100755 (executable)
index 0000000..df79515
Binary files /dev/null and b/src/bin/jp3d/tcltk/logoLPI.gif differ
diff --git a/src/bin/jp3d/volume_to_jp3d.c b/src/bin/jp3d/volume_to_jp3d.c
new file mode 100755 (executable)
index 0000000..8a593b3
--- /dev/null
@@ -0,0 +1,906 @@
+/*\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) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain\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
+\r
+#include "openjp3d.h"\r
+#include "getopt.h"\r
+#include "convert.h"\r
+\r
+#ifdef _WIN32\r
+#include <windows.h>\r
+#else\r
+#define stricmp strcasecmp\r
+#define strnicmp strncasecmp\r
+#endif /* _WIN32 */\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+void encode_help_display() {\r
+       fprintf(stdout,"List of parameters for the JPEG2000 Part 10 encoder:\n");\r
+       fprintf(stdout,"------------\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"Required Parameters (except with -h):\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-i           : source file  (-i source.bin or source*.pgx) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-m           : source characteristics file (-m imgfile.img) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-o           : destination file (-o dest.jp3d) \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,"-n           : number of resolutions (-n 3,3,3) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-I           : use the irreversible transforms: ICT + DWT 9-7 (-I) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-C           : coding algorithm (-C 2EB) [2EB, 3EB] \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 compression factor.\n");\r
+       fprintf(stdout,"                 - Rate 1 means lossless compression\n");\r
+       fprintf(stdout,"               (options -r and -q cannot be used together)\n ");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-q           : different psnr for successive layers (-q 30,40,50) \n ");\r
+       fprintf(stdout,"               (options -r and -q cannot be used together)\n ");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-b           : size of code block (-b 32,32,32) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-c           : size of precinct (-c 128,128,128) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-t           : size of tile (-t 512,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,2) [-s X,Y,Z] \n");\r
+       fprintf(stdout,"                          - Remark: subsampling bigger than 2 can produce error\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           : code-block style (-M 0) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");\r
+       fprintf(stdout,"                 8=VSC 16=PTERM 32=SEGSYM 64=3DCTXT] \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,"-D           : define DC offset (-D 12) \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 volume (-d 150,300,100) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-l           : offset of the origin of the tiles (-l 100,75,25) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"DEFAULT CODING:\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 x 2^15 (means 1 precinct)\n");\r
+       fprintf(stdout," * Size of code-block : 64 x 64 x 64\n");\r
+       fprintf(stdout," * Number of resolutions in x, y and z axis: 3\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, y or z 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 volume\n");\r
+       fprintf(stdout," * No offset of the origin of the tiles\n");\r
+       fprintf(stdout," * Reversible DWT 5-3 on each 2D slice\n");\r
+       fprintf(stdout," * Coding algorithm: 2D-EBCOT \n");\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 markers will never appear in the tile_header.\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"- You need enough disk space memory (twice the original) to encode \n");\r
+       fprintf(stdout,"the volume,i.e. for a 1.5 GB volume you need a minimum of 3GB of disk memory)\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"- When loading *.pgx files, a relative path to directory is needed for input argument \n");\r
+       fprintf(stdout," followed by the common prefix of the slices and a '*' character representing sequential numeration.\n");\r
+       fprintf(stdout,"( -i relativepath/slices*.pgx )\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout," - The index file has the structure below:\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"\t      Image_height Image_width Image_depth\n");\r
+       fprintf(stdout,"\t      Progression order: 0 (LRCP)\n");\r
+       fprintf(stdout,"\t      Tiles_size_X Tiles_size_Y Tiles_size_Z\n");\r
+       fprintf(stdout,"\t      Components_nb\n");\r
+       fprintf(stdout,"\t      Layers_nb\n");\r
+       fprintf(stdout,"\t      Decomposition_levels\n");\r
+       fprintf(stdout,"\t      [Precincts_size_X_res_Nr Precincts_size_Y_res_Nr Precincts_size_Z_res_Nr]\n\t  ...\n");\r
+       fprintf(stdout,"\t      [Precincts_size_X_res_0 Precincts_size_Y_res_0 Precincts_size_Z_res_0]\n");\r
+       fprintf(stdout,"\t      Main_header_end_position\n");\r
+       fprintf(stdout,"\t      Codestream_size\n");\r
+       fprintf(stdout,"\t      Tile_0 [start_pos end_header end_pos TotalDisto NumPix MaxMSE]\n");\r
+       fprintf(stdout,"\t      ...\n");\r
+       fprintf(stdout,"\t      Tile_Nt [  ''         ''        ''        ''       ''    ''  ]\n");\r
+       fprintf(stdout,"\t  Tpacket_0 [Tile layer res. comp. prec. start_pos end_pos disto]\n");\r
+       fprintf(stdout,"\t  ...\n");\r
+       fprintf(stdout,"\t  Tpacket_Np [''   ''    ''   ''    ''       ''       ''     '' ]\n");\r
+       fprintf(stdout,"\t  MaxDisto\n");\r
+       fprintf(stdout,"\t  TotalDisto\n\n");\r
+       fprintf(stdout,"\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
+OPJ_TRANSFORM give_transform(char transform[4]) {\r
+       if(strncmp(transform, "2DWT", 4) == 0) {\r
+               return TRF_2D_DWT;\r
+       }\r
+       if(strncmp(transform, "3DWT", 4) == 0) {\r
+               return TRF_3D_DWT;\r
+       }\r
+       return TRF_UNKNOWN;\r
+}\r
+\r
+OPJ_ENTROPY_CODING give_coding(char coding[3]) {\r
+\r
+       if(strncmp(coding, "2EB", 3) == 0) {\r
+               return ENCOD_2EB;\r
+       }\r
+       if(strncmp(coding, "3EB", 3) == 0) {\r
+               return ENCOD_3EB;\r
+       }\r
+       /*if(strncmp(coding, "2GR", 3) == 0) {\r
+               return ENCOD_2GR;\r
+       }\r
+       if(strncmp(coding, "3GR", 3) == 0) {\r
+               return ENCOD_3GR;\r
+       }*/\r
+\r
+       return ENCOD_UNKNOWN;\r
+}\r
+\r
+int get_file_format(char *filename) {\r
+       int i;\r
+       static const char *extension[] = {"pgx", "bin", "img", "j3d", "jp3d", "j2k"};\r
+       static const int format[] = { PGX_DFMT, BIN_DFMT, IMG_DFMT, J3D_CFMT, J3D_CFMT, J2K_CFMT};\r
+       char * ext = strrchr(filename, '.');\r
+       if (ext) {\r
+               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
+int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *parameters) {\r
+       int i, value;\r
+\r
+       /* parse the command line */\r
+\r
+       while (1) {\r
+               int c = getopt(argc, argv, "i:m:o:r:q:f:t:n:c:b:x:p:s:d:hP:S:E:M:D:R:l:T:C:A:I");\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 PGX_DFMT:\r
+                                       case BIN_DFMT:\r
+                                       case IMG_DFMT:\r
+                                               break;\r
+                                       default:\r
+                                               fprintf(stdout, "[ERROR] Unrecognized format for infile : %s [accept only *.pgx or *.bin] !!\n\n", infile);\r
+                                               return 1;\r
+                                               break;\r
+                               }\r
+                               strncpy(parameters->infile, infile, MAX_PATH);\r
+                               fprintf(stdout, "[INFO] Infile: %s \n", parameters->infile);\r
+\r
+                       }\r
+                       break;\r
+                               \r
+                               /* ----------------------------------------------------- */\r
+                       case 'm':                       /* input IMG file */\r
+                       {\r
+                               char *imgfile = optarg;\r
+                               int imgformat = get_file_format(imgfile);\r
+                               switch(imgformat) {\r
+                                       case IMG_DFMT:\r
+                                               break;\r
+                                       default:\r
+                                               fprintf(stdout, "[ERROR] Unrecognized format for imgfile : %s [accept only *.img] !!\n\n", imgfile);\r
+                                               return 1;\r
+                                               break;\r
+                               }\r
+                               strncpy(parameters->imgfile, imgfile, MAX_PATH);\r
+                               fprintf(stdout, "[INFO] Imgfile: %s Format: %d\n", parameters->imgfile, imgformat);\r
+                       }\r
+                       break;\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 J3D_CFMT:\r
+                                       case J2K_CFMT:\r
+                                       case LSE_CFMT:\r
+                                               break;\r
+                                       default:\r
+                                               fprintf(stdout, "[ERROR] Unknown output format volume %s [only *.j2k, *.lse3d or *.jp3d]!! \n", outfile);\r
+                                               return 1;\r
+                                               break;\r
+                               }\r
+                               strncpy(parameters->outfile, outfile, MAX_PATH);\r
+                               fprintf(stdout, "[INFO] Outfile: %s \n", parameters->outfile);\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+                       \r
+                       case 'r':                       /* define compression rates for each layer */\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':                       /* define distorsion (PSNR) for each layer */\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
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'f':       \r
+                       {\r
+                               fprintf(stdout, "/---------------------------------------------------\\\n");\r
+                               fprintf(stdout, "|  Fixed layer allocation option not implemented !!  |\n");\r
+                               fprintf(stdout, "\\---------------------------------------------------/\n");\r
+                               /*int *row = NULL, *col = NULL;\r
+                               int numlayers = 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
+                               matrix_width = parameters->numresolution[0] + parameters->numresolution[1] + parameters->numresolution[2];\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 < matrix_width; j++) {\r
+                                               col += 3; j+=2;\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
+                               if (sscanf(optarg, "%d,%d,%d", &parameters->cp_tdx, &parameters->cp_tdy, &parameters->cp_tdz) !=3) {\r
+                                       fprintf(stdout, "[ERROR] '-t' 'dimensions of tiles' argument error !  [-t tdx,tdy,tdz]\n");\r
+                                       return 1;\r
+                               }\r
+                               parameters->tile_size_on = true;\r
+                       }\r
+                       break;\r
+                               \r
+                               /* ----------------------------------------------------- */\r
+                       \r
+                       case 'n':                       /* resolution */\r
+                       {\r
+                               int aux;\r
+                               aux = sscanf(optarg, "%d,%d,%d", &parameters->numresolution[0], &parameters->numresolution[1], &parameters->numresolution[2]);\r
+                               if (aux == 2) \r
+                                       parameters->numresolution[2] = 1;\r
+                               else if (aux == 1) {\r
+                                       parameters->numresolution[1] = parameters->numresolution[0];\r
+                                       parameters->numresolution[2] = 1;\r
+                               }else if (aux == 0){\r
+                                       parameters->numresolution[0] = 1;\r
+                                       parameters->numresolution[1] = 1;\r
+                                       parameters->numresolution[2] = 1;\r
+                               }\r
+                       }\r
+                       break;\r
+                               \r
+                               /* ----------------------------------------------------- */\r
+                       case 'c':                       /* precinct dimension */\r
+                       {\r
+                               char sep;\r
+                               int res_spec = 0;\r
+                               int aux;\r
+                               char *s = optarg;\r
+                               do {\r
+                                       sep = 0;\r
+                                       aux = sscanf(s, "[%d,%d,%d]%c", &parameters->prct_init[0][res_spec], &parameters->prct_init[1][res_spec], &parameters->prct_init[2][res_spec], &sep);\r
+                                       if (sep == ',' && aux != 4) {\r
+                                               fprintf(stdout, "[ERROR] '-c' 'dimensions of precincts' argument error !  [-c [prcx_res0,prcy_res0,prcz_res0],...,[prcx_resN,prcy_resN,prcz_resN]]\n");\r
+                                               return 1;\r
+                                       }\r
+                                       parameters->csty |= 0x01;\r
+                                       res_spec++;\r
+                                       s = strpbrk(s, "]") + 2;\r
+                               }\r
+                               while (sep == ',');\r
+                               parameters->res_spec = res_spec; /* number of precinct size specifications */\r
+                       }\r
+                       break;\r
+                               \r
+                               /* ----------------------------------------------------- */\r
+                       \r
+                       case 'b':                       /* code-block dimension */\r
+                       {\r
+                               int cblockw_init = 0, cblockh_init = 0, cblockl_init = 0;\r
+                               if (sscanf(optarg, "%d,%d,%d", &cblockw_init, &cblockh_init, &cblockl_init) != 3) {\r
+                                       fprintf(stdout, "[ERROR] '-b' 'dimensions of codeblocks' argument error !  [-b cblkx,cblky,cblkz]\n");\r
+                                       return 1;\r
+                               }\r
+                               if (cblockw_init * cblockh_init * cblockl_init > (1<<18) || cblockw_init > 1024 || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4 || cblockl_init > 1024 || cblockl_init < 4) {\r
+                                       fprintf(stdout,"[ERROR] Size of code_block error (option -b) !!\n\nRestriction :\n * width*height*length<=4096\n * 4<=width,height,length<= 1024\n\n");\r
+                                       return 1;\r
+                               }\r
+                               parameters->cblock_init[0] = cblockw_init;\r
+                               parameters->cblock_init[1] = cblockh_init;\r
+                               parameters->cblock_init[2] = cblockl_init;\r
+                       }\r
+                       break;\r
+                               \r
+                               /* ----------------------------------------------------- */\r
+                       \r
+                       case 'x':                       /* creation of index file */\r
+                       {\r
+                               char *index = optarg;\r
+                               strncpy(parameters->index, index, MAX_PATH);\r
+                               parameters->index_on = 1;\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(stdout, "[ERROR] Unrecognized progression order [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,%d", &parameters->subsampling_dx, &parameters->subsampling_dy, &parameters->subsampling_dz) != 2) {\r
+                                       fprintf(stdout, "[ERROR] '-s' sub-sampling argument error !  [-s dx,dy,dz]\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,%d", &parameters->volume_offset_x0, &parameters->volume_offset_y0, &parameters->volume_offset_z0) != 3) {\r
+                                       fprintf(stdout, "[ERROR] -d 'coordonnate of the reference grid' argument error !! [-d x0,y0,z0]\n");\r
+                                       return 1;\r
+                               }\r
+                       }\r
+                       break;\r
+                               \r
+                               /* ----------------------------------------------------- */\r
+                       \r
+                       case 'h':                       /* display an help description */\r
+                       {\r
+                               encode_help_display();\r
+                               return 1;\r
+                       }\r
+                       break;\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
+                               fprintf(stdout, "/----------------------------------\\\n");\r
+                               fprintf(stdout, "|  POC option not fully tested !!  |\n");\r
+                               fprintf(stdout, "\\----------------------------------/\n");\r
+                               \r
+                               while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%s", &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].prg = give_progression(POC[numpocs].progorder);\r
+                                       /* POC[numpocs].tile; */\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':                       /* Codification mode switch */\r
+                       {\r
+                               fprintf(stdout, "[INFO] Mode switch option not fully tested !!\n");\r
+                               value = 0;\r
+                               if (sscanf(optarg, "%d", &value) == 1) {\r
+                                       for (i = 0; i <= 6; 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 'D':                       /* DCO */\r
+                       {\r
+                               if (sscanf(optarg, "%d", &parameters->dcoffset) != 1) {\r
+                                       fprintf(stdout, "[ERROR] DC offset error !! [-D %d]\n",parameters->dcoffset);\r
+                                       return 1;\r
+                               }\r
+                       }\r
+                       break;\r
+                               \r
+                               /* ------------------------------------------------------ */\r
+                       \r
+                       case 'R':                       /* ROI */\r
+                       {\r
+                               if (sscanf(optarg, "OI:c=%d,U=%d", &parameters->roi_compno, &parameters->roi_shift) != 2) {\r
+                                       fprintf(stdout, "[ERROR] ROI error !! [-ROI:c='compno',U='shift']\n");\r
+                                       return 1;\r
+                               }\r
+                       }\r
+                       break;\r
+                               \r
+                               /* ------------------------------------------------------ */\r
+                       \r
+                       case 'l':                       /* Tile offset */\r
+                       {\r
+                               if (sscanf(optarg, "%d,%d,%d", &parameters->cp_tx0, &parameters->cp_ty0, &parameters->cp_tz0) != 3) {\r
+                                       fprintf(stdout, "[ERROR] -l 'tile offset' argument error !! [-l X0,Y0,Z0]");\r
+                                       return 1;\r
+                               }\r
+                       }\r
+                       break;\r
+                               \r
+                               /* ------------------------------------------------------ \r
+                               \r
+                       case 'T':                       // Tranformation of original data (2D-DWT/3D-DWT/3D-RLS/2D-DWT+1D-RLS) \r
+                       {\r
+                               char transform[4];\r
+\r
+                               strncpy(transform, optarg, 4);\r
+                               parameters->transform_format = give_transform(transform);\r
+                               if (parameters->transform_format == -1) {\r
+                                       fprintf(stdout, "[ERROR] -T 'Transform domain' argument error !! [-T 2DWT, 3DWT, 3RLS or 3LSE only]");\r
+                    return 1;\r
+                               }\r
+                       }\r
+                       break;\r
+                               \r
+                                ------------------------------------------------------ */\r
+                       \r
+                       case 'C':                       /* Coding of transformed data */\r
+                       {\r
+                               char coding[3];\r
+\r
+                               strncpy(coding, optarg, 3);\r
+                               parameters->encoding_format = give_coding(coding);\r
+                               if (parameters->encoding_format == -1) {\r
+                                       fprintf(stdout, "[ERROR] -C 'Coding algorithm' argument error !! [-C 2EB, 3EB, 2GR, 3GR or GRI only]");\r
+                    return 1;\r
+                               }\r
+                       }\r
+                       break;\r
+                       \r
+                       /* ------------------------------------------------------ */\r
+                       \r
+                       case 'I':                       /* reversible or not */\r
+                       {\r
+                               parameters->irreversible = 1;\r
+                       }\r
+                       break;\r
+                               \r
+                       default:\r
+                               fprintf(stdout, "[ERROR] This option is not valid \"-%c %s\"\n", c, optarg);\r
+                               return 1;\r
+               }\r
+       }\r
+\r
+       /* check for possible errors */\r
+\r
+       if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {\r
+               fprintf(stdout, "usage: jp3d_vm_enc -i volume-file -o jp3d-file (+ options)\n");\r
+               return 1;\r
+       }\r
+\r
+       if((parameters->decod_format == BIN_DFMT) && (parameters->imgfile[0] == 0)) {\r
+               fprintf(stdout, "usage: jp3d_vm_enc -i bin-volume-file -m img-file -o jp3d-file (+ options)\n");\r
+               return 1;\r
+       }\r
+\r
+       if((parameters->decod_format != BIN_DFMT) && (parameters->decod_format != PGX_DFMT) && (parameters->decod_format != IMG_DFMT)) {\r
+               fprintf(stdout, "usage: jp3d_vm_enc -i input-volume-file [*.bin,*.pgx,*.img] -o jp3d-file [*.jp3d,*.j2k] (+ options)\n");\r
+               return 1;\r
+       }\r
+       if((parameters->cod_format != J3D_CFMT) && (parameters->cod_format != J2K_CFMT)) {\r
+               fprintf(stdout, "usage: jp3d_vm_enc -i input-volume-file [*.bin,*.pgx,*.img] -o jp3d-file [*.jp3d,*.j2k] (+ options)\n");\r
+               return 1;\r
+       }\r
+\r
+       if((parameters->encoding_format == ENCOD_2GR || parameters->encoding_format == ENCOD_3GR) && parameters->transform_format != TRF_3D_LSE && parameters->transform_format != TRF_3D_RLS) {\r
+               fprintf(stdout, "[ERROR] Entropy coding options -C [2GR,3GR] are only compatible with predictive-based transform algorithms: -T [3RLS,3LSE].\n");\r
+               return 1;\r
+       }\r
+       if (parameters->encoding_format == ENCOD_3EB)\r
+               parameters->mode |= (1 << 6);\r
+\r
+       if ((parameters->mode >> 6) & 1) {\r
+               parameters->encoding_format = ENCOD_3EB;\r
+       }\r
+\r
+       if((parameters->numresolution[2] == 0 || (parameters->numresolution[1] == 0) || (parameters->numresolution[0] == 0))) {\r
+               fprintf(stdout, "[ERROR] -n 'resolution levels' argument error ! Resolutions must be greater than 1 in order to perform DWT.\n");\r
+               return 1;\r
+       }\r
+       if (parameters->numresolution[1] != parameters->numresolution[0]) {\r
+               fprintf(stdout, "[ERROR] -n 'resolution levels' argument error ! Resolutions in X and Y axis must be the same in this implementation.\n");\r
+               return 1;\r
+       }\r
+       \r
+       if (parameters->numresolution[2] > parameters->numresolution[0]) {\r
+               fprintf(stdout, "[ERROR] -n 'resolution levels' argument error ! Resolutions in Z axis must be lower than in X-Y axis.\n");\r
+               return 1;\r
+       }\r
+       \r
+       if (parameters->dcoffset >= 128 && parameters->dcoffset <= -128) {\r
+               fprintf(stdout, "[ERROR] -D 'DC offset' argument error ! Value must be -128<=DCO<=128.\n");\r
+               return 1;\r
+       }\r
+\r
+       if(parameters->numresolution[2] != 1) {\r
+               parameters->transform_format = TRF_3D_DWT;\r
+               //fprintf(stdout, "[Warning] Resolution level in axial dim > 1 : 3D-DWT will be performed... \n");\r
+       } else if (parameters->numresolution[2] == 1) {\r
+               parameters->transform_format = TRF_2D_DWT;\r
+               //fprintf(stdout, "[Warning] Resolution level in axial dim == 1 : 2D-DWT will be performed... \n");\r
+       }\r
+       \r
+       if ((parameters->cod_format == J2K_CFMT) && (parameters->transform_format != TRF_2D_DWT || parameters->encoding_format != ENCOD_2EB)) {\r
+               fprintf(stdout, "[WARNING] Incompatible options -o *.j2k and defined transform or encoding algorithm. Latter will be ignored\n");\r
+               parameters->transform_format = TRF_2D_DWT;\r
+               parameters->encoding_format = ENCOD_2EB;\r
+       }\r
+\r
+       if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc || parameters->cp_fixed_quality) && (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_quality))) {\r
+               fprintf(stdout, "[ERROR] Options -r and -q 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.0; /* MOD antonin : losslessbug */\r
+               parameters->tcp_numlayers++;\r
+               parameters->cp_disto_alloc = 1;\r
+       }\r
+\r
+       if((parameters->cp_tx0 > parameters->volume_offset_x0) || (parameters->cp_ty0 > parameters->volume_offset_y0) || (parameters->cp_tz0 > parameters->volume_offset_z0)) {\r
+               fprintf(stdout, "[ERROR] Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) TZO(%d)<=IMG_Z0(%d)\n",\r
+                       parameters->cp_tx0, parameters->volume_offset_x0, parameters->cp_ty0, parameters->volume_offset_y0, \r
+                       parameters->cp_tz0, parameters->volume_offset_z0);\r
+               return 1;\r
+       }\r
+\r
+       for (i = 0; i < parameters->numpocs; i++) {\r
+               if (parameters->POC[i].prg == -1) {\r
+                       fprintf(stdout,"[ERROR] Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",i + 1);\r
+               }\r
+       }\r
+       return 0;\r
+}\r
+\r
+/* -------------------------------------------------------------------------- */\r
+\r
+/**\r
+sample error callback expecting a FILE* client object\r
+*/\r
+void error_callback(const char *msg, void *client_data) {\r
+       FILE *stream = (FILE*)client_data;\r
+       fprintf(stream, "[ERROR] %s", msg);\r
+}\r
+/**\r
+sample warning callback expecting a FILE* client object\r
+*/\r
+void warning_callback(const char *msg, void *client_data) {\r
+       FILE *stream = (FILE*)client_data;\r
+       fprintf(stream, "[WARNING] %s", msg);\r
+}\r
+/**\r
+sample debug callback expecting a FILE* client object\r
+*/\r
+void info_callback(const char *msg, void *client_data) {\r
+       FILE *stream = (FILE*)client_data;\r
+       fprintf(stream, "[INFO] %s", msg);\r
+}\r
+\r
+/* -------------------------------------------------------------------------- */\r
+\r
+int main(int argc, char **argv) {\r
+       bool bSuccess;\r
+       bool delete_comment = true;\r
+       opj_cparameters_t parameters;   /* compression parameters */\r
+       opj_event_mgr_t event_mgr;              /* event manager */\r
+       opj_volume_t *volume = NULL;\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 = 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
+\r
+       /* parse input and get user encoding parameters */\r
+       if(parse_cmdline_encoder(argc, argv, &parameters) == 1) {\r
+               return 0;\r
+       }\r
+\r
+       if(parameters.cp_comment == NULL) {\r
+               parameters.cp_comment = "Created by OpenJPEG version JP3D";\r
+               /* no need to delete parameters.cp_comment on exit */\r
+               delete_comment = false;\r
+       }\r
+       \r
+       /* encode the destination volume */\r
+       /* ---------------------------- */\r
+       if (parameters.cod_format == J3D_CFMT || parameters.cod_format == J2K_CFMT)     {\r
+               int codestream_length, pixels, bitsin;\r
+               opj_cio_t *cio = NULL;\r
+               FILE *f = NULL;\r
+               opj_cinfo_t* cinfo = NULL;\r
+               \r
+               /* decode the source volume */\r
+               /* ----------------------- */\r
+               switch (parameters.decod_format) {\r
+                       case PGX_DFMT: \r
+                               fprintf(stdout, "[INFO] Loading pgx file(s)\n");\r
+                               volume = pgxtovolume(parameters.infile, &parameters);\r
+                               if (!volume) {\r
+                                       fprintf(stdout, "[ERROR] Unable to load pgx files\n");\r
+                                       return 1;\r
+                               }\r
+                               break;\r
+                       \r
+                       case BIN_DFMT:\r
+                               fprintf(stdout, "[INFO] Loading bin file\n");\r
+                               volume = bintovolume(parameters.infile, parameters.imgfile, &parameters);\r
+                               if (!volume) {\r
+                                       fprintf(stdout, "[ERROR] Unable to load bin file\n");\r
+                                       return 1;\r
+                               }\r
+                               break;\r
+\r
+                       case IMG_DFMT:\r
+                               fprintf(stdout, "[INFO] Loading img file\n");\r
+                               volume = imgtovolume(parameters.infile, &parameters);\r
+                               if (!volume) {\r
+                                       fprintf(stderr, "[ERROR] Unable to load img file\n");\r
+                                       return 1;\r
+                               }\r
+                               break;\r
+               }\r
+               \r
+               /* get a JP3D or J2K compressor handle */\r
+               if (parameters.cod_format == J3D_CFMT) \r
+            cinfo = opj_create_compress(CODEC_J3D);\r
+               else if (parameters.cod_format == J2K_CFMT) \r
+            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, stdout);                   \r
+\r
+               /* setup the encoder parameters using the current volume and using user parameters */\r
+               opj_setup_encoder(cinfo, &parameters, volume);\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 volume */\r
+               //fprintf(stdout, "[INFO] Encode the volume\n");\r
+               bSuccess = opj_encode(cinfo, cio, volume, parameters.index);\r
+               if (!bSuccess) {\r
+                       opj_cio_close(cio);\r
+                       fprintf(stdout, "[ERROR] Failed to encode volume\n");\r
+                       return 1;\r
+               }\r
+               codestream_length = cio_tell(cio);\r
+               pixels =(volume->x1 - volume->x0) * (volume->y1 - volume->y0) * (volume->z1 - volume->z0);\r
+               bitsin = pixels * volume->comps[0].prec;\r
+               fprintf(stdout, "[RESULT] Volume: %d x %d x %d (x %d bpv)\n Codestream: %d B,  Ratio: %5.3f bpv,  (%5.3f : 1) \n", \r
+                       (volume->x1 - volume->x0),(volume->y1 - volume->y0),(volume->z1 - volume->z0),volume->comps[0].prec,\r
+                       codestream_length, ((double)codestream_length * 8.0/(double)pixels), ((double)bitsin/(8.0*(double)codestream_length)));\r
+\r
+               /* write the buffer to disk */\r
+               f = fopen(parameters.outfile, "wb");\r
+               if (!f) {\r
+                       fprintf(stdout, "[ERROR] 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
+\r
+               /* close and free the byte stream */\r
+               opj_cio_close(cio);\r
+\r
+               /* free remaining compression structures */\r
+               opj_destroy_compress(cinfo);\r
+       } else {\r
+               fprintf(stdout, "[ERROR] Cod_format != JP3d !!! \n");\r
+               return 1;\r
+       }\r
+\r
+       /* free user parameters structure */\r
+       if(delete_comment) {\r
+               if(parameters.cp_comment) free(parameters.cp_comment);\r
+       }\r
+       if(parameters.cp_matrice) free(parameters.cp_matrice);\r
+\r
+       /* free volume data */\r
+       opj_volume_destroy(volume);\r
+       \r
+       return 0;\r
+}\r
diff --git a/src/bin/jp3d/windirent.h b/src/bin/jp3d/windirent.h
new file mode 100644 (file)
index 0000000..72b38ce
--- /dev/null
@@ -0,0 +1,678 @@
+/*
+ * uce-dirent.h - operating system independent dirent implementation
+ * 
+ * Copyright (C) 1998-2002  Toni Ronkko
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * ``Software''), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ * 
+ * 
+ * May 28 1998, Toni Ronkko <tronkko@messi.uku.fi>
+ *
+ * $Id: uce-dirent.h,v 1.7 2002/05/13 10:48:35 tr Exp $
+ *
+ * $Log: uce-dirent.h,v $
+ * Revision 1.7  2002/05/13 10:48:35  tr
+ * embedded some source code directly to the header so that no source
+ * modules need to be included in the MS Visual C project using the
+ * interface, removed all the dependencies to other headers of the `uce'
+ * library so that the header can be made public
+ *
+ * Revision 1.6  2002/04/12 16:22:04  tr
+ * Unified Compiling Environment (UCE) replaced `std' library
+ *
+ * Revision 1.5  2001/07/20 16:33:40  tr
+ * moved to `std' library and re-named defines accordingly
+ *
+ * Revision 1.4  2001/07/10 16:47:18  tronkko
+ * revised comments
+ *
+ * Revision 1.3  2001/01/11 13:16:43  tr
+ * using ``uce-machine.h'' for finding out defines such as `FREEBSD'
+ *
+ * Revision 1.2  2000/10/08 16:00:41  tr
+ * copy of FreeBSD man page
+ *
+ * Revision 1.1  2000/07/10 05:53:16  tr
+ * Initial revision
+ *
+ * Revision 1.2  1998/07/19 18:29:14  tr
+ * Added error reporting capabilities and some asserts.
+ *
+ * Revision 1.1  1998/07/04 16:27:51  tr
+ * Initial revision
+ *
+ * 
+ * MSVC 1.0 scans automatic dependencies incorrectly when your project
+ * contains this very header.  The problem is that MSVC cannot handle
+ * include directives inside #if..#endif block those are never entered.
+ * Since this header ought to compile in many different operating systems,
+ * there had to be several conditional blocks that are compiled only in
+ * operating systems for what they were designed for.  MSVC 1.0 cannot
+ * handle inclusion of sys/dir.h in a part that is compiled only in Apollo
+ * operating system.  To fix the problem you need to insert DIR.H into
+ * SYSINCL.DAT located in MSVC\BIN directory and restart visual C++.
+ * Consult manuals for more informaton about the problem.
+ *
+ * Since many UNIX systems have dirent.h we assume to have one also.
+ * However, if your UNIX system does not have dirent.h you can download one
+ * for example at: http://ftp.uni-mannheim.de/ftp/GNU/dirent/dirent.tar.gz.
+ * You can also see if you have one of dirent.h, direct.h, dir.h, ndir.h,
+ * sys/dir.h and sys/ndir.h somewhere.  Try defining HAVE_DIRENT_H,
+ * HAVE_DIRECT_H, HAVE_DIR_H, HAVE_NDIR_H, HAVE_SYS_DIR_H and
+ * HAVE_SYS_NDIR_H according to the files found.
+ */
+#ifndef DIRENT_H
+#define DIRENT_H
+#define DIRENT_H_INCLUDED
+
+/* find out platform */
+#if defined(MSDOS)                             /* MS-DOS */
+#elif defined(__MSDOS__)                       /* Turbo C/Borland */
+# define MSDOS
+#elif defined(__DOS__)                         /* Watcom */
+# define MSDOS
+#endif
+
+#if defined(WIN32)                             /* MS-Windows */
+#elif defined(__NT__)                          /* Watcom */
+# define WIN32
+#elif defined(_WIN32)                          /* Microsoft */
+# define WIN32
+#elif defined(__WIN32__)                       /* Borland */
+# define WIN32
+#endif
+
+/*
+ * See what kind of dirent interface we have unless autoconf has already
+ * determinated that.
+ */
+#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)
+# if defined(_MSC_VER)                         /* Microsoft C/C++ */
+    /* no dirent.h */
+# elif defined(__MINGW32__)                    /* MinGW */
+    /* no dirent.h */
+# elif defined(__BORLANDC__)                   /* Borland C/C++ */
+#   define HAVE_DIRENT_H
+#   define VOID_CLOSEDIR
+# elif defined(__TURBOC__)                     /* Borland Turbo C */
+    /* no dirent.h */
+# elif defined(__WATCOMC__)                    /* Watcom C/C++ */
+#   define HAVE_DIRECT_H
+# elif defined(__apollo)                       /* Apollo */
+#   define HAVE_SYS_DIR_H
+# elif defined(__hpux)                         /* HP-UX */
+#   define HAVE_DIRENT_H
+# elif defined(__alpha) || defined(__alpha__)  /* Alpha OSF1 */
+#   error "not implemented"
+# elif defined(__sgi)                          /* Silicon Graphics */
+#   define HAVE_DIRENT_H
+# elif defined(sun) || defined(_sun)           /* Sun Solaris */
+#   define HAVE_DIRENT_H
+# elif defined(__FreeBSD__)                    /* FreeBSD */
+#   define HAVE_DIRENT_H
+# elif defined(__linux__)                      /* Linux */
+#   define HAVE_DIRENT_H
+# elif defined(__GNUC__)                       /* GNU C/C++ */
+#   define HAVE_DIRENT_H
+# else
+#   error "not implemented"
+# endif
+#endif
+
+/* include proper interface headers */
+#if defined(HAVE_DIRENT_H)
+# include <dirent.h>
+# ifdef FREEBSD
+#   define NAMLEN(dp) ((int)((dp)->d_namlen))
+# else
+#   define NAMLEN(dp) ((int)(strlen((dp)->d_name)))
+# endif
+
+#elif defined(HAVE_NDIR_H)
+# include <ndir.h>
+# define NAMLEN(dp) ((int)((dp)->d_namlen))
+
+#elif defined(HAVE_SYS_NDIR_H)
+# include <sys/ndir.h>
+# define NAMLEN(dp) ((int)((dp)->d_namlen))
+
+#elif defined(HAVE_DIRECT_H)
+# include <direct.h>
+# define NAMLEN(dp) ((int)((dp)->d_namlen))
+
+#elif defined(HAVE_DIR_H)
+# include <dir.h>
+# define NAMLEN(dp) ((int)((dp)->d_namlen))
+
+#elif defined(HAVE_SYS_DIR_H)
+# include <sys/types.h>
+# include <sys/dir.h>
+# ifndef dirent
+#   define dirent direct
+# endif
+# define NAMLEN(dp) ((int)((dp)->d_namlen))
+
+#elif defined(MSDOS) || defined(WIN32)
+
+  /* figure out type of underlaying directory interface to be used */
+# if defined(WIN32)
+#   define DIRENT_WIN32_INTERFACE
+# elif defined(MSDOS)
+#   define DIRENT_MSDOS_INTERFACE
+# else
+#   error "missing native dirent interface"
+# endif
+
+  /*** WIN32 specifics ***/
+# if defined(DIRENT_WIN32_INTERFACE)
+#   include <windows.h>
+#   if !defined(DIRENT_MAXNAMLEN)
+#     define DIRENT_MAXNAMLEN (MAX_PATH)
+#   endif
+
+
+  /*** MS-DOS specifics ***/
+# elif defined(DIRENT_MSDOS_INTERFACE)
+#   include <dos.h>
+
+    /* Borland defines file length macros in dir.h */
+#   if defined(__BORLANDC__)
+#     include <dir.h>
+#     if !defined(DIRENT_MAXNAMLEN)
+#       define DIRENT_MAXNAMLEN ((MAXFILE)+(MAXEXT))
+#     endif
+#     if !defined(_find_t)
+#       define _find_t find_t
+#     endif
+
+    /* Turbo C defines ffblk structure in dir.h */
+#   elif defined(__TURBOC__)
+#     include <dir.h>
+#     if !defined(DIRENT_MAXNAMLEN)
+#       define DIRENT_MAXNAMLEN ((MAXFILE)+(MAXEXT))
+#     endif
+#     define DIRENT_USE_FFBLK
+
+    /* MSVC */
+#   elif defined(_MSC_VER)
+#     if !defined(DIRENT_MAXNAMLEN)
+#       define DIRENT_MAXNAMLEN (12)
+#     endif
+
+    /* Watcom */
+#   elif defined(__WATCOMC__)
+#     if !defined(DIRENT_MAXNAMLEN)
+#       if defined(__OS2__) || defined(__NT__)
+#         define DIRENT_MAXNAMLEN (255)
+#       else
+#         define DIRENT_MAXNAMLEN (12)
+#       endif
+#     endif
+
+#   endif
+# endif
+
+  /*** generic MS-DOS and MS-Windows stuff ***/
+# if !defined(NAME_MAX) && defined(DIRENT_MAXNAMLEN)
+#   define NAME_MAX DIRENT_MAXNAMLEN
+# endif
+# if NAME_MAX < DIRENT_MAXNAMLEN
+#   error "assertion failed: NAME_MAX >= DIRENT_MAXNAMLEN"
+# endif
+
+
+  /*
+   * Substitute for real dirent structure.  Note that `d_name' field is a
+   * true character array although we have it copied in the implementation
+   * dependent data.  We could save some memory if we had declared `d_name'
+   * as a pointer refering the name within implementation dependent data.
+   * We have not done that since some code may rely on sizeof(d_name) to be
+   * something other than four.  Besides, directory entries are typically so
+   * small that it takes virtually no time to copy them from place to place.
+   */
+  typedef struct dirent {
+    char d_name[NAME_MAX + 1];
+
+    /*** Operating system specific part ***/
+# if defined(DIRENT_WIN32_INTERFACE)       /*WIN32*/
+    WIN32_FIND_DATA data;
+# elif defined(DIRENT_MSDOS_INTERFACE)     /*MSDOS*/
+#   if defined(DIRENT_USE_FFBLK)
+    struct ffblk data;
+#   else
+    struct _find_t data;
+#   endif
+# endif
+  } dirent;
+
+  /* DIR substitute structure containing directory name.  The name is
+   * essential for the operation of ``rewinndir'' function. */
+  typedef struct DIR {
+    char          *dirname;                    /* directory being scanned */
+    dirent        current;                     /* current entry */
+    int           dirent_filled;               /* is current un-processed? */
+
+  /*** Operating system specific part ***/
+#  if defined(DIRENT_WIN32_INTERFACE)
+    HANDLE        search_handle;
+#  elif defined(DIRENT_MSDOS_INTERFACE)
+#  endif
+  } DIR;
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/* supply prototypes for dirent functions */
+static DIR *opendir (const char *dirname);
+static struct dirent *readdir (DIR *dirp);
+static int closedir (DIR *dirp);
+static void rewinddir (DIR *dirp);
+
+/*
+ * Implement dirent interface as static functions so that the user does not
+ * need to change his project in any way to use dirent function.  With this
+ * it is sufficient to include this very header from source modules using
+ * dirent functions and the functions will be pulled in automatically.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+
+/* use ffblk instead of _find_t if requested */
+#if defined(DIRENT_USE_FFBLK)
+# define _A_ARCH   (FA_ARCH)
+# define _A_HIDDEN (FA_HIDDEN)
+# define _A_NORMAL (0)
+# define _A_RDONLY (FA_RDONLY)
+# define _A_SUBDIR (FA_DIREC)
+# define _A_SYSTEM (FA_SYSTEM)
+# define _A_VOLID  (FA_LABEL)
+# define _dos_findnext(dest) findnext(dest)
+# define _dos_findfirst(name,flags,dest) findfirst(name,dest,flags)
+#endif
+
+static int _initdir (DIR *p);
+static const char *_getdirname (const struct dirent *dp);
+static void _setdirname (struct DIR *dirp);
+
+/*
+ * <function name="opendir">
+ * <intro>open directory stream for reading
+ * <syntax>DIR *opendir (const char *dirname);
+ *
+ * <desc>Open named directory stream for read and return pointer to the
+ * internal working area that is used for retrieving individual directory
+ * entries.  The internal working area has no fields of your interest.
+ *
+ * <ret>Returns a pointer to the internal working area or NULL in case the 
+ * directory stream could not be opened.  Global `errno' variable will set
+ * in case of error as follows:
+ *
+ * <table>
+ * [EACESS  |Permission denied.
+ * [EMFILE  |Too many open files used by the process.
+ * [ENFILE  |Too many open files in system.
+ * [ENOENT  |Directory does not exist.
+ * [ENOMEM  |Insufficient memory.
+ * [ENOTDIR |dirname does not refer to directory.  This value is not
+ *           reliable on MS-DOS and MS-Windows platforms.  Many
+ *           implementations return ENOENT even when the name refers to a
+ *           file.]
+ * </table>
+ * </function>
+ */
+static DIR *opendir(const char *dirname)
+{
+  DIR *dirp;
+  assert (dirname != NULL);
+  
+  dirp = (DIR*)malloc (sizeof (struct DIR));
+  if (dirp != NULL) {
+    char *p;
+    
+    /* allocate room for directory name */
+    dirp->dirname = (char*) malloc (strlen (dirname) + 1 + strlen ("\\*.*"));
+    if (dirp->dirname == NULL) {
+      /* failed to duplicate directory name.  errno set by malloc() */
+      free (dirp);
+      return NULL;
+    }
+    /* Copy directory name while appending directory separator and "*.*".
+     * Directory separator is not appended if the name already ends with
+     * drive or directory separator.  Directory separator is assumed to be
+     * '/' or '\' and drive separator is assumed to be ':'. */
+    strcpy (dirp->dirname, dirname);
+    p = strchr (dirp->dirname, '\0');
+    if (dirp->dirname < p  &&
+        *(p - 1) != '\\'  &&  *(p - 1) != '/'  &&  *(p - 1) != ':')
+    {
+      strcpy (p++, "\\");
+    }
+# ifdef DIRENT_WIN32_INTERFACE
+    strcpy (p, "*"); /*scan files with and without extension in win32*/
+# else
+    strcpy (p, "*.*"); /*scan files with and without extension in DOS*/
+# endif
+
+    /* open stream */
+    if (_initdir (dirp) == 0) {
+      /* initialization failed */
+      free (dirp->dirname);
+      free (dirp);
+      return NULL;
+    }
+  }
+  return dirp;
+}
+
+
+/*
+ * <function name="readdir">
+ * <intro>read a directory entry
+ * <syntax>struct dirent *readdir (DIR *dirp);
+ *
+ * <desc>Read individual directory entry and return pointer to a structure
+ * containing the name of the entry.  Individual directory entries returned
+ * include normal files, sub-directories, pseudo-directories "." and ".."
+ * and also volume labels, hidden files and system files in MS-DOS and
+ * MS-Windows.   You might want to use stat(2) function to determinate which
+ * one are you dealing with.  Many dirent implementations already contain
+ * equivalent information in dirent structure but you cannot depend on
+ * this.
+ *
+ * The dirent structure contains several system dependent fields that
+ * generally have no interest to you.  The only interesting one is char
+ * d_name[] that is also portable across different systems.  The d_name
+ * field contains the name of the directory entry without leading path.
+ * While d_name is portable across different systems the actual storage
+ * capacity of d_name varies from system to system and there is no portable
+ * way to find out it at compile time as different systems define the
+ * capacity of d_name with different macros and some systems do not define
+ * capacity at all (besides actual declaration of the field). If you really
+ * need to find out storage capacity of d_name then you might want to try
+ * NAME_MAX macro. The NAME_MAX is defined in POSIX standard althought
+ * there are many MS-DOS and MS-Windows implementations those do not define
+ * it.  There are also systems that declare d_name as "char d_name[1]" and
+ * then allocate suitable amount of memory at run-time.  Thanks to Alain
+ * Decamps (Alain.Decamps@advalvas.be) for pointing it out to me.
+ *
+ * This all leads to the fact that it is difficult to allocate space
+ * for the directory names when the very same program is being compiled on
+ * number of operating systems.  Therefore I suggest that you always
+ * allocate space for directory names dynamically.
+ *
+ * <ret>
+ * Returns a pointer to a structure containing name of the directory entry
+ * in `d_name' field or NULL if there was an error.  In case of an error the
+ * global `errno' variable will set as follows:
+ *
+ * <table>
+ * [EBADF  |dir parameter refers to an invalid directory stream.  This value
+ *          is not set reliably on all implementations.]
+ * </table>
+ * </function>
+ */
+static struct dirent *
+readdir (DIR *dirp)
+{
+  assert(dirp != NULL);
+  if (dirp == NULL) {
+    errno = EBADF;
+    return NULL;
+  }
+
+#if defined(DIRENT_WIN32_INTERFACE)
+  if (dirp->search_handle == INVALID_HANDLE_VALUE) {
+    /* directory stream was opened/rewound incorrectly or it ended normally */
+    errno = EBADF;
+    return NULL;
+  }
+#endif
+
+  if (dirp->dirent_filled != 0) {
+    /*
+     * Directory entry has already been retrieved and there is no need to
+     * retrieve a new one.  Directory entry will be retrieved in advance
+     * when the user calls readdir function for the first time.  This is so
+     * because real dirent has separate functions for opening and reading
+     * the stream whereas Win32 and DOS dirents open the stream
+     * automatically when we retrieve the first file.  Therefore, we have to
+     * save the first file when opening the stream and later we have to
+     * return the saved entry when the user tries to read the first entry.
+     */
+    dirp->dirent_filled = 0;
+  } else {
+    /* fill in entry and return that */
+#if defined(DIRENT_WIN32_INTERFACE)
+    if (FindNextFile (dirp->search_handle, &dirp->current.data) == FALSE) {
+      /* Last file has been processed or an error occured */
+      FindClose (dirp->search_handle);
+      dirp->search_handle = INVALID_HANDLE_VALUE;
+      errno = ENOENT;
+      return NULL;
+    }
+
+# elif defined(DIRENT_MSDOS_INTERFACE)
+    if (_dos_findnext (&dirp->current.data) != 0) {
+      /* _dos_findnext and findnext will set errno to ENOENT when no
+       * more entries could be retrieved. */
+      return NULL;
+    }
+# endif
+
+    _setdirname (dirp);
+    assert (dirp->dirent_filled == 0);
+  }
+  return &dirp->current;
+}
+
+
+/*
+ * <function name="closedir">
+ * <intro>close directory stream.
+ * <syntax>int closedir (DIR *dirp);
+ *
+ * <desc>Close directory stream opened by the `opendir' function.  Close of
+ * directory stream invalidates the DIR structure as well as previously read
+ * dirent entry.
+ *
+ * <ret>The function typically returns 0 on success and -1 on failure but
+ * the function may be declared to return void on same systems.  At least
+ * Borland C/C++ and some UNIX implementations use void as a return type.
+ * The dirent wrapper tries to define VOID_CLOSEDIR whenever closedir is
+ * known to return nothing.  The very same definition is made by the GNU
+ * autoconf if you happen to use it.
+ *
+ * The global `errno' variable will set to EBADF in case of error.
+ * </function>
+ */
+static int
+closedir (DIR *dirp)
+{   
+  int retcode = 0;
+
+  /* make sure that dirp points to legal structure */
+  assert (dirp != NULL);
+  if (dirp == NULL) {
+    errno = EBADF;
+    return -1;
+  }
+  /* free directory name and search handles */
+  if (dirp->dirname != NULL) free (dirp->dirname);
+
+#if defined(DIRENT_WIN32_INTERFACE)
+  if (dirp->search_handle != INVALID_HANDLE_VALUE) {
+    if (FindClose (dirp->search_handle) == FALSE) {
+      /* Unknown error */
+      retcode = -1;
+      errno = EBADF;
+    }
+  }
+#endif                     
+
+  /* clear dirp structure to make sure that it cannot be used anymore*/
+  memset (dirp, 0, sizeof (*dirp));
+# if defined(DIRENT_WIN32_INTERFACE)
+  dirp->search_handle = INVALID_HANDLE_VALUE;
+# endif
+
+  free (dirp);
+  return retcode;
+}
+
+
+/*
+ * <function name="rewinddir">
+ * <intro>rewind directory stream to the beginning
+ * <syntax>void rewinddir (DIR *dirp);
+ *
+ * <desc>Rewind directory stream to the beginning so that the next call of
+ * readdir() returns the very first directory entry again.  However, note
+ * that next call of readdir() may not return the same directory entry as it
+ * did in first time.  The directory stream may have been affected by newly
+ * created files.
+ *
+ * Almost every dirent implementation ensure that rewinddir will update
+ * the directory stream to reflect any changes made to the directory entries
+ * since the previous ``opendir'' or ``rewinddir'' call.  Keep an eye on
+ * this if your program depends on the feature.  I know at least one dirent
+ * implementation where you are required to close and re-open the stream to
+ * see the changes.
+ *
+ * <ret>Returns nothing.  If something went wrong while rewinding, you will
+ * notice it later when you try to retrieve the first directory entry.
+ */
+static void
+rewinddir (DIR *dirp)
+{   
+  /* make sure that dirp is legal */
+  assert (dirp != NULL);
+  if (dirp == NULL) {
+    errno = EBADF;
+    return;
+  }
+  assert (dirp->dirname != NULL);
+  
+  /* close previous stream */
+#if defined(DIRENT_WIN32_INTERFACE)
+  if (dirp->search_handle != INVALID_HANDLE_VALUE) {
+    if (FindClose (dirp->search_handle) == FALSE) {
+      /* Unknown error */
+      errno = EBADF;
+    }
+  }
+#endif
+
+  /* re-open previous stream */
+  if (_initdir (dirp) == 0) {
+    /* initialization failed but we cannot deal with error.  User will notice
+     * error later when she tries to retrieve first directory enty. */
+    /*EMPTY*/;
+  }
+}
+
+
+/*
+ * Open native directory stream object and retrieve first file.
+ * Be sure to close previous stream before opening new one.
+ */
+static int
+_initdir (DIR *dirp)
+{ 
+  assert (dirp != NULL);
+  assert (dirp->dirname != NULL);
+  dirp->dirent_filled = 0;
+
+# if defined(DIRENT_WIN32_INTERFACE)
+  /* Open stream and retrieve first file */
+  dirp->search_handle = FindFirstFile (dirp->dirname, &dirp->current.data);
+  if (dirp->search_handle == INVALID_HANDLE_VALUE) {
+    /* something went wrong but we don't know what.  GetLastError() could
+     * give us more information about the error, but then we should map
+     * the error code into errno. */
+    errno = ENOENT;
+    return 0;
+  }
+
+# elif defined(DIRENT_MSDOS_INTERFACE)
+  if (_dos_findfirst (dirp->dirname,
+          _A_SUBDIR | _A_RDONLY | _A_ARCH | _A_SYSTEM | _A_HIDDEN,
+          &dirp->current.data) != 0)
+  {
+    /* _dos_findfirst and findfirst will set errno to ENOENT when no 
+     * more entries could be retrieved. */
+    return 0;
+  }
+# endif
+
+  /* initialize DIR and it's first entry */
+  _setdirname (dirp);
+  dirp->dirent_filled = 1;
+  return 1;
+}
+
+
+/*
+ * Return implementation dependent name of the current directory entry.
+ */
+static const char *
+_getdirname (const struct dirent *dp)
+{
+#if defined(DIRENT_WIN32_INTERFACE)
+  return dp->data.cFileName;
+  
+#elif defined(DIRENT_USE_FFBLK)
+  return dp->data.ff_name;
+  
+#else
+  return dp->data.name;
+#endif  
+}
+
+
+/*
+ * Copy name of implementation dependent directory entry to the d_name field.
+ */
+static void
+_setdirname (struct DIR *dirp) {
+  /* make sure that d_name is long enough */
+  assert (strlen (_getdirname (&dirp->current)) <= NAME_MAX);
+  
+  strncpy (dirp->current.d_name,
+      _getdirname (&dirp->current),
+      NAME_MAX);
+  dirp->current.d_name[NAME_MAX] = '\0'; /*char d_name[NAME_MAX+1]*/
+}
+  
+# ifdef __cplusplus
+}
+# endif
+# define NAMLEN(dp) ((int)(strlen((dp)->d_name)))
+
+#else
+# error "missing dirent interface"
+#endif
+
+
+#endif /*DIRENT_H*/
diff --git a/src/lib/openjp3d/CMakeLists.txt b/src/lib/openjp3d/CMakeLists.txt
new file mode 100644 (file)
index 0000000..a7b0096
--- /dev/null
@@ -0,0 +1,40 @@
+
+INCLUDE_REGULAR_EXPRESSION("^.*$")
+
+SET(OPENJP3D_LIBRARY_NAME openjp3d)
+# Defines the source code for the library
+SET(OPENJP3D_SRCS
+bio.c  cio.c  dwt.c  event.c  jp3d.c  jp3d_lib.c  mct.c  mqc.c  openjp3d.c  pi.c  raw.c  t1.c  t1_3d.c  t2.c  tcd.c  tgt.c  volume.c
+)
+
+# 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)
+
+# build jp3d lib:
+ADD_LIBRARY(${OPENJP3D_LIBRARY_NAME} ${OPENJP3D_SRCS})
+IF(UNIX)
+  TARGET_LINK_LIBRARIES(${OPENJP3D_LIBRARY_NAME} m)
+ENDIF(UNIX)
+SET_TARGET_PROPERTIES(${OPENJP3D_LIBRARY_NAME} PROPERTIES ${OPENJPEG_LIBRARY_PROPERTIES})
+
+# Install library
+INSTALL(TARGETS ${OPENJP3D_LIBRARY_NAME}
+  EXPORT OpenJP3DTargets
+  DESTINATION ${OPENJPEG_INSTALL_LIB_DIR} 
+  COMPONENT Libraries
+)
+
+# Install includes files
+INSTALL(FILES openjp3d.h
+  DESTINATION ${OPENJP3D_INSTALL_INCLUDE_DIR}/${subdir} 
+  COMPONENT Headers
+)
+#INSTALL(CODE
+#  "EXECUTE_PROCESS(COMMAND ${CMAKE_COMMAND} -E create_symlink ${subdir}/openjp3d.h \$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${OPENJP3D_INSTALL_INCLUDE_DIR}/openjp3d.h)")
+#
diff --git a/src/lib/openjp3d/Makefile.am b/src/lib/openjp3d/Makefile.am
new file mode 100644 (file)
index 0000000..578bcac
--- /dev/null
@@ -0,0 +1,88 @@
+MAINTAINERCLEANFILES = Makefile.in
+
+lib_LTLIBRARIES = libopenjp3dvm.la
+
+includesdir = ${includedir}/openjp3d-@JP3D_MAJOR_NR@.@JP3D_MINOR_NR@
+includes_HEADERS = openjp3d.h
+
+libopenjp3dvm_la_LDFLAGS = -no-undefined -version-info @lt_version_jp3d@
+
+libopenjp3dvm_la_CPPFLAGS = \
+-I. \
+-I$(top_srcdir)/jp3d/libjp3dvm \
+-I$(top_builddir)/jp3d/libjp3dvm
+libopenjp3dvm_la_CFLAGS =
+libopenjp3dvm_la_LIBADD = -lm
+libopenjp3dvm_la_SOURCES = \
+bio.c \
+cio.c \
+dwt.c \
+event.c \
+jp3d.c \
+jp3d_lib.c \
+volume.c \
+mct.c \
+mqc.c \
+openjp3d.c \
+pi.c \
+raw.c \
+t1.c \
+t1_3d.c \
+t2.c \
+tcd.c \
+tgt.c \
+bio.h \
+cio.h \
+dwt.h \
+event.h \
+fix.h \
+int.h \
+jp3d.h \
+jp3d_lib.h \
+mct.h \
+mqc.h \
+opj_includes.h \
+pi.h \
+raw.h \
+t1.h \
+t1_3d.h \
+t2.h \
+tcd.h \
+tgt.h \
+volume.h
+
+EXTRA_DIST = \
+CMakeLists.txt
+
+install-data-hook:
+       cd $(DESTDIR)$(includedir) && \
+         rm -f openjp3d.h && \
+         $(LN_S) openjp3d-@JP3D_MAJOR_NR@.@JP3D_MINOR_NR@/openjp3d.h \
+                 openjp3d.h
+       @echo -e " (LA)\t$(libdir)/libopenjp3dvm.la" >> $(top_builddir)/report.txt
+       @( $(call solist) ) >> $(top_builddir)/report.txt
+       @echo -e " (A)\t$(base)/$(a)" >> $(top_builddir)/report.txt
+       @echo -e " (H)\t$(includedir)/openjp3d-$(MAJOR_NR).$(MINOR_NR)/openjp3d.h" >> $(top_builddir)/report.txt
+       @echo -e " (LN)\t$(includedir)/openjp3d.h" >> $(top_builddir)/report.txt
+
+uninstall-hook:
+       rm -f $(DESTDIR)$(includedir)/openjp3d.h
+
+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/src/lib/openjp3d/bio.c b/src/lib/openjp3d/bio.c
new file mode 100755 (executable)
index 0000000..bc3b113
--- /dev/null
@@ -0,0 +1,189 @@
+/*\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
+ * 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 "opj_includes.h"\r
+\r
+/** @defgroup BIO BIO - Individual bit input-output stream */\r
+/*@{*/\r
+\r
+/** @name Local static functions */\r
+/*@{*/\r
+\r
+/**\r
+Write a bit\r
+@param bio BIO handle\r
+@param b Bit to write (0 or 1)\r
+*/\r
+static void bio_putbit(opj_bio_t *bio, int b);\r
+/**\r
+Read a bit\r
+@param bio BIO handle\r
+@return Returns the read bit\r
+*/\r
+static int bio_getbit(opj_bio_t *bio);\r
+/**\r
+Write a byte\r
+@param bio BIO handle\r
+@return Returns 0 if successful, returns 1 otherwise\r
+*/\r
+static int bio_byteout(opj_bio_t *bio);\r
+/**\r
+Read a byte\r
+@param bio BIO handle\r
+@return Returns 0 if successful, returns 1 otherwise\r
+*/\r
+static int bio_bytein(opj_bio_t *bio);\r
+\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+\r
+/* \r
+==========================================================\r
+   local functions\r
+==========================================================\r
+*/\r
+\r
+static int bio_byteout(opj_bio_t *bio) {\r
+       bio->buf = (bio->buf << 8) & 0xffff;\r
+       bio->ct = bio->buf == 0xff00 ? 7 : 8;\r
+       if (bio->bp >= bio->end) {\r
+               return 1;\r
+       }\r
+       *bio->bp++ = bio->buf >> 8;\r
+       return 0;\r
+}\r
+\r
+static int bio_bytein(opj_bio_t *bio) {\r
+       bio->buf = (bio->buf << 8) & 0xffff;\r
+       bio->ct = bio->buf == 0xff00 ? 7 : 8;\r
+       if (bio->bp >= bio->end) {\r
+               return 1;\r
+       }\r
+       bio->buf |= *bio->bp++;\r
+       return 0;\r
+}\r
+\r
+static void bio_putbit(opj_bio_t *bio, int b) {\r
+       if (bio->ct == 0) {\r
+               bio_byteout(bio);\r
+       }\r
+       bio->ct--;\r
+       bio->buf |= b << bio->ct;\r
+}\r
+\r
+/* MOD antonin */\r
+static int bio_getbit(opj_bio_t *bio) {\r
+/* DOM */\r
+       if (bio->ct == 0) {\r
+               bio_bytein(bio);\r
+       }\r
+       bio->ct--;\r
+       return (bio->buf >> bio->ct) & 1;\r
+}\r
+\r
+/* \r
+==========================================================\r
+   Bit Input/Output interface\r
+==========================================================\r
+*/\r
+\r
+opj_bio_t* bio_create() {\r
+       opj_bio_t *bio = (opj_bio_t*)opj_malloc(sizeof(opj_bio_t));\r
+       return bio;\r
+}\r
+\r
+void bio_destroy(opj_bio_t *bio) {\r
+       if(bio) {\r
+               opj_free(bio);\r
+       }\r
+}\r
+\r
+int bio_numbytes(opj_bio_t *bio) {\r
+       return (bio->bp - bio->start);\r
+}\r
+\r
+void bio_init_enc(opj_bio_t *bio, unsigned char *bp, int len) {\r
+       bio->start = bp;\r
+       bio->end = bp + len;\r
+       bio->bp = bp;\r
+       bio->buf = 0;\r
+       bio->ct = 8;\r
+}\r
+\r
+void bio_init_dec(opj_bio_t *bio, unsigned char *bp, int len) {\r
+       bio->start = bp;\r
+       bio->end = bp + len;\r
+       bio->bp = bp;\r
+       bio->buf = 0;\r
+       bio->ct = 0;\r
+}\r
+\r
+void bio_write(opj_bio_t *bio, int v, int n) {\r
+       int i;\r
+       for (i = n - 1; i >= 0; i--) {\r
+               bio_putbit(bio, (v >> i) & 1);\r
+       }\r
+}\r
+\r
+int bio_read(opj_bio_t *bio, int n) {\r
+       int i, v;\r
+       v = 0;\r
+       for (i = n - 1; i >= 0; i--) {\r
+               v += bio_getbit(bio) << i;\r
+       }\r
+       return v;\r
+}\r
+\r
+int bio_flush(opj_bio_t *bio) {\r
+       bio->ct = 0;\r
+       if (bio_byteout(bio)) {\r
+               return 1;\r
+       }\r
+       if (bio->ct == 7) {\r
+               bio->ct = 0;\r
+               if (bio_byteout(bio)) {\r
+                       return 1;\r
+               }\r
+       }\r
+       return 0;\r
+}\r
+\r
+int bio_inalign(opj_bio_t *bio) {\r
+       bio->ct = 0;\r
+       if ((bio->buf & 0xff) == 0xff) {\r
+               if (bio_bytein(bio)) {\r
+                       return 1;\r
+               }\r
+               bio->ct = 0;\r
+       }\r
+       return 0;\r
+}\r
diff --git a/src/lib/openjp3d/bio.h b/src/lib/openjp3d/bio.h
new file mode 100755 (executable)
index 0000000..36bb942
--- /dev/null
@@ -0,0 +1,132 @@
+/*\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
+ * 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 __BIO_H\r
+#define __BIO_H\r
+/** \r
+@file bio.h\r
+@brief Implementation of an individual bit input-output (BIO)\r
+\r
+The functions in BIO.C have for goal to realize an individual bit input - output.\r
+*/\r
+\r
+/** @defgroup BIO BIO - Individual bit input-output stream */\r
+/*@{*/\r
+\r
+/**\r
+Individual bit input-output stream (BIO)\r
+*/\r
+typedef struct opj_bio {\r
+/** pointer to the start of the buffer */\r
+       unsigned char *start;   \r
+/** pointer to the end of the buffer */\r
+       unsigned char *end;             \r
+/** pointer to the present position in the buffer */\r
+       unsigned char *bp;              \r
+/** temporary place where each byte is read or written */\r
+       unsigned int buf;               \r
+/** coder : number of bits free to write. decoder : number of bits read */\r
+       int ct;                                 \r
+} opj_bio_t;\r
+\r
+/** @name Funciones generales */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Create a new BIO handle \r
+@return Returns a new BIO handle if successful, returns NULL otherwise\r
+*/\r
+opj_bio_t* bio_create();\r
+/**\r
+Destroy a previously created BIO handle\r
+@param bio BIO handle to destroy\r
+*/\r
+void bio_destroy(opj_bio_t *bio);\r
+/**\r
+Number of bytes written.\r
+@param bio BIO handle\r
+@return Returns the number of bytes written\r
+*/\r
+int bio_numbytes(opj_bio_t *bio);\r
+/**\r
+Init encoder\r
+@param bio BIO handle\r
+@param bp Output buffer\r
+@param len Output buffer length \r
+*/\r
+void bio_init_enc(opj_bio_t *bio, unsigned char *bp, int len);\r
+/**\r
+Init decoder\r
+@param bio BIO handle\r
+@param bp Input buffer\r
+@param len Input buffer length \r
+*/\r
+void bio_init_dec(opj_bio_t *bio, unsigned char *bp, int len);\r
+/**\r
+Write bits\r
+@param bio BIO handle\r
+@param v Value of bits\r
+@param n Number of bits to write\r
+*/\r
+void bio_write(opj_bio_t *bio, int v, int n);\r
+/**\r
+Read bits\r
+@param bio BIO handle\r
+@param n Number of bits to read \r
+@return Returns the corresponding read number\r
+*/\r
+int bio_read(opj_bio_t *bio, int n);\r
+/**\r
+Flush bits\r
+@param bio BIO handle\r
+@return Returns 1 if successful, returns 0 otherwise\r
+*/\r
+int bio_flush(opj_bio_t *bio);\r
+/**\r
+Passes the ending bits (coming from flushing)\r
+@param bio BIO handle\r
+@return Returns 1 if successful, returns 0 otherwise\r
+*/\r
+int bio_inalign(opj_bio_t *bio);\r
+/**\r
+Read a bit\r
+@param bio BIO handle\r
+@return Returns the read bit\r
+*/\r
+/* MOD antonin */\r
+//int bio_getbit(opj_bio_t *bio);\r
+/* DOM */\r
+/* ----------------------------------------------------------------------- */\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* __BIO_H */\r
+\r
diff --git a/src/lib/openjp3d/cio.c b/src/lib/openjp3d/cio.c
new file mode 100755 (executable)
index 0000000..4ac64fd
--- /dev/null
@@ -0,0 +1,217 @@
+/*\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
+ * 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 "opj_includes.h"\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+opj_cio_t* OPJ_CALLCONV opj_cio_open(opj_common_ptr cinfo, unsigned char *buffer, int length) {\r
+       opj_cp_t *cp = NULL;\r
+       opj_cio_t *cio = (opj_cio_t*)opj_malloc(sizeof(opj_cio_t));\r
+       if(!cio) return NULL;\r
+       cio->cinfo = cinfo;\r
+       if(buffer && length) {\r
+               /* wrap a user buffer containing the encoded image */\r
+               cio->openmode = OPJ_STREAM_READ;\r
+               cio->buffer = buffer;\r
+               cio->length = length;\r
+       }\r
+       else if(!buffer && !length && cinfo) {\r
+               /* allocate a buffer for the encoded image */\r
+               cio->openmode = OPJ_STREAM_WRITE;\r
+               switch(cinfo->codec_format) {\r
+                       case CODEC_J3D:\r
+                       case CODEC_J2K:\r
+                               cp = ((opj_j3d_t*)cinfo->j3d_handle)->cp;\r
+                               break;\r
+                       default:\r
+                               opj_free(cio);\r
+                               return NULL;\r
+               }\r
+               cio->length = cp->tdx * cp->tdy * cp->tdz * cp->tw * cp->th * cp->tl * 4;\r
+               cio->buffer = (unsigned char *)opj_malloc(cio->length);\r
+               if(!cio->buffer) {\r
+                       opj_free(cio);\r
+                       return NULL;\r
+               }\r
+       }\r
+       else {\r
+               opj_free(cio);\r
+               return NULL;\r
+       }\r
+\r
+       /* Initialize byte IO */\r
+       cio->start = cio->buffer;\r
+       cio->end = cio->buffer + cio->length;\r
+       cio->bp = cio->buffer;\r
+\r
+       return cio;\r
+}\r
+\r
+void OPJ_CALLCONV opj_cio_close(opj_cio_t *cio) {\r
+       if(cio) {\r
+               if(cio->openmode == OPJ_STREAM_WRITE) {\r
+                       /* destroy the allocated buffer */\r
+                       opj_free(cio->buffer);\r
+               }\r
+               /* destroy the cio */\r
+               opj_free(cio);\r
+       }\r
+}\r
+\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+/*\r
+ * Get position in byte stream.\r
+ */\r
+int OPJ_CALLCONV cio_tell(opj_cio_t *cio) {\r
+       return cio->bp - cio->start;\r
+}\r
+\r
+/*\r
+ * Set position in byte stream.\r
+ *\r
+ * pos : position, in number of bytes, from the beginning of the stream\r
+ */\r
+void OPJ_CALLCONV cio_seek(opj_cio_t *cio, int pos) {\r
+       cio->bp = cio->start + pos;\r
+}\r
+\r
+/*\r
+ * Number of bytes left before the end of the stream.\r
+ */\r
+int cio_numbytesleft(opj_cio_t *cio) {\r
+       return cio->end - cio->bp;\r
+}\r
+\r
+/*\r
+ * Get pointer to the current position in the stream.\r
+ */\r
+unsigned char *cio_getbp(opj_cio_t *cio) {\r
+       return cio->bp;\r
+}\r
+\r
+/*\r
+ * Write a byte.\r
+ */\r
+bool cio_byteout(opj_cio_t *cio, unsigned char v) {\r
+       if (cio->bp >= cio->end) {\r
+               opj_event_msg(cio->cinfo, EVT_ERROR, "write error\n");\r
+               return false;\r
+       }\r
+       *cio->bp++ = v;\r
+       return true;\r
+}\r
+\r
+/*\r
+ * Read a byte.\r
+ */\r
+unsigned char cio_bytein(opj_cio_t *cio) {\r
+       if (cio->bp >= cio->end) {\r
+               opj_event_msg(cio->cinfo, EVT_ERROR, "read error\n");\r
+               return 0;\r
+       }\r
+       return *cio->bp++;\r
+}\r
+\r
+/*\r
+ * Write some bytes.\r
+ *\r
+ * v : value to write\r
+ * n : number of bytes to write\r
+ */\r
+unsigned int cio_write(opj_cio_t *cio, unsigned int v, int n) {\r
+       int i;\r
+       for (i = n - 1; i >= 0; i--) {\r
+               if( !cio_byteout(cio, (unsigned char) ((v >> (i << 3)) & 0xff)) )\r
+                       return 0;\r
+       }\r
+       return n;\r
+}\r
+\r
+/*\r
+ * Read some bytes.\r
+ *\r
+ * n : number of bytes to read\r
+ *\r
+ * return : value of the n bytes read\r
+ */\r
+unsigned int cio_read(opj_cio_t *cio, int n) {\r
+       int i;\r
+       unsigned int v;\r
+       v = 0;\r
+       for (i = n - 1; i >= 0; i--) {\r
+               v += cio_bytein(cio) << (i << 3);\r
+       }\r
+       return v;\r
+}\r
+\r
+/* \r
+ * Skip some bytes.\r
+ *\r
+ * n : number of bytes to skip\r
+ */\r
+void cio_skip(opj_cio_t *cio, int n) {\r
+       cio->bp += n;\r
+}\r
+\r
+/*\r
+ * Write some bytes.\r
+ *\r
+ * v : value to write\r
+ * n : number of bytes to write\r
+ */\r
+int cio_write_int(opj_cio_t *cio, int v, int n) {\r
+       int i;\r
+       for (i = n - 1; i >= 0; i--) {\r
+               if( !cio_byteout(cio, (char) ((v >> (i << 3)) & 0xff)) )\r
+                       return 0;\r
+       }\r
+       return n;\r
+}\r
+\r
+/*\r
+ * Read some bytes.\r
+ *\r
+ * n : number of bytes to read\r
+ *\r
+ * return : value of the n bytes read\r
+ */\r
+int cio_read_int(opj_cio_t *cio, int n) {\r
+       int i;\r
+       int v;\r
+       v = 0;\r
+       for (i = n - 1; i >= 0; i--) {\r
+               v += cio_bytein(cio) << (i << 3);\r
+       }\r
+       return v;\r
+}\r
+\r
diff --git a/src/lib/openjp3d/cio.h b/src/lib/openjp3d/cio.h
new file mode 100755 (executable)
index 0000000..b7b0c41
--- /dev/null
@@ -0,0 +1,100 @@
+/*\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
+ * 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 __CIO_H\r
+#define __CIO_H\r
+/**\r
+@file cio.h\r
+@brief Implementation of a byte input-output process (CIO)\r
+\r
+The functions in CIO.C have for goal to realize a byte input / output process.\r
+*/\r
+\r
+/** @defgroup CIO CIO - byte input-output stream */\r
+/*@{*/\r
+\r
+/** @name Funciones generales (see also openjp3d.h) */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Number of bytes left before the end of the stream\r
+@param cio CIO handle\r
+@return Returns the number of bytes before the end of the stream\r
+*/\r
+int cio_numbytesleft(opj_cio_t *cio);\r
+/**\r
+Get pointer to the current position in the stream\r
+@param cio CIO handle\r
+@return Returns a pointer to the current position\r
+*/\r
+unsigned char *cio_getbp(opj_cio_t *cio);\r
+/**\r
+Write some bytes\r
+@param cio CIO handle\r
+@param v Value to write\r
+@param n Number of bytes to write\r
+@return Returns the number of bytes written or 0 if an error occured\r
+*/\r
+unsigned int cio_write(opj_cio_t *cio, unsigned int v, int n);\r
+/**\r
+Read some bytes\r
+@param cio CIO handle\r
+@param n Number of bytes to read\r
+@return Returns the value of the n bytes read\r
+*/\r
+unsigned int cio_read(opj_cio_t *cio, int n);\r
+/**\r
+Skip some bytes\r
+@param cio CIO handle\r
+@param n Number of bytes to skip\r
+*/\r
+void cio_skip(opj_cio_t *cio, int n);\r
+/**\r
+Write some bytes\r
+@param cio CIO handle\r
+@param v Signed integer value to write\r
+@param n Number of bytes to write\r
+@return Returns the number of bytes written or 0 if an error occured\r
+*/\r
+int cio_write_int(opj_cio_t *cio, int v, int n);\r
+/**\r
+Read some bytes\r
+@param cio CIO handle\r
+@param n Number of bytes to read\r
+@return Returns the value of the n bytes read\r
+*/\r
+int cio_read_int(opj_cio_t *cio, int n);\r
+/* ----------------------------------------------------------------------- */\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* __CIO_H */\r
+\r
diff --git a/src/lib/openjp3d/dwt.c b/src/lib/openjp3d/dwt.c
new file mode 100755 (executable)
index 0000000..8f30dae
--- /dev/null
@@ -0,0 +1,1016 @@
+/*
+ * 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
+ * Copyrigth (c) 2006, Mónica Díez, LPI-UVA, Spain
+ * 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.
+ */
+
+/*
+ *  NOTE:
+ *  This is a modified version of the openjpeg dwt.c file.
+ *  Average speed improvement compared to the original file (measured on
+ *  my own machine, a P4 running at 3.0 GHz):
+ *  5x3 wavelets about 2 times faster
+ *  9x7 wavelets about 3 times faster
+ *  for both, encoding and decoding.
+ *
+ *  The better performance is caused by doing the 1-dimensional DWT
+ *  within a temporary buffer where the data can be accessed sequential
+ *  for both directions, horizontal and vertical. The 2d vertical DWT was
+ *  the major bottleneck in the former version.
+ *
+ *  I have also removed the "Add Patrick" part because it is not longer
+ *  needed.  
+ *
+ *  6/6/2005
+ *  -Ive (aka Reiner Wahler)
+ *  mail: ive@lilysoft.com
+ */
+
+#include "opj_includes.h"
+
+/** @defgroup DWT DWT - Implementation of a discrete wavelet transform */
+/*@{*/
+
+/** @name Local static functions */
+/*@{*/
+unsigned int ops;
+/**
+Forward lazy transform (horizontal)
+*/
+static void dwt_deinterleave_h(int *a, int *b, int dn, int sn, int cas);
+/**
+Forward lazy transform (vertical)
+*/
+static void dwt_deinterleave_v(int *a, int *b, int dn, int sn, int x, int cas);
+/**
+Forward lazy transform (axial)
+*/
+static void dwt_deinterleave_z(int *a, int *b, int dn, int sn, int xy, int cas);
+/**
+Inverse lazy transform (horizontal)
+*/
+static void dwt_interleave_h(int *a, int *b, int dn, int sn, int cas);
+/**
+Inverse lazy transform (vertical)
+*/
+static void dwt_interleave_v(int *a, int *b, int dn, int sn, int x, int cas);
+/**
+Inverse lazy transform (axial)
+*/
+static void dwt_interleave_z(int *a, int *b, int dn, int sn, int xy, int cas);
+/**
+Forward 5-3 wavelet tranform in 1-D
+*/
+static void dwt_encode_53(int *a, int dn, int sn, int cas);
+static void dwt_encode_97(int *a, int dn, int sn, int cas);
+/**
+Inverse 5-3 wavelet tranform in 1-D
+*/
+static void dwt_decode_53(int *a, int dn, int sn, int cas);
+static void dwt_decode_97(int *a, int dn, int sn, int cas);
+/**
+Computing of wavelet transform L2 norms for arbitrary transforms
+*/
+static double dwt_calc_wtnorms(int orient, int level[3], int dwtid[3], opj_wtfilt_t *wtfiltx, opj_wtfilt_t *wtfilty, opj_wtfilt_t *wtfiltz);
+/**
+Encoding of quantification stepsize
+*/
+static void dwt_encode_stepsize(int stepsize, int numbps, opj_stepsize_t *bandno_stepsize);
+/*@}*/
+
+/*@}*/
+
+#define S(i) a[(i)*2]
+#define D(i) a[(1+(i)*2)]
+#define S_(i) ((i)<0?S(0):((i)>=sn?S(sn-1):S(i)))
+#define D_(i) ((i)<0?D(0):((i)>=dn?D(dn-1):D(i)))
+/* new */
+#define SS_(i) ((i)<0?S(0):((i)>=dn?S(dn-1):S(i)))
+#define DD_(i) ((i)<0?D(0):((i)>=sn?D(sn-1):D(i)))
+
+/* <summary>                                                              */
+/* This table contains the norms of the 5-3 wavelets for different bands. */
+/* </summary>                                                             */
+static double dwt_norm[10][10][10][8];
+static int flagnorm[10][10][10][8];
+
+/*static const double dwt_norms[5][8][10] = {
+       {//ResZ=1
+               {1.000, 1.500, 2.750, 5.375, 10.68, 21.34, 42.67, 85.33, 170.7, 341.3},
+               {1.038, 1.592, 2.919, 5.703, 11.33, 22.64, 45.25, 90.48, 180.9},
+               {1.038, 1.592, 2.919, 5.703, 11.33, 22.64, 45.25, 90.48, 180.9},
+               {.7186, .9218, 1.586, 3.043, 6.019, 12.01, 24.00, 47.97, 95.93}
+       },{//ResZ=2
+               {1.000, 1.8371, 2.750, 5.375, 10.68, 21.34, 42.67, 85.33, 170.7, 341.3},
+               {1.2717, 1.592, 2.919, 5.703, 11.33, 22.64, 45.25, 90.48, 180.9},
+               {1.2717, 1.592, 2.919, 5.703, 11.33, 22.64, 45.25, 90.48, 180.9},
+               {.8803, .9218, 1.586, 3.043, 6.019, 12.01, 24.00, 47.97, 95.93},
+               {1.2717},
+               {.8803},
+               {.8803},
+               {.6093},
+       },{ //ResZ=3
+               {1.000, 1.8371, 4.5604, 5.375, 10.68, 21.34, 42.67, 85.33, 170.7, 341.3},
+               {1.2717, 2.6403, 2.919, 5.703, 11.33, 22.64, 45.25, 90.48, 180.9},
+               {1.2717, 2.6403, 2.919, 5.703, 11.33, 22.64, 45.25, 90.48, 180.9},
+               {.8803, 1.5286, 1.586, 3.043, 6.019, 12.01, 24.00, 47.97, 95.93},
+               {1.2717, 2.6403},
+               {.8803, 1.5286},
+               {.8803, 1.5286},
+               {.6093, 0.8850},
+       },{ //ResZ=4
+               {1.000, 1.8371, 4.5604, 12.4614, 10.68, 21.34, 42.67, 85.33, 170.7, 341.3},
+               {1.2717, 2.6403, 6.7691 , 5.703, 11.33, 22.64, 45.25, 90.48, 180.9},
+               {1.2717, 2.6403, 6.7691 , 5.703, 11.33, 22.64, 45.25, 90.48, 180.9},
+               {.8803, 1.5286, 3.6770 , 3.043, 6.019, 12.01, 24.00, 47.97, 95.93},
+               {1.2717, 2.6403, 6.7691 },
+               {.8803, 1.5286, 3.6770 },
+               {.8803, 1.5286, 3.6770 },
+               {.6093, 0.8850, 1.9974 },
+       },{ //ResZ=5
+               {1.000, 1.8371, 4.5604, 12.4614, 34.9025, 21.34, 42.67, 85.33, 170.7, 341.3},
+               {1.2717, 2.6403, 6.7691 , 18.6304 , 11.33, 22.64, 45.25, 90.48, 180.9},
+               {1.2717, 2.6403, 6.7691 , 18.6304, 11.33, 22.64, 45.25, 90.48, 180.9},
+               {.8803, 1.5286, 3.6770 , 9.9446, 6.019, 12.01, 24.00, 47.97, 95.93},
+               {1.2717, 2.6403, 6.7691, 18.6304},
+               {.8803, 1.5286, 3.6770, 9.9446 },
+               {.8803, 1.5286, 3.6770, 9.9446 },
+               {.6093, 0.8850, 1.9974, 5.3083 },
+       }
+};*/
+
+/* <summary>                                                              */
+/* This table contains the norms of the 9-7 wavelets for different bands. */
+/* </summary>                                                             */
+/*static const double dwt_norms_real[5][8][10] = {
+       {//ResZ==1
+               {1.000, 1.9659, 4.1224, 8.4167, 16.9356, 33.9249, 67.8772, 135.7680, 271.5430, 543.0894},
+               {1.0113, 1.9968, 4.1834, 8.5341, 17.1667, 34.3852, 68.7967, 137.6065, 275.2196},
+               {1.0113, 1.9968, 4.1834, 8.5341, 17.1667, 34.3852, 68.7967, 137.6065, 275.2196},
+               {0.5202, 0.9672, 2.0793, 4.3005, 8.6867, 17.4188, 34.8608, 69.7332, 139.4722}
+       }, { //ResZ==2
+               {1.000, 2.7564, 4.1224, 8.4167, 16.9356, 33.9249, 67.8772, 135.7680, 271.5430, 543.0894},
+               {1.4179, 1.9968, 4.1834, 8.5341, 17.1667, 34.3852, 68.7967, 137.6065, 275.2196},
+               {1.4179, 1.9968, 4.1834, 8.5341, 17.1667, 34.3852, 68.7967, 137.6065, 275.2196},
+               {0.7294, 0.9672, 2.0793, 4.3005, 8.6867, 17.4188, 34.8608, 69.7332, 139.4722},
+               {1.4179},
+               {0.7294},
+               {0.7294},
+               {0.3752} //HHH
+       },{ //ResZ==3
+               {1.000, 2.7564, 8.3700, 8.4167, 16.9356, 33.9249, 67.8772, 135.7680, 271.5430, 543.0894},
+               {1.4179, 4.0543, 4.1834, 8.5341, 17.1667, 34.3852, 68.7967, 137.6065, 275.2196},
+               {1.4179, 4.0543, 4.1834, 8.5341, 17.1667, 34.3852, 68.7967, 137.6065, 275.2196},
+               {0.7294, 1.9638, 2.0793, 4.3005, 8.6867, 17.4188, 34.8608, 69.7332, 139.4722},
+               {1.4179, 4.0543},
+               {0.7294, 1.9638},
+               {0.7294, 1.9638},
+               {0.3752, 0.9512} //HHH
+       },{ //ResZ==4
+               {1.000, 2.7564, 8.3700, 24.4183, 16.9356, 33.9249, 67.8772, 135.7680, 271.5430, 543.0894},
+               {1.4179, 4.0543, 12.1366, 8.5341, 17.1667, 34.3852, 68.7967, 137.6065, 275.2196},
+               {1.4179, 4.0543, 12.1366, 8.5341, 17.1667, 34.3852, 68.7967, 137.6065, 275.2196},
+               {0.7294, 1.9638, 6.0323, 4.3005, 8.6867, 17.4188, 34.8608, 69.7332, 139.4722},
+               {1.4179, 4.0543, 12.1366},
+               {0.7294, 1.9638, 6.0323},
+               {0.7294, 1.9638, 6.0323},
+               {0.3752, 0.9512, 2.9982} //HHH
+       },{ //ResZ==5
+               {1.000, 2.7564, 8.3700, 24.4183, 69.6947, 33.9249, 67.8772, 135.7680, 271.5430, 543.0894},
+               {1.4179, 4.0543, 12.1366, 35.1203, 17.1667, 34.3852, 68.7967, 137.6065, 275.2196},
+               {1.4179, 4.0543, 12.1366, 35.1203, 17.1667, 34.3852, 68.7967, 137.6065, 275.2196},
+               {0.7294, 1.9638, 6.0323, 17.6977, 8.6867, 17.4188, 34.8608, 69.7332, 139.4722},
+               {1.4179, 4.0543, 12.1366, 35.1203},
+               {0.7294, 1.9638, 6.0323, 17.6977},
+               {0.7294, 1.9638, 6.0323, 17.6977},
+               {0.3752, 0.9512, 2.9982, 8.9182} //HHH
+       }
+};*/
+
+static opj_atk_t atk_info_wt[] = {
+       {0, 1, J3D_ATK_WS, J3D_ATK_IRR, 0, J3D_ATK_WS, 1.230174104, 4, {0}, {0}, {0}, {1,1,1,1}, {-1.586134342059924, -0.052980118572961, 0.882911075530934, 0.443506852043971}},/* WT 9-7 IRR*/
+       {1, 0, J3D_ATK_WS, J3D_ATK_REV, 0, J3D_ATK_WS, 0, 2, {0}, {1,2}, {1,2}, {1,1}, {-1,1}},/* WT 5-3 REV*/
+       {2, 0, J3D_ATK_ARB, J3D_ATK_REV, 0, J3D_ATK_CON, 0, 2, {0,0}, {0,1}, {0,1}, {1,1}, {{-1},{1}}}, /* WT 2-2 REV*/
+       {3, 0, J3D_ATK_ARB, J3D_ATK_REV, 1, J3D_ATK_CON, 0, 3, {0,0,-1}, {0,1,2}, {0,1,2}, {1,1,3}, {{-1},{1},{1,0,-1}}}, /* WT 2-6 REV*/
+       {4, 0, J3D_ATK_ARB, J3D_ATK_REV, 1, J3D_ATK_CON, 0, 3, {0,0,-2}, {0,1,6}, {0,1,32}, {1,1,5}, {{-1},{1},{-3,22,0,-22,3}}}, /* WT 2-10 REV*/
+       {5, 1, J3D_ATK_ARB, J3D_ATK_IRR, 1, J3D_ATK_WS, 1, 7, {0}, {0}, {0}, {1,1,2,1,2,1,3},{{-1},{1.58613434206},{-0.460348209828, 0.460348209828},{0.25},{0.374213867768,-0.374213867768},{-1.33613434206},{0.29306717103,0,-0.29306717103}}}, /* WT 6-10 IRR*/
+       {6, 1, J3D_ATK_ARB, J3D_ATK_IRR, 0, J3D_ATK_WS, 1, 11, {0}, {0}, {0}, {1,1,2,1,2,1,2,1,2,1,5},{{-1},{0,99715069105},{-1.00573127827, 1.00573127827},{-0.27040357631},{2.20509972343, -2.20509972343},{0.08059995736},
+               {-1.62682532350, 1.62682532350},{0.52040357631},{0.60404664250, -0.60404664250},{-0.82775064841},{-0.06615812964, 0.29402137720, 0, -0.29402137720, 0.06615812964}}}, /* WT 10-18 IRR*/
+       {7, 1, J3D_ATK_WS, J3D_ATK_IRR, 0, J3D_ATK_WS, 1, 2, {0}, {0}, {0}, {1,1}, {-0.5, 0.25}},       /* WT 5-3 IRR*/
+       {8, 0, J3D_ATK_WS, J3D_ATK_REV, 0, J3D_ATK_WS, 0, 2, {0}, {4,4}, {8,8}, {2,2}, {{-9,1},{5,-1}}}         /* WT 13-7 REV*/
+};
+/* 
+==========================================================
+   local functions
+==========================================================
+*/
+
+/* <summary>                                    */
+/* Forward lazy transform (horizontal).  */
+/* </summary>                            */ 
+static void dwt_deinterleave_h(int *a, int *b, int dn, int sn, int cas) {
+       int i;
+    for (i=0; i<sn; i++) b[i]=a[2*i+cas];
+    for (i=0; i<dn; i++) b[sn+i]=a[(2*i+1-cas)];
+}
+
+/* <summary>                             */  
+/* Forward lazy transform (vertical).    */
+/* </summary>                            */ 
+static void dwt_deinterleave_v(int *a, int *b, int dn, int sn, int x, int cas) {
+    int i;
+    for (i=0; i<sn; i++) b[i*x]=a[2*i+cas];
+    for (i=0; i<dn; i++) b[(sn+i)*x]=a[(2*i+1-cas)];
+}
+
+/* <summary>                             */  
+/* Forward lazy transform (axial).       */
+/* </summary>                            */ 
+static void dwt_deinterleave_z(int *a, int *b, int dn, int sn, int xy, int cas) {
+    int i;
+    for (i=0; i<sn; i++) b[i*xy]=a[2*i+cas];
+    for (i=0; i<dn; i++) b[(sn+i)*xy]=a[(2*i+1-cas)];
+}
+
+/* <summary>                             */
+/* Inverse lazy transform (horizontal).  */
+/* </summary>                            */
+static void dwt_interleave_h(int *a, int *b, int dn, int sn, int cas) {
+    int i;
+    int *ai = NULL;
+    int *bi = NULL;
+    ai = a;
+    bi = b + cas;
+    for (i = 0; i < sn; i++) {
+      *bi = *ai;  
+         bi += 2;  
+         ai++;
+    }
+    ai = a + sn;
+    bi = b + 1 - cas;
+    for (i = 0; i < dn; i++) {
+      *bi = *ai;
+         bi += 2;
+         ai++;
+    }
+}
+
+/* <summary>                             */  
+/* Inverse lazy transform (vertical).    */
+/* </summary>                            */ 
+static void dwt_interleave_v(int *a, int *b, int dn, int sn, int x, int cas) {
+    int i;
+    int *ai = NULL;
+    int *bi = NULL;
+    ai = a;
+    bi = b + cas;
+    for (i = 0; i < sn; i++) {
+      *bi = *ai;
+         bi += 2;
+         ai += x;
+    }
+    ai = a + (sn * x);
+    bi = b + 1 - cas;
+    for (i = 0; i < dn; i++) {
+      *bi = *ai;
+         bi += 2;  
+         ai += x;
+    }
+}
+
+/* <summary>                             */
+/* Inverse lazy transform (axial).  */
+/* </summary>                            */
+static void dwt_interleave_z(int *a, int *b, int dn, int sn, int xy, int cas) {
+    int i;
+    int *ai = NULL;
+    int *bi = NULL;
+    ai = a;
+    bi = b + cas;
+    for (i = 0; i < sn; i++) {
+      *bi = *ai;  
+         bi += 2;  
+         ai += xy;
+    }
+    ai = a + (sn * xy);
+    bi = b + 1 - cas;
+    for (i = 0; i < dn; i++) {
+      *bi = *ai;
+         bi += 2;
+         ai += xy;
+    }
+}
+
+
+/* <summary>                            */
+/* Forward 5-3 or 9-7 wavelet tranform in 1-D. */
+/* </summary>                           */
+static void dwt_encode_53(int *a, int dn, int sn, int cas) {
+       int i;
+
+       if (!cas) {
+               if ((dn > 0) || (sn > 1)) {     /* NEW :  CASE ONE ELEMENT */
+                       //for (i = 0; i < dn; i++) D(i) -= (S_(i) + S_(i + 1)) >> 1;
+                       //for (i = 0; i < sn; i++) S(i) += (D_(i - 1) + D_(i) + 2) >> 2;
+                       for (i = 0; i < dn; i++){
+                               D(i) -= (S_(i) + S_(i + 1)) >> 1;
+                               //ops += 2;
+                       }
+                       for (i = 0; i < sn; i++){
+                               S(i) += (D_(i - 1) + D_(i) + 2) >> 2;
+                               //ops += 3;
+                       }
+               }
+       } else {
+               /*if (!sn && dn == 1)
+                       S(0) *= 2;
+               else {
+                       for (i = 0; i < dn; i++) S(i) -= (DD_(i) + DD_(i - 1)) >> 1;
+                       for (i = 0; i < sn; i++) D(i) += (SS_(i) + SS_(i + 1) + 2) >> 2;
+               }*/
+               if (!sn && dn == 1){
+                       S(0) *= 2;
+                       //ops++;
+               } else {
+                       for (i = 0; i < dn; i++){
+                               S(i) -= (DD_(i) + DD_(i - 1)) >> 1;
+                       //      ops += 2;
+                       }
+                       for (i = 0; i < sn; i++){
+                               D(i) += (SS_(i) + SS_(i + 1) + 2) >> 2;
+                       //      ops += 3;
+                       }
+               }
+       }
+}
+static void dwt_encode_97(int *a, int dn, int sn, int cas) {
+       int i;
+
+       if (!cas) {
+                       if ((dn > 0) || (sn > 1)) {     /* NEW :  CASE ONE ELEMENT */
+                               for (i = 0; i < dn; i++)
+                                       D(i) -= fix_mul(S_(i) + S_(i + 1), 12993);
+                               for (i = 0; i < sn; i++)
+                                       S(i) -= fix_mul(D_(i - 1) + D_(i), 434);
+                               for (i = 0; i < dn; i++)
+                                       D(i) += fix_mul(S_(i) + S_(i + 1), 7233);
+                               for (i = 0; i < sn; i++)
+                                       S(i) += fix_mul(D_(i - 1) + D_(i), 3633);
+                               for (i = 0; i < dn; i++)
+                                       D(i) = fix_mul(D(i), 5038);     /*5038 */
+                               for (i = 0; i < sn; i++)
+                                       S(i) = fix_mul(S(i), 6659);     /*6660 */
+                       }
+               } else {
+                       if ((sn > 0) || (dn > 1)) {     /* NEW :  CASE ONE ELEMENT */
+                               for (i = 0; i < dn; i++)
+                                       S(i) -= fix_mul(DD_(i) + DD_(i - 1), 12993);
+                               for (i = 0; i < sn; i++)
+                                       D(i) -= fix_mul(SS_(i) + SS_(i + 1), 434);
+                               for (i = 0; i < dn; i++)
+                                       S(i) += fix_mul(DD_(i) + DD_(i - 1), 7233);
+                               for (i = 0; i < sn; i++)
+                                       D(i) += fix_mul(SS_(i) + SS_(i + 1), 3633);
+                               for (i = 0; i < dn; i++)
+                                       S(i) = fix_mul(S(i), 5038);     /*5038 */
+                               for (i = 0; i < sn; i++)
+                                       D(i) = fix_mul(D(i), 6659);     /*6660 */
+                       }
+               }
+}
+/* <summary>                            */
+/* Inverse 5-3 or 9-7 wavelet tranform in 1-D. */
+/* </summary>                           */ 
+static void dwt_decode_53(int *a, int dn, int sn, int cas) {
+       int i;
+       if (!cas) {
+               if ((dn > 0) || (sn > 1)) { /* NEW :  CASE ONE ELEMENT */
+                       for (i = 0; i < sn; i++) S(i) -= (D_(i - 1) + D_(i) + 2) >> 2;
+                       for (i = 0; i < dn; i++) D(i) += (S_(i) + S_(i + 1)) >> 1;
+               }
+       } else {
+               if (!sn  && dn == 1)          /* NEW :  CASE ONE ELEMENT */
+                       S(0) /= 2;
+               else {
+                       for (i = 0; i < sn; i++) D(i) -= (SS_(i) + SS_(i + 1) + 2) >> 2;
+                       for (i = 0; i < dn; i++) S(i) += (DD_(i) + DD_(i - 1)) >> 1;
+               }
+       }
+}
+static void dwt_decode_97(int *a, int dn, int sn, int cas) {
+       int i;
+
+       if (!cas) {
+               if ((dn > 0) || (sn > 1)) {     /* NEW :  CASE ONE ELEMENT */
+                       for (i = 0; i < sn; i++)
+                               S(i) = fix_mul(S(i), 10078);    /* 10076 */
+                       for (i = 0; i < dn; i++)
+                               D(i) = fix_mul(D(i), 13318);    /* 13320 */
+                       for (i = 0; i < sn; i++)
+                               S(i) -= fix_mul(D_(i - 1) + D_(i), 3633);
+                       for (i = 0; i < dn; i++)
+                               D(i) -= fix_mul(S_(i) + S_(i + 1), 7233);
+                       for (i = 0; i < sn; i++)
+                               S(i) += fix_mul(D_(i - 1) + D_(i), 434);
+                       for (i = 0; i < dn; i++)
+                               D(i) += fix_mul(S_(i) + S_(i + 1), 12994);      /* 12993 */
+               }
+       } else {
+               if ((sn > 0) || (dn > 1)) {     /* NEW :  CASE ONE ELEMENT */
+                       for (i = 0; i < sn; i++)
+                               D(i) = fix_mul(D(i), 10078);    /* 10076 */
+                       for (i = 0; i < dn; i++)
+                               S(i) = fix_mul(S(i), 13318);    /* 13320 */
+                       for (i = 0; i < sn; i++)
+                               D(i) -= fix_mul(SS_(i) + SS_(i + 1), 3633);
+                       for (i = 0; i < dn; i++)
+                               S(i) -= fix_mul(DD_(i) + DD_(i - 1), 7233);
+                       for (i = 0; i < sn; i++)
+                               D(i) += fix_mul(SS_(i) + SS_(i + 1), 434);
+                       for (i = 0; i < dn; i++)
+                               S(i) += fix_mul(DD_(i) + DD_(i - 1), 12994);    /* 12993 */
+               }
+       }
+}
+
+
+/* <summary>                */
+/* Get norm of arbitrary wavelet transform. */
+/* </summary>               */
+static int upandconv(double *nXPS, double *LPS, int lenXPS, int lenLPS) {
+       /* Perform the convolution of the vectors. */
+       int i,j;
+       double *tmp = (double *)opj_malloc(2*lenXPS * sizeof(double));
+       //Upsample
+       memset(tmp, 0, 2*lenXPS*sizeof(double));
+       for (i = 0; i < lenXPS; i++) {
+               *(tmp + 2*i) = *(nXPS + i);
+               *(nXPS + i) = 0;
+       }
+       //Convolution
+       for (i = 0; i < 2*lenXPS; i++) {
+               for (j = 0; j < lenLPS; j++) {
+                       *(nXPS+i+j) = *(nXPS+i+j) + *(tmp + i) * *(LPS + j);
+                       //fprintf(stdout,"*(tmp + %d) * *(LPS + %d) = %f * %f \n",i,j,*(tmp + i),*(LPS + j));
+               }
+       }
+       free(tmp);
+       return 2*lenXPS+lenLPS-1;
+}
+
+static double dwt_calc_wtnorms(int orient, int level[3], int dwtid[3], opj_wtfilt_t *wtfiltX,  opj_wtfilt_t *wtfiltY,  opj_wtfilt_t *wtfiltZ) {
+       int i, lenLPS, lenHPS;
+       double  Lx = 0, Ly= 0, Hx= 0, Hy= 0, Lz= 0, Hz= 0;
+       double *nLPSx, *nHPSx,*nLPSy, *nHPSy,*nLPSz, *nHPSz;
+       int levelx, levely, levelz;
+           
+       levelx = (orient == 0) ? level[0]-1 : level[0];
+       levely = (orient == 0) ? level[1]-1 : level[1];
+       levelz = (orient == 0) ? level[2]-1 : level[2];
+       
+       //X axis
+       lenLPS = wtfiltX->lenLPS;
+       lenHPS = wtfiltX->lenHPS;
+       for (i = 0; i < levelx; i++) {
+               lenLPS *= 2;
+               lenHPS *= 2;
+               lenLPS += wtfiltX->lenLPS - 1;
+               lenHPS += wtfiltX->lenLPS - 1;
+       }
+       nLPSx = (double *)opj_malloc(lenLPS * sizeof(double));
+       nHPSx = (double *)opj_malloc(lenHPS * sizeof(double));
+
+       memcpy(nLPSx, wtfiltX->LPS, wtfiltX->lenLPS * sizeof(double));
+       memcpy(nHPSx, wtfiltX->HPS, wtfiltX->lenHPS * sizeof(double));
+       lenLPS = wtfiltX->lenLPS;
+       lenHPS = wtfiltX->lenHPS;
+       for (i = 0; i < levelx; i++) {
+               lenLPS = upandconv(nLPSx, wtfiltX->LPS, lenLPS, wtfiltX->lenLPS);
+               lenHPS = upandconv(nHPSx, wtfiltX->LPS, lenHPS, wtfiltX->lenLPS);
+       }
+       for (i = 0; i < lenLPS; i++)
+               Lx += nLPSx[i] * nLPSx[i];
+       for (i = 0; i < lenHPS; i++)
+               Hx += nHPSx[i] * nHPSx[i];
+       Lx = sqrt(Lx);
+       Hx = sqrt(Hx);
+       free(nLPSx);
+       free(nHPSx);
+       
+       //Y axis
+       if (dwtid[0] != dwtid[1] || level[0] != level[1]){
+               lenLPS = wtfiltY->lenLPS;
+               lenHPS = wtfiltY->lenHPS;
+               for (i = 0; i < levely; i++) {
+                       lenLPS *= 2;
+                       lenHPS *= 2;
+                       lenLPS += wtfiltY->lenLPS - 1;
+                       lenHPS += wtfiltY->lenLPS - 1;
+               }
+               nLPSy = (double *)opj_malloc(lenLPS * sizeof(double));
+               nHPSy = (double *)opj_malloc(lenHPS * sizeof(double));
+
+               memcpy(nLPSy, wtfiltY->LPS, wtfiltY->lenLPS * sizeof(double));
+               memcpy(nHPSy, wtfiltY->HPS, wtfiltY->lenHPS * sizeof(double));
+               lenLPS = wtfiltY->lenLPS;
+               lenHPS = wtfiltY->lenHPS;
+               for (i = 0; i < levely; i++) {
+                       lenLPS = upandconv(nLPSy, wtfiltY->LPS, lenLPS, wtfiltY->lenLPS);
+                       lenHPS = upandconv(nHPSy, wtfiltY->LPS, lenHPS, wtfiltY->lenLPS);
+               }
+               for (i = 0; i < lenLPS; i++)
+                       Ly += nLPSy[i] * nLPSy[i];
+               for (i = 0; i < lenHPS; i++)
+                       Hy += nHPSy[i] * nHPSy[i];
+               Ly = sqrt(Ly);
+               Hy = sqrt(Hy);
+               free(nLPSy);
+               free(nHPSy);
+       } else { 
+               Ly = Lx;
+               Hy = Hx;
+       }
+       //Z axis
+       if (levelz >= 0) { 
+               lenLPS = wtfiltZ->lenLPS;
+               lenHPS = wtfiltZ->lenHPS;
+               for (i = 0; i < levelz; i++) {
+                       lenLPS *= 2;
+                       lenHPS *= 2;
+                       lenLPS += wtfiltZ->lenLPS - 1;
+                       lenHPS += wtfiltZ->lenLPS - 1;
+               }
+               nLPSz = (double *)opj_malloc(lenLPS * sizeof(double));
+               nHPSz = (double *)opj_malloc(lenHPS * sizeof(double));
+
+               memcpy(nLPSz, wtfiltZ->LPS, wtfiltZ->lenLPS * sizeof(double));
+               memcpy(nHPSz, wtfiltZ->HPS, wtfiltZ->lenHPS * sizeof(double));
+               lenLPS = wtfiltZ->lenLPS;
+               lenHPS = wtfiltZ->lenHPS;
+               for (i = 0; i < levelz; i++) {
+                       lenLPS = upandconv(nLPSz, wtfiltZ->LPS, lenLPS, wtfiltZ->lenLPS);
+                       lenHPS = upandconv(nHPSz, wtfiltZ->LPS, lenHPS, wtfiltZ->lenLPS);
+               }
+               for (i = 0; i < lenLPS; i++)
+                       Lz += nLPSz[i] * nLPSz[i];
+               for (i = 0; i < lenHPS; i++)
+                       Hz += nHPSz[i] * nHPSz[i];
+               Lz = sqrt(Lz);
+               Hz = sqrt(Hz);
+               free(nLPSz);
+               free(nHPSz);
+       } else {
+               Lz = 1.0; Hz = 1.0;
+       }
+       switch (orient) {
+               case 0: 
+                       return Lx * Ly * Lz;
+               case 1:
+                       return Lx * Hy * Lz;
+               case 2:
+                       return Hx * Ly * Lz;
+               case 3:
+                       return Hx * Hy * Lz;
+               case 4:
+                       return Lx * Ly * Hz;
+               case 5:
+                       return Lx * Hy * Hz;
+               case 6: 
+                       return Hx * Ly * Hz;
+               case 7:
+                       return Hx * Hy * Hz;
+               default:
+                       return -1;
+       }
+       
+}
+static void dwt_getwtfilters(opj_wtfilt_t *wtfilt, int dwtid) {
+       if (dwtid == 0) { //DWT 9-7 
+                       wtfilt->lenLPS = 7;             wtfilt->lenHPS = 9;
+                       wtfilt->LPS = (double *)opj_malloc(wtfilt->lenLPS * sizeof(double));
+                       wtfilt->HPS = (double *)opj_malloc(wtfilt->lenHPS * sizeof(double));
+                       wtfilt->LPS[0] = -0.091271763114;       wtfilt->HPS[0] = 0.026748757411;
+                       wtfilt->LPS[1] = -0.057543526228;       wtfilt->HPS[1] = 0.016864118443;
+                       wtfilt->LPS[2] = 0.591271763114;        wtfilt->HPS[2] = -0.078223266529;
+                       wtfilt->LPS[3] = 1.115087052457;        wtfilt->HPS[3] = -0.266864118443;
+                       wtfilt->LPS[4] = 0.591271763114;        wtfilt->HPS[4] = 0.602949018236;
+                       wtfilt->LPS[5] = -0.057543526228;       wtfilt->HPS[5] = -0.266864118443;
+                       wtfilt->LPS[6] = -0.091271763114;       wtfilt->HPS[6] = -0.078223266529;
+                                                                                               wtfilt->HPS[7] = 0.016864118443;
+                                                                                               wtfilt->HPS[8] = 0.026748757411;                        
+       } else if (dwtid == 1) { //DWT 5-3 
+                       wtfilt->lenLPS = 3;             wtfilt->lenHPS = 5;
+                       wtfilt->LPS = (double *)opj_malloc(wtfilt->lenLPS * sizeof(double));
+                       wtfilt->HPS = (double *)opj_malloc(wtfilt->lenHPS * sizeof(double));
+                       wtfilt->LPS[0] = 0.5;   wtfilt->HPS[0] = -0.125; 
+                       wtfilt->LPS[1] = 1;             wtfilt->HPS[1] = -0.25; 
+                       wtfilt->LPS[2] = 0.5;   wtfilt->HPS[2] = 0.75;
+                                                                       wtfilt->HPS[3] = -0.25; 
+                                                                       wtfilt->HPS[4] = -0.125;
+       } else {
+               fprintf(stdout,"[ERROR] Sorry, this wavelet hasn't been implemented so far ... Try another one :-)\n");
+               exit(1);
+       }
+}
+/* <summary>                            */
+/* Encoding of quantization stepsize for each subband. */
+/* </summary>                           */ 
+static void dwt_encode_stepsize(int stepsize, int numbps, opj_stepsize_t *bandno_stepsize) {
+       int p, n;
+       p = int_floorlog2(stepsize) - 13;
+       n = 11 - int_floorlog2(stepsize);
+       bandno_stepsize->mant = (n < 0 ? stepsize >> -n : stepsize << n) & 0x7ff;
+       bandno_stepsize->expn = numbps - p;
+       //if J3D_CCP_QNTSTY_NOQNT --> stepsize = 8192.0 --> p = 0, n = -2 --> mant = 0; expn = (prec+gain)
+       //else --> bandno_stepsize = (1<<(numbps - expn)) + (1<<(numbps - expn - 11)) * Ub
+}
+
+/* 
+==========================================================
+   DWT interface
+==========================================================
+*/
+/* <summary>                            */
+/* Forward 5-3 wavelet tranform in 3-D. */
+/* </summary>                           */
+void dwt_encode(opj_tcd_tilecomp_t * tilec, int dwtid[3]) {
+       int i, j, k;
+       int x, y, z;
+       int w, h, wh, d;
+       int level,levelx,levely,levelz,diff;
+       int *a = NULL;
+       int *aj = NULL;
+       int *bj = NULL;
+       int *cj = NULL;
+       
+       ops = 0;
+
+       memset(flagnorm,0,8000*sizeof(int));
+       w = tilec->x1-tilec->x0;
+       h = tilec->y1-tilec->y0;
+       d = tilec->z1-tilec->z0;
+       wh = w * h;
+       levelx = tilec->numresolution[0]-1;
+       levely = tilec->numresolution[1]-1;
+       levelz = tilec->numresolution[2]-1;
+       level = int_max(levelx,int_max(levely,levelz));
+       diff = tilec->numresolution[0] - tilec->numresolution[2];
+
+       a = tilec->data;
+
+       for (x = 0, y = 0, z = 0; (x < levelx) && (y < levely); x++, y++, z++) {
+               int rw;                 /* width of the resolution level computed                                                           */
+               int rh;                 /* heigth of the resolution level computed                                                          */
+               int rd;                 /* depth of the resolution level computed                                                          */
+               int rw1;                /* width of the resolution level once lower than computed one                                       */
+               int rh1;                /* height of the resolution level once lower than computed one                                      */
+               int rd1;                /* depth of the resolution level once lower than computed one                                      */
+               int cas_col;    /* 0 = non inversion on horizontal filtering 1 = inversion between low-pass and high-pass filtering */
+               int cas_row;    /* 0 = non inversion on vertical filtering 1 = inversion between low-pass and high-pass filtering   */
+               int cas_axl;    /* 0 = non inversion on axial filtering 1 = inversion between low-pass and high-pass filtering   */
+               int dn, sn;
+               
+               rw = tilec->resolutions[level - x].x1 - tilec->resolutions[level - x].x0;
+               rh = tilec->resolutions[level - y].y1 - tilec->resolutions[level - y].y0;
+               rd = tilec->resolutions[level - z].z1 - tilec->resolutions[level - z].z0;
+               rw1= tilec->resolutions[level - x - 1].x1 - tilec->resolutions[level - x - 1].x0;
+               rh1= tilec->resolutions[level - y - 1].y1 - tilec->resolutions[level - y - 1].y0;
+               rd1= tilec->resolutions[level - z - 1].z1 - tilec->resolutions[level - z - 1].z0;
+               
+               cas_col = tilec->resolutions[level - x].x0 % 2; /* 0 = non inversion on horizontal filtering 1 = inversion between low-pass and high-pass filtering */
+               cas_row = tilec->resolutions[level - y].y0 % 2; /* 0 = non inversion on vertical filtering 1 = inversion between low-pass and high-pass filtering   */
+               cas_axl = tilec->resolutions[level - z].z0 % 2;
+       
+               /*fprintf(stdout," x %d y %d z %d \n",x,y,z);
+               fprintf(stdout," levelx %d levely %d levelz %d \n",levelx,levely,levelz);
+               fprintf(stdout," z1 %d z0 %d\n",tilec->resolutions[level - z].z1,tilec->resolutions[level - z].z0);
+               fprintf(stdout," rw %d rh %d rd %d \n rw1 %d rh1 %d rd1 %d \n",rw,rh,rd,rw1,rh1,rd1);*/
+
+               for (i = 0; i < rd; i++) {
+                       
+                       cj = a + (i * wh);
+                       
+                       //Horizontal
+                       sn = rw1;
+                       dn = rw - rw1;
+                       bj = (int*)opj_malloc(rw * sizeof(int));
+                       if (dwtid[0] == 0) {
+                               for (j = 0; j < rh; j++) {
+                                       aj = cj + j * w;
+                                       for (k = 0; k < rw; k++)  bj[k] = aj[k];
+                                       dwt_encode_97(bj, dn, sn, cas_row);
+                                       dwt_deinterleave_h(bj, aj, dn, sn, cas_row);
+                               }
+                       } else if (dwtid[0] == 1) {
+                               for (j = 0; j < rh; j++) {
+                                       aj = cj + j * w;
+                                       for (k = 0; k < rw; k++)  bj[k] = aj[k];
+                                       dwt_encode_53(bj, dn, sn, cas_row);
+                                       dwt_deinterleave_h(bj, aj, dn, sn, cas_row);
+                               }
+                       } 
+                       opj_free(bj);
+
+                       //Vertical
+                       sn = rh1;
+                       dn = rh - rh1;
+                       bj = (int*)opj_malloc(rh * sizeof(int));
+                       if (dwtid[1] == 0) { /*DWT 9-7*/
+                               for (j = 0; j < rw; j++) {
+                                       aj = cj + j;
+                                       for (k = 0; k < rh; k++)  bj[k] = aj[k*w];
+                                       dwt_encode_97(bj, dn, sn, cas_col);
+                                       dwt_deinterleave_v(bj, aj, dn, sn, w, cas_col);
+                               }
+            } else if (dwtid[1] == 1) { /*DWT 5-3*/
+                               for (j = 0; j < rw; j++) {
+                                       aj = cj + j;
+                                       for (k = 0; k < rh; k++)  bj[k] = aj[k*w];
+                                       dwt_encode_53(bj, dn, sn, cas_col);
+                                       dwt_deinterleave_v(bj, aj, dn, sn, w, cas_col);
+                               }
+                       } 
+                       opj_free(bj);
+               }
+
+               if (z < levelz){
+                       //Axial fprintf(stdout,"Axial DWT Transform %d %d %d\n",z,rd,rd1);
+                       sn = rd1;
+                       dn = rd - rd1;
+                       bj = (int*)opj_malloc(rd * sizeof(int));
+                       if (dwtid[2] == 0) {
+                for (j = 0; j < (rw*rh); j++) {
+                                       aj = a + j;
+                                       for (k = 0; k < rd; k++)  bj[k] = aj[k*wh];
+                                       dwt_encode_97(bj, dn, sn, cas_axl);
+                                       dwt_deinterleave_z(bj, aj, dn, sn, wh, cas_axl);
+                               }
+                       } else if (dwtid[2] == 1) {
+                               for (j = 0; j < (rw*rh); j++) {
+                                       aj = a + j;
+                                       for (k = 0; k < rd; k++)  bj[k] = aj[k*wh];
+                                       dwt_encode_53(bj, dn, sn, cas_axl);
+                                       dwt_deinterleave_z(bj, aj, dn, sn, wh, cas_axl);
+                               }
+                       } 
+                       opj_free(bj);
+               }
+       }
+
+       //fprintf(stdout,"[INFO] Ops: %d \n",ops);
+}
+
+
+/* <summary>                            */
+/* Inverse 5-3 wavelet tranform in 3-D. */
+/* </summary>                           */
+void dwt_decode(opj_tcd_tilecomp_t * tilec, int stops[3], int dwtid[3]) {
+       int i, j, k;
+       int x, y, z;
+       int w, h, wh, d;
+       int level, levelx, levely, levelz, diff;
+       int *a = NULL;
+       int *aj = NULL;
+       int *bj = NULL;
+       int *cj = NULL;
+       
+       a = tilec->data;
+
+       w = tilec->x1-tilec->x0;
+       h = tilec->y1-tilec->y0;
+       d = tilec->z1-tilec->z0;
+       wh = w * h;
+       levelx = tilec->numresolution[0]-1;
+       levely = tilec->numresolution[1]-1;
+       levelz = tilec->numresolution[2]-1;
+       level = int_max(levelx,int_max(levely,levelz));
+       diff = tilec->numresolution[0] - tilec->numresolution[2];
+               
+/* General lifting framework -- DCCS-LIWT */
+       for (x = level - 1, y = level - 1, z = level - 1; (x >= stops[0]) && (y >= stops[1]); x--, y--, z--) {
+               int rw;                 /* width of the resolution level computed                                                           */
+               int rh;                 /* heigth of the resolution level computed                                                          */
+               int rd;                 /* depth of the resolution level computed                                                          */
+               int rw1;                /* width of the resolution level once lower than computed one                                       */
+               int rh1;                /* height of the resolution level once lower than computed one                                      */
+               int rd1;                /* depth of the resolution level once lower than computed one                                      */
+               int cas_col;    /* 0 = non inversion on horizontal filtering 1 = inversion between low-pass and high-pass filtering */
+               int cas_row;    /* 0 = non inversion on vertical filtering 1 = inversion between low-pass and high-pass filtering   */
+               int cas_axl;    /* 0 = non inversion on axial filtering 1 = inversion between low-pass and high-pass filtering   */
+               int dn, sn;
+               
+               rw = tilec->resolutions[level - x].x1 - tilec->resolutions[level - x].x0;
+               rh = tilec->resolutions[level - y].y1 - tilec->resolutions[level - y].y0;
+               rd = tilec->resolutions[level - z].z1 - tilec->resolutions[level - z].z0;
+               rw1= tilec->resolutions[level - x - 1].x1 - tilec->resolutions[level - x - 1].x0;
+               rh1= tilec->resolutions[level - y - 1].y1 - tilec->resolutions[level - y - 1].y0;
+               rd1= tilec->resolutions[level - z - 1].z1 - tilec->resolutions[level - z - 1].z0;
+               
+               cas_col = tilec->resolutions[level - x].x0 % 2; /* 0 = non inversion on horizontal filtering 1 = inversion between low-pass and high-pass filtering */
+               cas_row = tilec->resolutions[level - y].y0 % 2; /* 0 = non inversion on vertical filtering 1 = inversion between low-pass and high-pass filtering   */
+               cas_axl = tilec->resolutions[level - z].z0 % 2;
+       
+               /*fprintf(stdout," x %d y %d z %d \n",x,y,z);
+               fprintf(stdout," levelx %d levely %d levelz %d \n",levelx,levely,levelz);
+               fprintf(stdout," dwtid[0] %d [1] %d [2] %d \n",dwtid[0],dwtid[1],dwtid[2]);
+               fprintf(stdout," rw %d rh %d rd %d \n rw1 %d rh1 %d rd1 %d \n",rw,rh,rd,rw1,rh1,rd1);
+               fprintf(stdout,"IDWT Transform %d %d %d %d\n",level, z, rd,rd1);*/
+
+               if (z >= stops[2] && rd != rd1) {
+                       //fprintf(stdout,"Axial Transform %d %d %d %d\n",levelz, z, rd,rd1);
+                       sn = rd1;
+                       dn = rd - rd1;
+                       bj = (int*)opj_malloc(rd * sizeof(int));
+                       if (dwtid[2] == 0) {
+                               for (j = 0; j < (rw*rh); j++) {
+                                       aj = a + j;
+                                       dwt_interleave_z(aj, bj, dn, sn, wh, cas_axl);
+                                       dwt_decode_97(bj, dn, sn, cas_axl);
+                                       for (k = 0; k < rd; k++)  aj[k * wh] = bj[k];
+                               }
+                       } else if (dwtid[2] == 1) {
+                               for (j = 0; j < (rw*rh); j++) {
+                                       aj = a + j;
+                                       dwt_interleave_z(aj, bj, dn, sn, wh, cas_axl);
+                                       dwt_decode_53(bj, dn, sn, cas_axl);
+                                       for (k = 0; k < rd; k++)  aj[k * wh] = bj[k];
+                               }
+                       } 
+                       opj_free(bj);
+               }
+
+               for (i = 0; i < rd; i++) {
+                       //Fetch corresponding slice for doing DWT-2D
+                       cj = tilec->data + (i * wh);
+                       
+                       //Vertical
+                       sn = rh1;
+                       dn = rh - rh1;
+                       bj = (int*)opj_malloc(rh * sizeof(int));
+                       if (dwtid[1] == 0) {
+                               for (j = 0; j < rw; j++) {
+                                       aj = cj + j;
+                                       dwt_interleave_v(aj, bj, dn, sn, w, cas_col);
+                                       dwt_decode_97(bj, dn, sn, cas_col);
+                                       for (k = 0; k < rh; k++)  aj[k * w] = bj[k];
+                               }
+                       } else if (dwtid[1] == 1) {
+                               for (j = 0; j < rw; j++) {
+                                       aj = cj + j;
+                                       dwt_interleave_v(aj, bj, dn, sn, w, cas_col);
+                                       dwt_decode_53(bj, dn, sn, cas_col);
+                                       for (k = 0; k < rh; k++)  aj[k * w] = bj[k];
+                               }
+                       } 
+                       opj_free(bj);
+
+                       //Horizontal
+                       sn = rw1;
+                       dn = rw - rw1;
+                       bj = (int*)opj_malloc(rw * sizeof(int));
+                       if (dwtid[0]==0) {
+                               for (j = 0; j < rh; j++) {
+                                       aj = cj + j*w;
+                                       dwt_interleave_h(aj, bj, dn, sn, cas_row);
+                                       dwt_decode_97(bj, dn, sn, cas_row);
+                                       for (k = 0; k < rw; k++)  aj[k] = bj[k];
+                               }
+                       } else if (dwtid[0]==1) {
+                               for (j = 0; j < rh; j++) {
+                                       aj = cj + j*w;
+                                       dwt_interleave_h(aj, bj, dn, sn, cas_row);
+                                       dwt_decode_53(bj, dn, sn, cas_row);
+                                       for (k = 0; k < rw; k++)  aj[k] = bj[k];
+                               }
+                       } 
+                       opj_free(bj);
+                       
+               }
+       
+       }
+
+}
+
+
+/* <summary>                          */
+/* Get gain of wavelet transform. */
+/* </summary>                         */
+int dwt_getgain(int orient, int reversible) {
+       if (reversible == 1) { 
+               if (orient == 0)
+                       return 0;
+               else if (orient == 1 || orient == 2 || orient == 4 )
+                       return 1;
+               else if (orient == 3 || orient == 5 || orient == 6 )
+                       return 2;
+               else 
+                       return 3;
+       }
+       //else if (reversible == 0){
+       return 0;
+}
+
+/* <summary>                */
+/* Get norm of wavelet transform. */
+/* </summary>               */
+double dwt_getnorm(int orient, int level[3], int dwtid[3]) {
+       int levelx = level[0];
+       int levely = level[1];
+       int levelz = (level[2] < 0) ? 0 : level[2];
+       double norm;
+
+       if (flagnorm[levelx][levely][levelz][orient] == 1) {
+               norm = dwt_norm[levelx][levely][levelz][orient];
+               //fprintf(stdout,"[INFO] Level: %d %d %d Orient %d Dwt_norm: %f \n",level[0],level[1],level[2],orient,norm);
+       } else {
+               opj_wtfilt_t *wtfiltx =(opj_wtfilt_t *) opj_malloc(sizeof(opj_wtfilt_t));
+               opj_wtfilt_t *wtfilty =(opj_wtfilt_t *) opj_malloc(sizeof(opj_wtfilt_t));
+               opj_wtfilt_t *wtfiltz =(opj_wtfilt_t *) opj_malloc(sizeof(opj_wtfilt_t));
+               //Fetch equivalent filters for each dimension
+               dwt_getwtfilters(wtfiltx, dwtid[0]);
+               dwt_getwtfilters(wtfilty, dwtid[1]);
+               dwt_getwtfilters(wtfiltz, dwtid[2]);
+               //Calculate the corresponding norm 
+               norm = dwt_calc_wtnorms(orient, level, dwtid, wtfiltx, wtfilty, wtfiltz);
+               //Save norm in array (no recalculation)
+               dwt_norm[levelx][levely][levelz][orient] = norm;
+               flagnorm[levelx][levely][levelz][orient] = 1;
+               //Free reserved space
+               opj_free(wtfiltx->LPS); opj_free(wtfilty->LPS); opj_free(wtfiltz->LPS);
+               opj_free(wtfiltx->HPS); opj_free(wtfilty->HPS); opj_free(wtfiltz->HPS);
+               opj_free(wtfiltx);              opj_free(wtfilty);              opj_free(wtfiltz);
+               //fprintf(stdout,"[INFO] Dwtid: %d %d %d Level: %d %d %d Orient %d Norm: %f \n",dwtid[0],dwtid[1],dwtid[2],level[0],level[1],level[2],orient,norm);
+       } 
+       return norm;
+}
+/* <summary>                                                           */
+/* Calculate explicit stepsizes for DWT.       */
+/* </summary>                                                          */
+void dwt_calc_explicit_stepsizes(opj_tccp_t * tccp, int prec) { 
+       int totnumbands, bandno, diff;
+       
+       assert(tccp->numresolution[0] >= tccp->numresolution[2]);       
+       diff = tccp->numresolution[0] - tccp->numresolution[2];         /*if RESx=RESy != RESz */
+       totnumbands = (7 * tccp->numresolution[0] - 6) - 4 * diff; /* 3-D */
+               
+       for (bandno = 0; bandno < totnumbands; bandno++) {
+               double stepsize;
+               int resno, level[3], orient, gain;
+
+               /* Bandno:      0 - LLL         1 - LHL 
+                                       2 - HLL         3 - HHL
+                                       4 - LLH         5 - LHH
+                                       6 - HLH         7 - HHH */
+
+               resno = (bandno == 0) ? 0 : ( (bandno <= 3 * diff) ? ((bandno - 1) / 3 + 1) : ((bandno + 4*diff - 1) / 7 + 1));
+               orient = (bandno == 0) ? 0 : ( (bandno <= 3 * diff) ? ((bandno - 1) % 3 + 1) : ((bandno + 4*diff - 1) % 7 + 1));
+               level[0] = tccp->numresolution[0] - 1 - resno;
+               level[1] = tccp->numresolution[1] - 1 - resno;
+               level[2] = tccp->numresolution[2] - 1 - resno;
+       
+               /* Gain:        0 - LLL         1 - LHL 
+                                       1 - HLL         2 - HHL
+                                       1 - LLH         2 - LHH
+                                       2 - HLH         3 - HHH         */
+               gain = (tccp->reversible == 0) ? 0 : ( (orient == 0) ? 0 : 
+                               ( ((orient == 1) || (orient == 2) || (orient == 4)) ? 1 : 
+                                               (((orient == 3) || (orient == 5) || (orient == 6)) ? 2 : 3)) );
+                               
+               if (tccp->qntsty == J3D_CCP_QNTSTY_NOQNT) {
+                       stepsize = 1.0;
+               } else {
+                       double norm = dwt_getnorm(orient,level,tccp->dwtid); //Fetch norms if irreversible transform (by the moment only I9.7)
+                       stepsize = (1 << (gain + 1)) / norm;
+               }
+               //fprintf(stdout,"[INFO] Bandno: %d Orient: %d Level: %d %d %d Stepsize: %f\n",bandno,orient,level[0],level[1],level[2],stepsize);
+               dwt_encode_stepsize((int) floor(stepsize * 8192.0), prec + gain, &tccp->stepsizes[bandno]);
+       }
+}
+
+
+
diff --git a/src/lib/openjp3d/dwt.h b/src/lib/openjp3d/dwt.h
new file mode 100755 (executable)
index 0000000..d87f799
--- /dev/null
@@ -0,0 +1,100 @@
+/*\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
+ * Copyrigth (c) 2006, Mónica Díez, LPI-UVA, Spain\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 __DWT_H\r
+#define __DWT_H\r
+/**\r
+@file dwt.h\r
+@brief Implementation of a discrete wavelet transform (DWT)\r
+\r
+The functions in DWT.C have for goal to realize forward and inverse discret wavelet\r
+transform with filter 5-3 (reversible) and filter 9-7 (irreversible). The functions in\r
+DWT.C are used by some function in TCD.C.\r
+*/\r
+\r
+/** @defgroup DWT DWT - Implementation of a discrete wavelet transform */\r
+/*@{*/\r
+\r
+/**\r
+DCCS-LIWT properties\r
+*/\r
+\r
+\r
+typedef struct opj_wtfilt {\r
+       double *LPS;\r
+       int lenLPS;\r
+       double *HPS;\r
+       int lenHPS;\r
+} opj_wtfilt_t;\r
+/** @name Funciones generales */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Forward 5-3 wavelet tranform in 3-D. \r
+Apply a reversible DWT transform to a component of an volume.\r
+@param tilec Tile component information (current tile)\r
+@param dwtid Number of identification of wavelet kernel(s) used in DWT in each direction\r
+*/\r
+void dwt_encode(opj_tcd_tilecomp_t * tilec, int dwtid[3]);\r
+/**\r
+Inverse 5-3 wavelet tranform in 3-D.\r
+Apply a reversible inverse DWT transform to a component of an volume.\r
+@param tilec Tile component information (current tile)\r
+@param stops Number of decoded resolution levels in each dimension\r
+@param dwtid Number of identification of wavelet kernel(s) used in DWT in each dimension\r
+*/\r
+void dwt_decode(opj_tcd_tilecomp_t * tilec, int stops[3], int dwtid[3]);\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Get the gain of a subband for the reversible 3-D DWT.\r
+@param orient Number that identifies the subband (0->LLL, 1->HLL, 2->LHL, 3->HHL, 4->LLH, 5->HLH, 6->LHH, 7->HHH)\r
+@param reversible Wavelet transformation type\r
+@return Returns 0 if orient = 0, returns 1 if orient = 1,2 or 4, returns 2 if orient = 3,5 or 6, returns 3 otherwise\r
+*/\r
+int dwt_getgain(int orient, int reversible);\r
+/**\r
+Get the norm of a wavelet function of a subband at a specified level for the reversible 5-3 DWT or irreversible 9-7 in 3-D.\r
+@param orient Band of the wavelet function\r
+@param level Levels of the wavelet function in X,Y,Z axis\r
+@param dwtid Wavelet transformation identifier\r
+@return Returns the norm of the wavelet function\r
+*/\r
+double dwt_getnorm(int orient, int level[3], int dwtid[3]);\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Calcula el valor del escalón de cuantificación correspondiente a cada subbanda.\r
+@param tccp Tile component coding parameters\r
+@param prec Precision of data\r
+*/\r
+void dwt_calc_explicit_stepsizes(opj_tccp_t * tccp, int prec);\r
+/*@}*/\r
+\r
+#endif /* __DWT_H */\r
diff --git a/src/lib/openjp3d/event.c b/src/lib/openjp3d/event.c
new file mode 100755 (executable)
index 0000000..e27df65
--- /dev/null
@@ -0,0 +1,181 @@
+/*\r
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team\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 "opj_includes.h"\r
+\r
+// ==========================================================\r
+//   Utility functions\r
+// ==========================================================\r
+\r
+#ifndef _WIN32\r
+static char*\r
+i2a(unsigned i, char *a, unsigned r) {\r
+       if (i/r > 0) a = i2a(i/r,a,r);\r
+       *a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i%r];\r
+       return a+1;\r
+}\r
+\r
+/** \r
+ Transforms integer i into an ascii string and stores the result in a; \r
+ string is encoded in the base indicated by r.\r
+ @param i Number to be converted\r
+ @param a String result\r
+ @param r Base of value; must be in the range 2 - 36\r
+ @return Returns a\r
+*/\r
+static char *\r
+_itoa(int i, char *a, int r) {\r
+       r = ((r < 2) || (r > 36)) ? 10 : r;\r
+       if(i < 0) {\r
+               *a = '-';\r
+               *i2a(-i, a+1, r) = 0;\r
+       }\r
+       else *i2a(i, a, r) = 0;\r
+       return a;\r
+}\r
+\r
+#endif // !_WIN32\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+opj_event_mgr_t* OPJ_CALLCONV opj_set_event_mgr(opj_common_ptr cinfo, opj_event_mgr_t *event_mgr, void *context) {\r
+       if(cinfo) {\r
+               opj_event_mgr_t *previous = cinfo->event_mgr;\r
+               cinfo->event_mgr = event_mgr;\r
+               cinfo->client_data = context;\r
+               return previous;\r
+       }\r
+\r
+       return NULL;\r
+}\r
+\r
+bool opj_event_msg(opj_common_ptr cinfo, int event_type, const char *fmt, ...) {\r
+#define MSG_SIZE 512 /* 512 bytes should be more than enough for a short message */\r
+       opj_msg_callback msg_handler = NULL;\r
+\r
+       opj_event_mgr_t *event_mgr = cinfo->event_mgr;\r
+       if(event_mgr != NULL) {\r
+               switch(event_type) {\r
+                       case EVT_ERROR:\r
+                               msg_handler = event_mgr->error_handler;\r
+                               break;\r
+                       case EVT_WARNING:\r
+                               msg_handler = event_mgr->warning_handler;\r
+                               break;\r
+                       case EVT_INFO:\r
+                               msg_handler = event_mgr->info_handler;\r
+                               break;\r
+                       default:\r
+                               break;\r
+               }\r
+               if(msg_handler == NULL) {\r
+                       return false;\r
+               }\r
+       } else {\r
+               return false;\r
+       }\r
+\r
+       if ((fmt != NULL) && (event_mgr != NULL)) {\r
+               va_list arg;\r
+               int str_length, i, j;\r
+               char message[MSG_SIZE];\r
+               memset(message, 0, MSG_SIZE);\r
+               /* initialize the optional parameter list */\r
+               va_start(arg, fmt);\r
+               /* check the length of the format string */\r
+               str_length = (strlen(fmt) > MSG_SIZE) ? MSG_SIZE : strlen(fmt);\r
+               /* parse the format string and put the result in 'message' */\r
+               for (i = 0, j = 0; i < str_length; ++i) {\r
+                       if (fmt[i] == '%') {\r
+                               if (i + 1 < str_length) {\r
+                                       switch(tolower(fmt[i + 1])) {\r
+                                               case '%' :\r
+                                                       message[j++] = '%';\r
+                                                       break;\r
+                                               case 'o' : /* octal numbers */\r
+                                               {\r
+                                                       char tmp[16];\r
+                                                       _itoa(va_arg(arg, int), tmp, 8);\r
+                                                       strcat(message, tmp);\r
+                                                       j += strlen(tmp);\r
+                                                       ++i;\r
+                                                       break;\r
+                                               }\r
+                                               case 'i' : /* decimal numbers */\r
+                                               case 'd' :\r
+                                               {\r
+                                                       char tmp[16];\r
+                                                       _itoa(va_arg(arg, int), tmp, 10);\r
+                                                       strcat(message, tmp);\r
+                                                       j += strlen(tmp);\r
+                                                       ++i;\r
+                                                       break;\r
+                                               }\r
+                                               case 'x' : /* hexadecimal numbers */\r
+                                               {\r
+                                                       char tmp[16];\r
+                                                       _itoa(va_arg(arg, int), tmp, 16);\r
+                                                       strcat(message, tmp);\r
+                                                       j += strlen(tmp);\r
+                                                       ++i;\r
+                                                       break;\r
+                                               }\r
+                                               case 's' : /* strings */\r
+                                               {\r
+                                                       char *tmp = va_arg(arg, char*);\r
+                                                       strcat(message, tmp);\r
+                                                       j += strlen(tmp);\r
+                                                       ++i;\r
+                                                       break;\r
+                                               }\r
+                                               case 'f' :      /* floats */\r
+                                               {\r
+                                                       char tmp[16];\r
+                                                       double value = va_arg(arg, double);\r
+                                                       sprintf(tmp, "%f", value);\r
+                                                       strcat(message, tmp);\r
+                                                       j += strlen(tmp);\r
+                                                       ++i;\r
+                                                       break;\r
+                                               }\r
+                                       };\r
+                               } else {\r
+                                       message[j++] = fmt[i];\r
+                               }\r
+                       } else {\r
+                               message[j++] = fmt[i];\r
+                       };\r
+               }\r
+               /* deinitialize the optional parameter list */\r
+               va_end(arg);\r
+\r
+               /* output the message to the user program */\r
+               msg_handler(message, cinfo->client_data);\r
+       }\r
+\r
+       return true;\r
+}\r
+\r
diff --git a/src/lib/openjp3d/event.h b/src/lib/openjp3d/event.h
new file mode 100755 (executable)
index 0000000..8f45452
--- /dev/null
@@ -0,0 +1,58 @@
+/*\r
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team\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
+#ifndef __EVENT_H\r
+#define __EVENT_H\r
+/**\r
+@file event.h\r
+@brief Implementation of a event callback system\r
+\r
+The functions in EVENT.C have for goal to send output messages (errors, warnings, debug) to the user.\r
+*/\r
+\r
+#define EVT_ERROR      1       /**< Error event type */\r
+#define EVT_WARNING    2       /**< Warning event type */\r
+#define EVT_INFO       4       /**< Debug event type */\r
+\r
+/** @defgroup EVENT EVENT - Implementation of a event callback system */\r
+/*@{*/\r
+\r
+/** @name Funciones generales (see also openjp3d.h) */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Write formatted data to a string and send the string to a user callback. \r
+@param cinfo Codec context info\r
+@param event_type Event type or callback to use to send the message\r
+@param fmt Format-control string (plus optionnal arguments)\r
+@return Returns true if successful, returns false otherwise\r
+*/\r
+bool opj_event_msg(opj_common_ptr cinfo, int event_type, const char *fmt, ...);\r
+/* ----------------------------------------------------------------------- */\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* __EVENT_H */\r
diff --git a/src/lib/openjp3d/fix.h b/src/lib/openjp3d/fix.h
new file mode 100755 (executable)
index 0000000..3b5e77c
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * 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
+ * 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
+
+#if defined(_MSC_VER) || defined(__BORLANDC__)
+#define int64 __int64
+#else
+#define int64 long long
+#endif
+
+/**
+@file fix.h
+@brief Implementation of operations of specific multiplication (FIX)
+
+The functions in FIX.H have for goal to realize specific multiplication.
+*/
+
+/** @defgroup FIX FIX - Implementation of operations of specific multiplication */
+/*@{*/
+
+/**
+Multiply two fixed-precision rational numbers.
+@param a
+@param b
+@return Returns a * b
+*/
+static  int fix_mul(int a, int b) {
+    int64 temp = (int64) a * (int64) b >> 12;
+    return (int) ((temp >> 1) + (temp & 1)) ;
+}
+
+/*@}*/
+
+#endif /* __FIX_H */
diff --git a/src/lib/openjp3d/int.h b/src/lib/openjp3d/int.h
new file mode 100755 (executable)
index 0000000..39b579a
--- /dev/null
@@ -0,0 +1,122 @@
+/*
+ * 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
+ * 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
+/**
+@file int.h
+@brief Implementation of operations on integers (INT)
+
+The functions in INT.H have for goal to realize operations on integers.
+*/
+
+/** @defgroup INT INT - Implementation of operations on integers */
+/*@{*/
+
+/** @name Funciones generales (see also openjp3d.h) */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+/**
+Get the minimum of two integers
+@return Returns a if a < b else b
+*/
+static  int int_min(int a, int b) {
+       return a < b ? a : b;
+}
+/**
+Get the maximum of two integers
+@return Returns a if a > b else b
+*/
+static  int int_max(int a, int b) {
+       return (a > b) ? a : b;
+}
+/**
+Clamp an integer inside an interval
+@return
+<ul>
+<li>Returns a if (min < a < max)
+<li>Returns max if (a > max)
+<li>Returns min if (a < min) 
+</ul>
+*/
+static int int_clamp(int a, int min, int max) {
+       if (a < min)
+               return min;
+       if (a > max)
+               return max;
+       return a;
+}
+/**
+@return Get absolute value of integer
+*/
+static  int int_abs(int a) {
+       return a < 0 ? -a : a;
+}
+
+static double dbl_abs(double a) {
+       return a < 0 ? -a : a;
+}
+/**
+Divide an integer and round upwards
+@return Returns a divided by b
+*/
+static  int int_ceildiv(int a, int b) {
+       return (a + b - 1) / b;
+}
+/**
+Divide an integer by a power of 2 and round upwards
+@return Returns a divided by 2^b
+*/
+static  int int_ceildivpow2(int a, int b) {
+       return (a + (1 << b) - 1) >> b;
+}
+/**
+Divide an integer by a power of 2 and round downwards
+@return Returns a divided by 2^b
+*/
+static  int int_floordivpow2(int a, int b) {
+       return a >> b;
+}
+/**
+Get logarithm of an integer and round downwards
+@return Returns log2(a)
+*/
+static  int int_floorlog2(int a) {
+       int l;
+       for (l = 0; a > 1; l++) {
+               a >>= 1;
+       }
+       return l;
+}
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif
diff --git a/src/lib/openjp3d/jp3d.c b/src/lib/openjp3d/jp3d.c
new file mode 100755 (executable)
index 0000000..2fd5d02
--- /dev/null
@@ -0,0 +1,2328 @@
+/*\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) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain\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 "opj_includes.h"\r
+\r
+/** @defgroup J3D J3D - JPEG-2000 PART 10 codestream reader/writer */\r
+/*@{*/\r
+\r
+/** @name Funciones locales */\r
+/*@{*/\r
+\r
+/**\r
+Write the SOC marker (Start Of Codestream)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_soc(opj_j3d_t *j3d);\r
+/**\r
+Read the SOC marker (Start of Codestream)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_soc(opj_j3d_t *j3d);\r
+/**\r
+Write the SIZ marker (2D volume and tile size)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_siz(opj_j3d_t *j3d);\r
+/**\r
+Read the SIZ marker (2D volume and tile size)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_siz(opj_j3d_t *j3d);\r
+/**\r
+Write the ZSI marker (3rd volume and tile size)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_zsi(opj_j3d_t *j3d);\r
+/**\r
+Read the ZSI marker (3rd volume and tile size)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_zsi(opj_j3d_t *j3d);\r
+/**\r
+Write the COM marker (comment)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_com(opj_j3d_t *j3d);\r
+/**\r
+Read the COM marker (comment)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_com(opj_j3d_t *j3d);\r
+/**\r
+Write the value concerning the specified component in the marker COD and COC\r
+@param j3d J3D handle\r
+@param compno Number of the component concerned by the information written\r
+*/\r
+static void j3d_write_cox(opj_j3d_t *j3d, int compno);\r
+/**\r
+Read the value concerning the specified component in the marker COD and COC\r
+@param j3d J3D handle\r
+@param compno Number of the component concerned by the information read\r
+*/\r
+static void j3d_read_cox(opj_j3d_t *j3d, int compno);\r
+/**\r
+Write the COD marker (coding style default)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_cod(opj_j3d_t *j3d);\r
+/**\r
+Read the COD marker (coding style default)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_cod(opj_j3d_t *j3d);\r
+/**\r
+Write the COC marker (coding style component)\r
+@param j3d J3D handle\r
+@param compno Number of the component concerned by the information written\r
+*/\r
+static void j3d_write_coc(opj_j3d_t *j3d, int compno);\r
+/**\r
+Read the COC marker (coding style component)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_coc(opj_j3d_t *j3d);\r
+/**\r
+Write the value concerning the specified component in the marker QCD and QCC\r
+@param j3d J3D handle\r
+@param compno Number of the component concerned by the information written\r
+*/\r
+static void j3d_write_qcx(opj_j3d_t *j3d, int compno);\r
+/**\r
+Read the value concerning the specified component in the marker QCD and QCC\r
+@param j3d J3D handle\r
+@param compno Number of the component concern by the information read\r
+@param len Length of the information in the QCX part of the marker QCD/QCC\r
+*/\r
+static void j3d_read_qcx(opj_j3d_t *j3d, int compno, int len);\r
+/**\r
+Write the QCD marker (quantization default)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_qcd(opj_j3d_t *j3d);\r
+/**\r
+Read the QCD marker (quantization default)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_qcd(opj_j3d_t *j3d);\r
+/**\r
+Write the QCC marker (quantization component)\r
+@param j3d J3D handle\r
+@param compno Number of the component concerned by the information written\r
+*/\r
+static void j3d_write_qcc(opj_j3d_t *j3d, int compno);\r
+/**\r
+Read the QCC marker (quantization component)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_qcc(opj_j3d_t *j3d);\r
+/**\r
+Write the POC marker (progression order change)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_poc(opj_j3d_t *j3d);\r
+/**\r
+Read the POC marker (progression order change)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_poc(opj_j3d_t *j3d);\r
+/**\r
+Read the CRG marker (component registration)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_crg(opj_j3d_t *j3d);\r
+/**\r
+Read the TLM marker (tile-part lengths)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_tlm(opj_j3d_t *j3d);\r
+/**\r
+Read the PLM marker (packet length, main header)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_plm(opj_j3d_t *j3d);\r
+/**\r
+Read the PLT marker (packet length, tile-part header)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_plt(opj_j3d_t *j3d);\r
+/**\r
+Read the PPM marker (packet packet headers, main header)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_ppm(opj_j3d_t *j3d);\r
+/**\r
+Read the PPT marker (packet packet headers, tile-part header)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_ppt(opj_j3d_t *j3d);\r
+/**\r
+Write the SOT marker (start of tile-part)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_sot(opj_j3d_t *j3d);\r
+/**\r
+Read the SOT marker (start of tile-part)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_sot(opj_j3d_t *j3d);\r
+/**\r
+Write the SOD marker (start of data)\r
+@param j3d J3D handle\r
+@param tile_coder Pointer to a TCD handle\r
+*/\r
+static void j3d_write_sod(opj_j3d_t *j3d, void *tile_coder);\r
+/**\r
+Read the SOD marker (start of data)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_sod(opj_j3d_t *j3d);\r
+/**\r
+Write the RGN marker (region-of-interest)\r
+@param j3d J3D handle\r
+@param compno Number of the component concerned by the information written\r
+@param tileno Number of the tile concerned by the information written\r
+*/\r
+static void j3d_write_rgn(opj_j3d_t *j3d, int compno, int tileno);\r
+/**\r
+Read the RGN marker (region-of-interest)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_rgn(opj_j3d_t *j3d);\r
+/**\r
+Write the EOC marker (end of codestream)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_eoc(opj_j3d_t *j3d);\r
+/**\r
+Read the EOC marker (end of codestream)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_eoc(opj_j3d_t *j3d);\r
+/**\r
+Read an unknown marker\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_unk(opj_j3d_t *j3d);\r
+/**\r
+Write the CAP marker (extended capabilities)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_cap(opj_j3d_t *j3d);\r
+/**\r
+Read the CAP marker (extended capabilities)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_cap(opj_j3d_t *j3d);\r
+/**\r
+Write the DCO marker (Variable DC offset)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_dco(opj_j3d_t *j3d);\r
+/**\r
+Read the DCO marker (Variable DC offset)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_dco(opj_j3d_t *j3d);\r
+/**\r
+Write the ATK marker (arbitrary transformation kernel)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_atk(opj_j3d_t *j3d);\r
+/**\r
+Read the ATK marker (arbitrary transformation kernel)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_atk(opj_j3d_t *j3d);\r
+/**\r
+Write the CBD marker (component bit depth definition)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_cbd(opj_j3d_t *j3d);\r
+/**\r
+Read the CBD marker (component bit depth definition)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_cbd(opj_j3d_t *j3d);\r
+/**\r
+Write the MCT marker (multiple component transfomation definition)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_mct(opj_j3d_t *j3d);\r
+/**\r
+Read the MCT marker (multiple component transfomation definition)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_mct(opj_j3d_t *j3d);\r
+/**\r
+Write the MCC marker (multiple component transfomation collection)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_mcc(opj_j3d_t *j3d);\r
+/**\r
+Read the MCC marker (multiple component transfomation collection)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_mcc(opj_j3d_t *j3d);\r
+/**\r
+Write the MCO marker (multiple component transfomation ordering)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_mco(opj_j3d_t *j3d);\r
+/**\r
+Read the MCO marker (multiple component transfomation ordering)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_mco(opj_j3d_t *j3d);\r
+/**\r
+Write the NLT marker (non-linearity point transformation)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_write_nlt(opj_j3d_t *j3d);\r
+/**\r
+Read the NLT marker (non-linearity point transformation)\r
+@param j3d J3D handle\r
+*/\r
+static void j3d_read_nlt(opj_j3d_t *j3d);\r
+/*@}*/\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+void j3d_dump_volume(FILE *fd, opj_volume_t * vol) {\r
+       int compno;\r
+       fprintf(fd, "volume {\n");\r
+       fprintf(fd, "  x0=%d, y0=%d, z0=%d, x1=%d, y1=%d, z1=%d\n", vol->x0, vol->y0, vol->z0,vol->x1, vol->y1,  vol->z1);\r
+       fprintf(fd, "  numcomps=%d\n", vol->numcomps);\r
+       for (compno = 0; compno < vol->numcomps; compno++) {\r
+               opj_volume_comp_t *comp = &vol->comps[compno];\r
+               fprintf(fd, "  comp %d {\n", compno);\r
+               fprintf(fd, "    dx=%d, dy=%d, dz=%d\n", comp->dx, comp->dy, comp->dz);\r
+               fprintf(fd, "    prec=%d\n", comp->prec);\r
+               fprintf(fd, "    sgnd=%d\n", comp->sgnd);\r
+               fprintf(fd, "  }\n");\r
+       }\r
+       fprintf(fd, "}\n");\r
+}\r
+\r
+void j3d_dump_cp(FILE *fd, opj_volume_t * vol, opj_cp_t * cp) {\r
+       int tileno, compno, layno, bandno, resno, numbands;\r
+       fprintf(fd, "coding parameters {\n");\r
+       fprintf(fd, "  tx0=%d, ty0=%d, tz0=%d\n", cp->tx0, cp->ty0, cp->tz0);\r
+       fprintf(fd, "  tdx=%d, tdy=%d, tdz=%d\n", cp->tdx, cp->tdy, cp->tdz);\r
+       fprintf(fd, "  tw=%d, th=%d, tl=%d\n", cp->tw, cp->th, cp->tl);\r
+       fprintf(fd, "  transform format: %d\n", cp->transform_format);\r
+       fprintf(fd, "  encoding format: %d\n", cp->encoding_format);\r
+       for (tileno = 0; tileno < cp->tw * cp->th * cp->tl; tileno++) {\r
+               opj_tcp_t *tcp = &cp->tcps[tileno];\r
+               fprintf(fd, "  tile %d {\n", tileno);\r
+               fprintf(fd, "    csty=%x\n", tcp->csty);\r
+               fprintf(fd, "    prg=%d\n", tcp->prg);\r
+               fprintf(fd, "    numlayers=%d\n", tcp->numlayers);\r
+               fprintf(fd, "    mct=%d\n", tcp->mct);\r
+               fprintf(fd, "    rates=");\r
+               for (layno = 0; layno < tcp->numlayers; layno++) {\r
+                       fprintf(fd, "%f ", tcp->rates[layno]);\r
+               }\r
+               fprintf(fd, "\n");\r
+               fprintf(fd, "    first=%d\n", tcp->first);\r
+               for (compno = 0; compno < vol->numcomps; compno++) {\r
+                       opj_tccp_t *tccp = &tcp->tccps[compno];\r
+                       fprintf(fd, "    comp %d {\n", compno);\r
+                       fprintf(fd, "      csty=%x\n", tccp->csty);\r
+                       fprintf(fd, "      numresx=%d, numresy=%d, numresz=%d\n", tccp->numresolution[0], tccp->numresolution[1], tccp->numresolution[2]);\r
+                       fprintf(fd, "      cblkw=%d, cblkh=%d, cblkl=%d\n", tccp->cblk[0], tccp->cblk[1], tccp->cblk[2]);\r
+                       fprintf(fd, "      cblksty=%x\n", tccp->cblksty);\r
+                       fprintf(fd, "      qntsty=%d\n", tccp->qntsty);\r
+                       fprintf(fd, "      numgbits=%d\n", tccp->numgbits);\r
+                       fprintf(fd, "      roishift=%d\n", tccp->roishift);\r
+                       fprintf(fd, "      reversible=%d\n", tccp->reversible);\r
+                       fprintf(fd, "      dwtidx=%d dwtidy=%d dwtidz=%d\n", tccp->dwtid[0], tccp->dwtid[1], tccp->dwtid[2]);\r
+                       if (tccp->atk != NULL) {\r
+                fprintf(fd, "      atk.index=%d\n", tccp->atk->index);\r
+                               fprintf(fd, "      atk.coeff_typ=%d\n", tccp->atk->coeff_typ);\r
+                               fprintf(fd, "      atk.filt_cat=%d\n", tccp->atk->filt_cat);\r
+                               fprintf(fd, "      atk.exten=%d\n", tccp->atk->exten);\r
+                               fprintf(fd, "      atk.minit=%d\n", tccp->atk->minit);\r
+                               fprintf(fd, "      atk.wt_typ=%d\n", tccp->atk->wt_typ);\r
+                       }\r
+                       fprintf(fd, "      stepsizes of bands=");\r
+            numbands = (tccp->qntsty == J3D_CCP_QNTSTY_SIQNT) ? 1 :\r
+                       ( (cp->transform_format == TRF_2D_DWT) ? (tccp->numresolution[0] * 3 - 2) :\r
+                               (tccp->numresolution[0] * 7 - 6) - 4 *(tccp->numresolution[0] - tccp->numresolution[2]) );\r
+                       for (bandno = 0; bandno < numbands; bandno++) {\r
+                               fprintf(fd, "(%d,%d) ", tccp->stepsizes[bandno].mant,tccp->stepsizes[bandno].expn);\r
+                       }\r
+                       fprintf(fd, "\n");\r
+                       \r
+                       if (tccp->csty & J3D_CCP_CSTY_PRT) {\r
+                               fprintf(fd, "      prcw=");\r
+                               for (resno = 0; resno < tccp->numresolution[0]; resno++) {\r
+                                       fprintf(fd, "%d ", tccp->prctsiz[0][resno]);\r
+                               }\r
+                               fprintf(fd, "\n");\r
+                               fprintf(fd, "      prch=");\r
+                               for (resno = 0; resno < tccp->numresolution[0]; resno++) {\r
+                                       fprintf(fd, "%d ", tccp->prctsiz[1][resno]);\r
+                               }\r
+                               fprintf(fd, "\n");\r
+                               fprintf(fd, "      prcl=");\r
+                               for (resno = 0; resno < tccp->numresolution[0]; resno++) {\r
+                                       fprintf(fd, "%d ", tccp->prctsiz[2][resno]);\r
+                               }\r
+                               fprintf(fd, "\n");\r
+                       }\r
+                       fprintf(fd, "    }\n");\r
+               }\r
+               fprintf(fd, "  }\n");\r
+       }\r
+       fprintf(fd, "}\n");\r
+}\r
+\r
+/* ----------------------------------------------------------------------- \r
+Extended capabilities\r
+------------------------------------------------------------------------*/\r
+\r
+static void j3d_write_cap(opj_j3d_t *j3d){\r
+       int len,lenp;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+       cio_write(cio, J3D_MS_CAP, 2);  /* CAP */\r
+       lenp = cio_tell(cio);\r
+       cio_skip(cio, 2);\r
+       cio_write(cio,J3D_CAP_10, 4); \r
+       len = cio_tell(cio) - lenp;\r
+       cio_seek(cio, lenp);\r
+       cio_write(cio, len, 2);         /* Lsiz */\r
+       cio_seek(cio, lenp + len);\r
+\r
+}\r
+static void j3d_read_cap(opj_j3d_t *j3d){\r
+       int len, Cap;\r
+       opj_cio_t *cio = j3d->cio;\r
+       /*cio_read(cio, 2);      CAP */\r
+       len = cio_read(cio, 2);\r
+       Cap = cio_read(cio, 4);\r
+}\r
+static void j3d_write_zsi(opj_j3d_t *j3d) {\r
+       int i;\r
+       int lenp, len;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+       opj_volume_t *volume = j3d->volume;\r
+       opj_cp_t *cp = j3d->cp;\r
+       \r
+       cio_write(cio, J3D_MS_ZSI, 2);  /* ZSI */\r
+       lenp = cio_tell(cio);\r
+       cio_skip(cio, 2);\r
+       cio_write(cio, volume->z1, 4);  /* Zsiz */\r
+       cio_write(cio, volume->z0, 4);  /* Z0siz */\r
+       cio_write(cio, cp->tdz, 4);             /* ZTsiz */\r
+       cio_write(cio, cp->tz0, 4);             /* ZT0siz */\r
+       for (i = 0; i < volume->numcomps; i++) {\r
+               cio_write(cio, volume->comps[i].dz, 1); /* ZRsiz_i */\r
+       }\r
+       len = cio_tell(cio) - lenp;\r
+       cio_seek(cio, lenp);\r
+       cio_write(cio, len, 2);         /* Lsiz */\r
+       cio_seek(cio, lenp + len);\r
+}\r
+\r
+static void j3d_read_zsi(opj_j3d_t *j3d) {\r
+       int len, i;\r
+       \r
+       opj_cio_t *cio = j3d->cio;\r
+       opj_volume_t *volume = j3d->volume;\r
+       opj_cp_t *cp = j3d->cp;\r
+       \r
+       len = cio_read(cio, 2);                 /* Lsiz */\r
+       volume->z1 = cio_read(cio, 4);  /* Zsiz */\r
+       volume->z0 = cio_read(cio, 4);  /* Z0siz */\r
+       cp->tdz = cio_read(cio, 4);             /* ZTsiz */\r
+       cp->tz0 = cio_read(cio, 4);             /* ZT0siz */\r
+       for (i = 0; i < volume->numcomps; i++) {\r
+               volume->comps[i].dz = cio_read(cio, 1); /* ZRsiz_i */\r
+       }\r
+       \r
+       //Initialization of volume\r
+       cp->tw = int_ceildiv(volume->x1 - cp->tx0, cp->tdx);\r
+       cp->th = int_ceildiv(volume->y1 - cp->ty0, cp->tdy);\r
+       cp->tl = int_ceildiv(volume->z1 - cp->tz0, cp->tdz);\r
+       cp->tcps = (opj_tcp_t *) opj_malloc(cp->tw * cp->th * cp->tl * sizeof(opj_tcp_t));\r
+       cp->tileno = (int *) opj_malloc(cp->tw * cp->th * cp->tl * sizeof(int));\r
+       cp->tileno_size = 0;\r
+       \r
+       for (i = 0; i < cp->tw * cp->th * cp->tl ; i++) {\r
+               cp->tcps[i].POC = 0;\r
+               cp->tcps[i].numpocs = 0;\r
+               cp->tcps[i].first = 1;\r
+       }\r
+       \r
+       /* Initialization for PPM marker (Packets header)*/\r
+       cp->ppm = 0;\r
+       cp->ppm_data = NULL;\r
+       cp->ppm_data_first = NULL;\r
+       cp->ppm_previous = 0;\r
+       cp->ppm_store = 0;\r
+       \r
+       j3d->default_tcp->tccps = (opj_tccp_t *) opj_malloc(sizeof(opj_tccp_t) * volume->numcomps);\r
+       for (i = 0; i < cp->tw * cp->th * cp->tl ; i++) {\r
+               cp->tcps[i].tccps = (opj_tccp_t *) opj_malloc(sizeof(opj_tccp_t) * volume->numcomps);\r
+       }\r
+       j3d->tile_data = (unsigned char **) opj_malloc(cp->tw * cp->th * cp->tl * sizeof(unsigned char *));\r
+       j3d->tile_len = (int *) opj_malloc(cp->tw * cp->th * cp->tl * sizeof(int));\r
+       j3d->state = J3D_STATE_MH;\r
+       \r
+}\r
+static void j3d_write_dco(opj_j3d_t *j3d){\r
+       int lenp, len, i;\r
+       int dcotype;    \r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+       opj_volume_t *volume = j3d->volume;\r
+       opj_cp_t *cp = j3d->cp;\r
+       \r
+       dcotype = 1; /* Offsets are 16bit signed integers Table A21 15444-2 */\r
+       cio_write(cio, J3D_MS_DCO, 2);  /* DCO */\r
+       lenp = cio_tell(cio);\r
+       cio_skip(cio, 2);\r
+       cio_write(cio, dcotype, 1);     \r
+       if (dcotype == 0) {\r
+               for (i = 0; i < volume->numcomps; i++) \r
+                       cio_write(cio, volume->comps[i].dcoffset, 1);   /* SPdco_i */\r
+       } else if (dcotype == 1) {\r
+               for (i = 0; i < volume->numcomps; i++){ \r
+                       cio_write(cio, volume->comps[i].dcoffset, 1);   /* SPdco_i */\r
+                       opj_event_msg(j3d->cinfo, EVT_INFO, "dcotype %d DCO %d \n",dcotype,volume->comps[i].dcoffset);\r
+               }\r
+       }\r
+       len = cio_tell(cio) - lenp;\r
+       cio_seek(cio, lenp);\r
+       cio_write(cio, len, 2);         /* Ldco */\r
+       cio_seek(cio, lenp + len);\r
+\r
+}\r
+static void j3d_read_dco(opj_j3d_t *j3d){\r
+       int len, i;\r
+       int dcotype;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+       opj_volume_t *volume = j3d->volume;\r
+       opj_cp_t *cp = j3d->cp;\r
+       \r
+       len = cio_read(cio, 2);                 /* Lsiz */\r
+       dcotype = cio_read(cio, 1); //offset 8bit unsigned / 16bit signed integers\r
+       if (dcotype == 0) {\r
+               for (i = 0; i < volume->numcomps; i++) {\r
+                       volume->comps[i].dcoffset = cio_read(cio, 1);\r
+                       if (volume->comps[i].dcoffset > 128) \r
+                               volume->comps[i].dcoffset = volume->comps[i].dcoffset - 256;\r
+               }\r
+       } else if (dcotype == 1) {\r
+               for (i = 0; i < volume->numcomps; i++) {\r
+                       volume->comps[i].dcoffset = cio_read(cio, 1);\r
+                       if (volume->comps[i].dcoffset > 128) \r
+                               volume->comps[i].dcoffset = volume->comps[i].dcoffset - 256;\r
+               }\r
+       }\r
+       \r
+}\r
+static void j3d_write_atk(opj_j3d_t *j3d){\r
+       int lenp, len, s, k;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+       opj_volume_t *volume = j3d->volume;\r
+       opj_atk_t *atk = j3d->cp->tcps->tccps->atk;\r
+       \r
+       cio_write(cio, J3D_MS_ATK, 2);  /* ATK */\r
+       lenp = cio_tell(cio);\r
+       cio_skip(cio, 2);                               \r
+       cio_write(cio, atk->index + (atk->coeff_typ << 8) + (atk->filt_cat << 11) \r
+               + (atk->wt_typ << 12) + (atk->minit << 13) + (atk->exten << 14), 2);                    /* Satk */\r
+    if (atk->wt_typ == J3D_ATK_IRR) \r
+               cio_write(cio,(unsigned int) (atk->Katk * 8192.0), 1 << atk->coeff_typ);\r
+       cio_write(cio, atk->Natk, 1);\r
+       for (s = 0; s < atk->Natk; s++){\r
+               if (atk->filt_cat == J3D_ATK_ARB) \r
+                       cio_write(cio, atk->Oatk[s], 1);\r
+               if (atk->wt_typ == J3D_ATK_REV){\r
+                       cio_write(cio, atk->Eatk[s], 1);\r
+                       cio_write(cio, atk->Batk[s], 1);\r
+               }\r
+               cio_write(cio, atk->LCatk[s], 1);\r
+               for (k = 0; k < atk->LCatk[s]; k++)\r
+                       cio_write(cio,(unsigned int) (atk->Aatk[s][k] * 8192.0), 1 << atk->coeff_typ);\r
+       }\r
+       len = cio_tell(cio) - lenp;\r
+       cio_seek(cio, lenp);\r
+       cio_write(cio, len, 2);         /* Latk */\r
+       cio_seek(cio, lenp + len);\r
+}\r
+static void j3d_read_atk(opj_j3d_t *j3d){\r
+       int len, i, Satk, k;\r
+       \r
+       opj_cio_t *cio = j3d->cio;\r
+       opj_volume_t *volume = j3d->volume;\r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_atk_t *atk = cp->tcps->tccps->atk; \r
+       \r
+       len = cio_read(cio, 2);                 /* Latk */\r
+       Satk = cio_read(cio, 2); \r
+       atk->index = Satk & 0x00ff;\r
+       atk->coeff_typ = Satk >> 8 & 0x0007;\r
+       atk->filt_cat = Satk >> 11 & 0x0001;\r
+       atk->wt_typ = Satk >> 12  & 0x0001;\r
+       atk->minit = Satk >> 13 & 0x0001;\r
+       atk->exten = Satk >> 14 & 0x0001;\r
+    if (atk->wt_typ == J3D_ATK_IRR) \r
+               atk->Katk = ((double) cio_read(cio, 1 << atk->coeff_typ) / 8192.0);\r
+       atk->Natk = cio_read(cio, 1);\r
+       for (i = 0; i < atk->Natk; i++) {\r
+               if (atk->filt_cat == J3D_ATK_ARB) \r
+                       atk->Oatk[i] = cio_read(cio, 1);\r
+               if (atk->wt_typ == J3D_ATK_REV){\r
+                       atk->Eatk[i] = cio_read(cio, 1);\r
+                       atk->Batk[i] = cio_read(cio, 1);\r
+               }\r
+               atk->LCatk[i] = cio_read(cio, 1);\r
+               for (k = 0; k < atk->LCatk[i]; k++)\r
+                       atk->Aatk[i][k] = ((double) cio_read(cio, 1 << atk->coeff_typ) / 8192.0);\r
+       }\r
+}\r
+static void j3d_write_cbd(opj_j3d_t *j3d){\r
+}\r
+static void j3d_read_cbd(opj_j3d_t *j3d){\r
+}\r
+static void j3d_write_mct(opj_j3d_t *j3d){\r
+}\r
+static void j3d_read_mct(opj_j3d_t *j3d){\r
+}\r
+static void j3d_write_mcc(opj_j3d_t *j3d){\r
+}\r
+static void j3d_read_mcc(opj_j3d_t *j3d){\r
+}\r
+static void j3d_write_mco(opj_j3d_t *j3d){\r
+}\r
+static void j3d_read_mco(opj_j3d_t *j3d){\r
+}\r
+static void j3d_write_nlt(opj_j3d_t *j3d){\r
+}\r
+static void j3d_read_nlt(opj_j3d_t *j3d){\r
+}\r
+/* ----------------------------------------------------------------------- \r
+15444-1 codestream syntax\r
+------------------------------------------------------------------------*/\r
+static void j3d_write_soc(opj_j3d_t *j3d) {\r
+       opj_cio_t *cio = j3d->cio;\r
+       cio_write(cio, J3D_MS_SOC, 2);\r
+}\r
+\r
+static void j3d_read_soc(opj_j3d_t *j3d) {\r
+       j3d->state = J3D_STATE_MHSIZ;\r
+}\r
+\r
+static void j3d_write_siz(opj_j3d_t *j3d) {\r
+       int i;\r
+       int lenp, len;\r
+       int Rsiz;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+       opj_volume_t *volume = j3d->volume;\r
+       opj_cp_t *cp = j3d->cp;\r
+       \r
+       cio_write(cio, J3D_MS_SIZ, 2);  /* SIZ */\r
+       lenp = cio_tell(cio);\r
+       cio_skip(cio, 2);\r
+       //cio_write(cio, 0, 2);                 /* Rsiz (capabilities of 15444-1 only) */\r
+       Rsiz = J3D_RSIZ_DCO | J3D_RSIZ_ATK; /** | J3D_RSIZ_MCT | J3D_RSIZ_NONLT (not implemented yet)*/\r
+       cio_write(cio, Rsiz, 2); /* capabilities of WDv5.2*/\r
+       cio_write(cio, volume->x1, 4);  /* Xsiz */\r
+       cio_write(cio, volume->y1, 4);  /* Ysiz */\r
+       cio_write(cio, volume->x0, 4);  /* X0siz */\r
+       cio_write(cio, volume->y0, 4);  /* Y0siz */\r
+       cio_write(cio, cp->tdx, 4);             /* XTsiz */\r
+       cio_write(cio, cp->tdy, 4);             /* YTsiz */\r
+       cio_write(cio, cp->tx0, 4);             /* XT0siz */\r
+       cio_write(cio, cp->ty0, 4);             /* YT0siz */\r
+       cio_write(cio, volume->numcomps, 2);    /* Csiz */\r
+       for (i = 0; i < volume->numcomps; i++) {\r
+               cio_write(cio, volume->comps[i].prec - 1 + (volume->comps[i].sgnd << 7), 1);    /* Ssiz_i */\r
+               cio_write(cio, volume->comps[i].dx, 1); /* XRsiz_i */\r
+               cio_write(cio, volume->comps[i].dy, 1); /* YRsiz_i */\r
+       }\r
+       len = cio_tell(cio) - lenp;\r
+       cio_seek(cio, lenp);\r
+       cio_write(cio, len, 2);         /* Lsiz */\r
+       cio_seek(cio, lenp + len);\r
+}\r
+\r
+static void j3d_read_siz(opj_j3d_t *j3d) {\r
+       int len, i;\r
+       \r
+       opj_cio_t *cio = j3d->cio;\r
+       opj_volume_t *volume = j3d->volume;\r
+       opj_cp_t *cp = j3d->cp;\r
+       \r
+       len = cio_read(cio, 2);                 /* Lsiz */\r
+       cp->rsiz = cio_read(cio, 2);    /* Rsiz (capabilities) */\r
+       volume->x1 = cio_read(cio, 4);  /* Xsiz */\r
+       volume->y1 = cio_read(cio, 4);  /* Ysiz */\r
+       volume->x0 = cio_read(cio, 4);  /* X0siz */\r
+       volume->y0 = cio_read(cio, 4);  /* Y0siz */\r
+       cp->tdx = cio_read(cio, 4);             /* XTsiz */\r
+       cp->tdy = cio_read(cio, 4);             /* YTsiz */\r
+       cp->tx0 = cio_read(cio, 4);             /* XT0siz */\r
+       cp->ty0 = cio_read(cio, 4);             /* YT0siz */\r
+       \r
+       volume->numcomps = cio_read(cio, 2);    /* Csiz */\r
+       volume->comps = (opj_volume_comp_t *) opj_malloc(volume->numcomps * sizeof(opj_volume_comp_t));\r
+       for (i = 0; i < volume->numcomps; i++) {\r
+               int tmp, j;\r
+               tmp = cio_read(cio, 1);         /* Ssiz_i */\r
+               volume->comps[i].prec = (tmp & 0x7f) + 1;\r
+               volume->comps[i].sgnd = tmp >> 7;\r
+               volume->comps[i].dx = cio_read(cio, 1); /* XRsiz_i */\r
+               volume->comps[i].dy = cio_read(cio, 1); /* YRsiz_i */\r
+               for (j = 0; j < 3; j++) {\r
+                       volume->comps[i].resno_decoded[j] = 0;          /* number of resolution decoded */\r
+                       volume->comps[i].factor[j] = 0;         /* reducing factor per component */\r
+               }\r
+       }\r
+\r
+       if (j3d->cinfo->codec_format == CODEC_J2K){\r
+               volume->z1 = 1;\r
+               volume->z0 = 0;\r
+               volume->numslices = 1;\r
+               cp->tdz = 1;\r
+               cp->tz0 = 0;\r
+               for (i = 0; i < volume->numcomps; i++) \r
+                       volume->comps[i].dz = 1;\r
+\r
+               //Initialization of volume\r
+               cp->tw = int_ceildiv(volume->x1 - cp->tx0, cp->tdx);\r
+               cp->th = int_ceildiv(volume->y1 - cp->ty0, cp->tdy);\r
+               cp->tl = int_ceildiv(volume->z1 - cp->tz0, cp->tdz);\r
+               cp->tcps = (opj_tcp_t *) opj_malloc(cp->tw * cp->th * cp->tl * sizeof(opj_tcp_t));\r
+               cp->tileno = (int *) opj_malloc(cp->tw * cp->th * cp->tl * sizeof(int));\r
+               cp->tileno_size = 0;\r
+               \r
+               for (i = 0; i < cp->tw * cp->th * cp->tl ; i++) {\r
+                       cp->tcps[i].POC = 0;\r
+                       cp->tcps[i].numpocs = 0;\r
+                       cp->tcps[i].first = 1;\r
+               }\r
+               \r
+               /* Initialization for PPM marker (Packets header)*/\r
+               cp->ppm = 0;\r
+               cp->ppm_data = NULL;\r
+               cp->ppm_data_first = NULL;\r
+               cp->ppm_previous = 0;\r
+               cp->ppm_store = 0;\r
+               \r
+               j3d->default_tcp->tccps = (opj_tccp_t *) opj_malloc(sizeof(opj_tccp_t) * volume->numcomps);\r
+               for (i = 0; i < cp->tw * cp->th * cp->tl ; i++) {\r
+                       cp->tcps[i].tccps = (opj_tccp_t *) opj_malloc(sizeof(opj_tccp_t) * volume->numcomps);\r
+               }\r
+               j3d->tile_data = (unsigned char **) opj_malloc(cp->tw * cp->th * cp->tl * sizeof(unsigned char *));\r
+               j3d->tile_len = (int *) opj_malloc(cp->tw * cp->th * cp->tl * sizeof(int));\r
+               j3d->state = J3D_STATE_MH;\r
+       }\r
+}\r
+\r
+\r
+\r
+static void j3d_write_com(opj_j3d_t *j3d) {\r
+       unsigned int i;\r
+       int lenp, len;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+\r
+       cio_write(cio, J3D_MS_COM, 2);\r
+       lenp = cio_tell(cio);\r
+       cio_skip(cio, 2);\r
+       //cio_write(cio, 0, 2);\r
+       cio_write(cio, j3d->cp->transform_format,1);\r
+       cio_write(cio, j3d->cp->encoding_format,1);\r
+       //opj_event_msg(j3d->cinfo, EVT_INFO, "TRF %D ENCOD %d\n",j3d->cp->transform_format,j3d->cp->encoding_format);\r
+       if (j3d->cp->comment != NULL) {\r
+               char *comment = j3d->cp->comment;\r
+               for (i = 0; i < strlen(comment); i++) {\r
+            cio_write(cio, comment[i], 1);\r
+               }\r
+       }\r
+       len = cio_tell(cio) - lenp;\r
+       cio_seek(cio, lenp);\r
+       cio_write(cio, len, 2);\r
+       cio_seek(cio, lenp + len);\r
+}\r
+\r
+static void j3d_read_com(opj_j3d_t *j3d) {\r
+       int len;\r
+       opj_cio_t *cio = j3d->cio;\r
+\r
+       len = cio_read(cio, 2);\r
+       \r
+       j3d->cp->transform_format = (OPJ_TRANSFORM) cio_read(cio, 1);\r
+       j3d->cp->encoding_format = (OPJ_ENTROPY_CODING) cio_read(cio, 1);\r
+       //opj_event_msg(j3d->cinfo, EVT_INFO, "TRF %D ENCOD %d\n",j3d->cp->transform_format,j3d->cp->encoding_format);\r
+\r
+       cio_skip(cio, len - 4);  //posible comments\r
+}\r
+\r
+static void j3d_write_cox(opj_j3d_t *j3d, int compno) {\r
+       int i;\r
+\r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_tcp_t *tcp = &cp->tcps[j3d->curtileno];\r
+       opj_tccp_t *tccp = &tcp->tccps[compno];\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       cio_write(cio, tccp->numresolution[0] - 1, 1);  /* SPcox (D) No of decomposition levels in x-axis*/\r
+       if (j3d->cinfo->codec_format == CODEC_J3D) {\r
+               cio_write(cio, tccp->numresolution[1] - 1, 1);  /* SPcox (E) No of decomposition levels in y-axis*/\r
+               cio_write(cio, tccp->numresolution[2] - 1, 1);  /* SPcox (F) No of decomposition levels in z-axis*/\r
+       }\r
+       /* (cblkw - 2) + (cblkh - 2) + (cblkl - 2) <= 18*/\r
+       cio_write(cio, tccp->cblk[0] - 2, 1);                           /* SPcox (G) Cblk width entre 10 y 2 (8 y 0)*/\r
+       cio_write(cio, tccp->cblk[1] - 2, 1);                           /* SPcox (H) Cblk height*/\r
+       if (j3d->cinfo->codec_format == CODEC_J3D) {\r
+               cio_write(cio, tccp->cblk[2] - 2, 1);                   /* SPcox (I) Cblk depth*/\r
+       }\r
+       cio_write(cio, tccp->cblksty, 1);                               /* SPcox (J) Cblk style*/\r
+       cio_write(cio, tccp->dwtid[0], 1);                              /* SPcox (K) WT in x-axis 15444-2 Table A10*/\r
+       if (j3d->cinfo->codec_format == CODEC_J3D) {\r
+               cio_write(cio, tccp->dwtid[1], 1);                              /* SPcox (L) WT in y-axis 15444-2 Table A10*/\r
+               cio_write(cio, tccp->dwtid[2], 1);                              /* SPcox (M) WT in z-axis 15444-2 Table A10*/\r
+       }\r
+       \r
+       if (tccp->csty & J3D_CCP_CSTY_PRT) {\r
+               for (i = 0; i < tccp->numresolution[0]; i++) {\r
+                       if (i < tccp->numresolution[2])\r
+                cio_write(cio, tccp->prctsiz[0][i] + (tccp->prctsiz[1][i] << 4) + (tccp->prctsiz[2][i] << 8), 2);      /* SPcox (N_i) Table A9*/\r
+                       else\r
+                               if (j3d->cinfo->codec_format == CODEC_J3D) \r
+                    cio_write(cio, tccp->prctsiz[0][i] + (tccp->prctsiz[1][i] << 4), 2);       /* SPcox (N_i) Table A9*/\r
+                               else\r
+                    cio_write(cio, tccp->prctsiz[0][i] + (tccp->prctsiz[1][i] << 4), 1);       /* SPcox (N_i) Table A9*/               }\r
+       }\r
+}\r
+\r
+static void j3d_read_cox(opj_j3d_t *j3d, int compno) {\r
+       int i;\r
+\r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_tcp_t *tcp = j3d->state == J3D_STATE_TPH ? &cp->tcps[j3d->curtileno] : j3d->default_tcp;\r
+       opj_tccp_t *tccp = &tcp->tccps[compno];\r
+       opj_cio_t *cio = j3d->cio;\r
+\r
+       tccp->numresolution[0] = cio_read(cio, 1) + 1;  /* SPcox (D) No of decomposition levels in x-axis*/\r
+       if (j3d->cinfo->codec_format == CODEC_J3D) {\r
+               tccp->numresolution[1] = cio_read(cio, 1) + 1;  /* SPcox (E) No of decomposition levels in y-axis*/\r
+               tccp->numresolution[2] = cio_read(cio, 1) + 1;  /* SPcox (F) No of decomposition levels in z-axis*/\r
+       }else if (j3d->cinfo->codec_format == CODEC_J2K) {\r
+               tccp->numresolution[1] = tccp->numresolution[0];        \r
+               tccp->numresolution[2] = 1;                                                     \r
+       }\r
+       /* check the reduce value */\r
+       cp->reduce[0] = int_min((tccp->numresolution[0])-1, cp->reduce[0]);\r
+       cp->reduce[1] = int_min((tccp->numresolution[1])-1, cp->reduce[1]);\r
+       cp->reduce[2] = int_min((tccp->numresolution[2])-1, cp->reduce[2]);\r
+       \r
+       tccp->cblk[0] = cio_read(cio, 1) + 2;   /* SPcox (G) */\r
+       tccp->cblk[1] = cio_read(cio, 1) + 2;   /* SPcox (H) */\r
+       if (j3d->cinfo->codec_format == CODEC_J3D)\r
+               tccp->cblk[2] = cio_read(cio, 1) + 2;   /* SPcox (I) */\r
+       else\r
+               tccp->cblk[2] = tccp->cblk[0];\r
+\r
+       tccp->cblksty = cio_read(cio, 1);       /* SPcox (J) */\r
+       tccp->dwtid[0] = cio_read(cio, 1);      /* SPcox (K) */\r
+       if (j3d->cinfo->codec_format == CODEC_J3D) {\r
+               tccp->dwtid[1] = cio_read(cio, 1);      /* SPcox (L) */\r
+               tccp->dwtid[2] = cio_read(cio, 1);      /* SPcox (M) */\r
+       }else{\r
+               tccp->dwtid[1] = tccp->dwtid[0];        /* SPcox (L) */\r
+               tccp->dwtid[2] = tccp->dwtid[0];        /* SPcox (M) */\r
+       }\r
+       tccp->reversible = (tccp->dwtid[0]>=1 && tccp->dwtid[1]>=1 && tccp->dwtid[2]>=1); //TODO: only valid for irreversible 9x7 WTs\r
+       if (tccp->csty & J3D_CP_CSTY_PRT) {\r
+               for (i = 0; i < tccp->numresolution[0]; i++) {\r
+                       int tmp = cio_read(cio, 2);     /* SPcox (N_i) */\r
+                       tccp->prctsiz[0][i] = tmp & 0xf;\r
+                       tccp->prctsiz[1][i] = tmp >> 4;\r
+                       tccp->prctsiz[2][i] = tmp >> 8;\r
+               }\r
+       }\r
+}\r
+\r
+static void j3d_write_cod(opj_j3d_t *j3d) {\r
+       opj_cp_t *cp = NULL;\r
+       opj_tcp_t *tcp = NULL;\r
+       int lenp, len;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       cio_write(cio, J3D_MS_COD, 2);  /* COD */\r
+       \r
+       lenp = cio_tell(cio);\r
+       cio_skip(cio, 2);\r
+       \r
+       cp = j3d->cp;\r
+       tcp = &cp->tcps[j3d->curtileno];\r
+\r
+       /* Scod : Table A-4*/\r
+       cio_write(cio, tcp->csty, 1);           /* Scod : Coding style parameters */\r
+       /* SGcod : Table A-5*/\r
+       cio_write(cio, tcp->prg, 1);            /* SGcod (A) : Progression order */\r
+       cio_write(cio, tcp->numlayers, 2);      /* SGcod (B) : No of layers */\r
+       cio_write(cio, tcp->mct, 1);            /* SGcod (C) : Multiple component transformation usage */\r
+       /* SPcod : Table A-6*/\r
+       j3d_write_cox(j3d, 0);                          \r
+       len = cio_tell(cio) - lenp;\r
+       cio_seek(cio, lenp);\r
+       cio_write(cio, len, 2);         /* Lcod */\r
+       cio_seek(cio, lenp + len);\r
+}\r
+\r
+static void j3d_read_cod(opj_j3d_t *j3d) {\r
+       int len, i, pos;\r
+       \r
+       opj_cio_t *cio = j3d->cio;\r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_tcp_t *tcp = j3d->state == J3D_STATE_TPH ? &cp->tcps[j3d->curtileno] : j3d->default_tcp;\r
+       opj_volume_t *volume = j3d->volume;\r
+\r
+       /* Lcod */\r
+       len = cio_read(cio, 2);                         \r
+       /* Scod : Table A-4*/\r
+       tcp->csty = cio_read(cio, 1);           \r
+       /* SGcod : Table A-5*/\r
+       tcp->prg = (OPJ_PROG_ORDER)cio_read(cio, 1);\r
+       tcp->numlayers = cio_read(cio, 2);      \r
+       tcp->mct = cio_read(cio, 1);            \r
+       \r
+       pos = cio_tell(cio);\r
+       for (i = 0; i < volume->numcomps; i++) {\r
+               tcp->tccps[i].csty = tcp->csty & J3D_CP_CSTY_PRT;\r
+               cio_seek(cio, pos);\r
+               j3d_read_cox(j3d, i);\r
+       }\r
+}\r
+\r
+static void j3d_write_coc(opj_j3d_t *j3d, int compno) {\r
+       int lenp, len;\r
+\r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_tcp_t *tcp = &cp->tcps[j3d->curtileno];\r
+       opj_volume_t *volume = j3d->volume;\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       cio_write(cio, J3D_MS_COC, 2);  /* COC */\r
+       lenp = cio_tell(cio);\r
+       cio_skip(cio, 2);\r
+       cio_write(cio, compno, volume->numcomps <= 256 ? 1 : 2);        /* Ccoc */\r
+       cio_write(cio, tcp->tccps[compno].csty, 1);                                     /* Scoc */\r
+       \r
+       j3d_write_cox(j3d, compno);\r
+       \r
+       len = cio_tell(cio) - lenp;\r
+       cio_seek(cio, lenp);\r
+       cio_write(cio, len, 2);                 /* Lcoc */\r
+       cio_seek(cio, lenp + len);\r
+}\r
+\r
+static void j3d_read_coc(opj_j3d_t *j3d) {\r
+       int len, compno;\r
+\r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_tcp_t *tcp = j3d->state == J3D_STATE_TPH ? &cp->tcps[j3d->curtileno] : j3d->default_tcp;\r
+       opj_volume_t *volume = j3d->volume;\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       len = cio_read(cio, 2);         /* Lcoc */\r
+       compno = cio_read(cio, volume->numcomps <= 256 ? 1 : 2);        /* Ccoc */\r
+       tcp->tccps[compno].csty = cio_read(cio, 1);     /* Scoc */\r
+       j3d_read_cox(j3d, compno);\r
+}\r
+\r
+static void j3d_write_qcx(opj_j3d_t *j3d, int compno) {\r
+       int bandno, numbands;\r
+       int expn, mant;\r
+       \r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_tcp_t *tcp = &cp->tcps[j3d->curtileno];\r
+       opj_tccp_t *tccp = &tcp->tccps[compno];\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       cio_write(cio, tccp->qntsty + (tccp->numgbits << 5), 1);        /* Sqcx : Table A28 de 15444-1*/\r
+       \r
+       if (j3d->cinfo->codec_format == CODEC_J2K)\r
+        numbands = tccp->qntsty == J3D_CCP_QNTSTY_SIQNT ? 1 : tccp->numresolution[0] * 3 - 2; \r
+       else if (j3d->cinfo->codec_format == CODEC_J3D) {\r
+               int diff = tccp->numresolution[0] - tccp->numresolution[2];\r
+        numbands = (tccp->qntsty == J3D_CCP_QNTSTY_SIQNT) ? 1 : (tccp->numresolution[0] * 7 - 6) - 4 *diff; /* SIQNT vs. SEQNT */\r
+       }\r
+       \r
+       for (bandno = 0; bandno < numbands; bandno++) {\r
+               expn = tccp->stepsizes[bandno].expn;\r
+               mant = tccp->stepsizes[bandno].mant;\r
+               \r
+               if (tccp->qntsty == J3D_CCP_QNTSTY_NOQNT) {\r
+                       cio_write(cio, expn << 3, 1);   /* SPqcx_i */\r
+               } else {\r
+                       cio_write(cio, (expn << 11) + mant, 2); /* SPqcx_i */\r
+               }\r
+       }\r
+}\r
+\r
+static void j3d_read_qcx(opj_j3d_t *j3d, int compno, int len) {\r
+       int tmp;\r
+       int bandno, numbands;\r
+\r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_tcp_t *tcp = j3d->state == J3D_STATE_TPH ? &cp->tcps[j3d->curtileno] : j3d->default_tcp;\r
+       opj_tccp_t *tccp = &tcp->tccps[compno];\r
+       opj_cio_t *cio = j3d->cio;\r
+\r
+       tmp = cio_read(cio, 1);         /* Sqcx */\r
+       tccp->qntsty = tmp & 0x1f;\r
+       tccp->numgbits = tmp >> 5;\r
+\r
+       /*Numbands = 1                          si SIQNT\r
+                            len - 1            si NOQNT\r
+                                (len - 1) / 2  si SEQNT */\r
+       numbands = tccp->qntsty == J3D_CCP_QNTSTY_SIQNT ? 1 : ((tccp->qntsty == J3D_CCP_QNTSTY_NOQNT) ? len - 1 : (len - 1) / 2);\r
+\r
+       for (bandno = 0; bandno < numbands; bandno++) {\r
+               int expn, mant;\r
+               if (tccp->qntsty == J3D_CCP_QNTSTY_NOQNT) {\r
+                       expn = cio_read(cio, 1) >> 3;   /* SPqcx_i */\r
+                       mant = 0;\r
+               } else {\r
+                       tmp = cio_read(cio, 2);                 /* SPqcx_i */\r
+                       expn = tmp >> 11;\r
+                       mant = tmp & 0x7ff;\r
+               }\r
+               tccp->stepsizes[bandno].expn = expn;\r
+               tccp->stepsizes[bandno].mant = mant;\r
+       }\r
+       \r
+       /* Add Antonin : if scalar_derived -> compute other stepsizes */\r
+       if (tccp->qntsty == J3D_CCP_QNTSTY_SIQNT) {\r
+               for (bandno = 1; bandno < J3D_MAXBANDS; bandno++) {\r
+                       int numbands = (cp->transform_format==TRF_2D_DWT) ? 3 : 7;\r
+                       tccp->stepsizes[bandno].expn = tccp->stepsizes[0].expn - ((bandno - 1) / numbands);\r
+                       tccp->stepsizes[bandno].mant = tccp->stepsizes[0].mant;\r
+               }\r
+       }\r
+       /* ddA */\r
+}\r
+\r
+static void j3d_write_qcd(opj_j3d_t *j3d) {\r
+       int lenp, len;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       cio_write(cio, J3D_MS_QCD, 2);  /* QCD */\r
+       lenp = cio_tell(cio);\r
+       cio_skip(cio, 2);\r
+       j3d_write_qcx(j3d, 0);                  /* Sqcd*/\r
+       len = cio_tell(cio) - lenp;\r
+       cio_seek(cio, lenp);\r
+       cio_write(cio, len, 2);                 /* Lqcd */\r
+       cio_seek(cio, lenp + len);\r
+}\r
+\r
+static void j3d_read_qcd(opj_j3d_t *j3d) {\r
+       int len, i, pos;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+       opj_volume_t *volume = j3d->volume;\r
+       \r
+       len = cio_read(cio, 2);         /* Lqcd */\r
+       pos = cio_tell(cio);\r
+       for (i = 0; i < volume->numcomps; i++) {\r
+               cio_seek(cio, pos);\r
+               j3d_read_qcx(j3d, i, len - 2);\r
+       }\r
+}\r
+\r
+static void j3d_write_qcc(opj_j3d_t *j3d, int compno) {\r
+       int lenp, len;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       cio_write(cio, J3D_MS_QCC, 2);  /* QCC */\r
+       lenp = cio_tell(cio);\r
+       cio_skip(cio, 2);\r
+       cio_write(cio, compno, j3d->volume->numcomps <= 256 ? 1 : 2);   /* Cqcc */\r
+       j3d_write_qcx(j3d, compno);\r
+       len = cio_tell(cio) - lenp;\r
+       cio_seek(cio, lenp);\r
+       cio_write(cio, len, 2);                 /* Lqcc */\r
+       cio_seek(cio, lenp + len);\r
+}\r
+\r
+static void j3d_read_qcc(opj_j3d_t *j3d) {\r
+       int len, compno;\r
+       int numcomp = j3d->volume->numcomps;\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       len = cio_read(cio, 2); /* Lqcc */\r
+       compno = cio_read(cio, numcomp <= 256 ? 1 : 2); /* Cqcc */\r
+       j3d_read_qcx(j3d, compno, len - 2 - (numcomp <= 256 ? 1 : 2));\r
+}\r
+\r
+static void j3d_write_poc(opj_j3d_t *j3d) {\r
+       int len, numpchgs, i;\r
+\r
+       int numcomps = j3d->volume->numcomps;\r
+       \r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_tcp_t *tcp = &cp->tcps[j3d->curtileno];\r
+       opj_tccp_t *tccp = &tcp->tccps[0];\r
+       opj_cio_t *cio = j3d->cio;\r
+\r
+       numpchgs = tcp->numpocs;\r
+       cio_write(cio, J3D_MS_POC, 2);  /* POC  */\r
+       len = 2 + (5 + 2 * (numcomps <= 256 ? 1 : 2)) * numpchgs;\r
+       cio_write(cio, len, 2);         /* Lpoc */\r
+       for (i = 0; i < numpchgs; i++) {\r
+               opj_poc_t *poc = &tcp->pocs[i];\r
+               cio_write(cio, poc->resno0, 1); /* RSpoc_i */\r
+               cio_write(cio, poc->compno0, (numcomps <= 256 ? 1 : 2));        /* CSpoc_i */\r
+               cio_write(cio, poc->layno1, 2); /* LYEpoc_i */\r
+               poc->layno1 = int_min(poc->layno1, tcp->numlayers);\r
+               cio_write(cio, poc->resno1, 1); /* REpoc_i */\r
+               poc->resno1 = int_min(poc->resno1, tccp->numresolution[0]);\r
+               cio_write(cio, poc->compno1, (numcomps <= 256 ? 1 : 2));        /* CEpoc_i */\r
+               poc->compno1 = int_min(poc->compno1, numcomps);\r
+               cio_write(cio, poc->prg, 1);    /* Ppoc_i */\r
+       }\r
+}\r
+\r
+static void j3d_read_poc(opj_j3d_t *j3d) {\r
+       int len, numpchgs, i, old_poc;\r
+\r
+       int numcomps = j3d->volume->numcomps;\r
+       \r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_tcp_t *tcp = j3d->state == J3D_STATE_TPH ? &cp->tcps[j3d->curtileno] : j3d->default_tcp;\r
+       opj_tccp_t *tccp = &tcp->tccps[0];\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       old_poc = tcp->POC ? tcp->numpocs + 1 : 0;\r
+       tcp->POC = 1;\r
+       len = cio_read(cio, 2);         /* Lpoc */\r
+       numpchgs = (len - 2) / (5 + 2 * (numcomps <= 256 ? 1 : 2));\r
+       \r
+       for (i = old_poc; i < numpchgs + old_poc; i++) {\r
+               opj_poc_t *poc;\r
+               poc = &tcp->pocs[i];\r
+               poc->resno0 = cio_read(cio, 1); /* RSpoc_i */\r
+               poc->compno0 = cio_read(cio, numcomps <= 256 ? 1 : 2);  /* CSpoc_i */\r
+               poc->layno1 = int_min(cio_read(cio, 2), (unsigned int) tcp->numlayers); /* LYEpoc_i */\r
+               poc->resno1 = int_min(cio_read(cio, 1), (unsigned int) tccp->numresolution[0]); /* REpoc_i */\r
+               poc->compno1 = int_min(\r
+                       cio_read(cio, numcomps <= 256 ? 1 : 2), (unsigned int) numcomps);       /* CEpoc_i */\r
+               poc->prg = (OPJ_PROG_ORDER)cio_read(cio, 1);    /* Ppoc_i */\r
+       }\r
+       \r
+       tcp->numpocs = numpchgs + old_poc - 1;\r
+}\r
+\r
+static void j3d_read_crg(opj_j3d_t *j3d) {\r
+       int len, i, Xcrg_i, Ycrg_i, Zcrg_i;\r
+       \r
+       opj_cio_t *cio = j3d->cio;\r
+       int numcomps = j3d->volume->numcomps;\r
+       \r
+       len = cio_read(cio, 2);                 /* Lcrg */\r
+       for (i = 0; i < numcomps; i++) {\r
+               Xcrg_i = cio_read(cio, 2);      /* Xcrg_i */\r
+               Ycrg_i = cio_read(cio, 2);      /* Ycrg_i */\r
+               Zcrg_i = cio_read(cio, 2);      /* Zcrg_i */\r
+       }\r
+}\r
+\r
+static void j3d_read_tlm(opj_j3d_t *j3d) {\r
+       int len, Ztlm, Stlm, ST, SP, tile_tlm, i;\r
+       long int Ttlm_i, Ptlm_i;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       len = cio_read(cio, 2);         /* Ltlm */\r
+       Ztlm = cio_read(cio, 1);        /* Ztlm */\r
+       Stlm = cio_read(cio, 1);        /* Stlm */\r
+       ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);\r
+       SP = (Stlm >> 6) & 0x01;\r
+       tile_tlm = (len - 4) / ((SP + 1) * 2 + ST);\r
+       for (i = 0; i < tile_tlm; i++) {\r
+               Ttlm_i = cio_read(cio, ST);     /* Ttlm_i */\r
+               Ptlm_i = cio_read(cio, SP ? 4 : 2);     /* Ptlm_i */\r
+       }\r
+}\r
+\r
+static void j3d_read_plm(opj_j3d_t *j3d) {\r
+       int len, i, Zplm, Nplm, add, packet_len = 0;\r
+       \r
+       opj_cio_t *cio = j3d->cio;\r
+\r
+       len = cio_read(cio, 2);         /* Lplm */\r
+       Zplm = cio_read(cio, 1);        /* Zplm */\r
+       len -= 3;\r
+       while (len > 0) {\r
+               Nplm = cio_read(cio, 4);                /* Nplm */\r
+               len -= 4;\r
+               for (i = Nplm; i > 0; i--) {\r
+                       add = cio_read(cio, 1);\r
+                       len--;\r
+                       packet_len = (packet_len << 7) + add;   /* Iplm_ij */\r
+                       if ((add & 0x80) == 0) {\r
+                               /* New packet */\r
+                               packet_len = 0;\r
+                       }\r
+                       if (len <= 0)\r
+                               break;\r
+               }\r
+       }\r
+}\r
+\r
+static void j3d_read_plt(opj_j3d_t *j3d) {\r
+       int len, i, Zplt, packet_len = 0, add;\r
+       \r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       len = cio_read(cio, 2);         /* Lplt */\r
+       Zplt = cio_read(cio, 1);        /* Zplt */\r
+       for (i = len - 3; i > 0; i--) {\r
+               add = cio_read(cio, 1);\r
+               packet_len = (packet_len << 7) + add;   /* Iplt_i */\r
+               if ((add & 0x80) == 0) {\r
+                       /* New packet */\r
+                       packet_len = 0;\r
+               }\r
+       }\r
+}\r
+\r
+static void j3d_read_ppm(opj_j3d_t *j3d) {\r
+       int len, Z_ppm, i, j;\r
+       int N_ppm;\r
+\r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       len = cio_read(cio, 2);\r
+       cp->ppm = 1;\r
+       \r
+       Z_ppm = cio_read(cio, 1);       /* Z_ppm */\r
+       len -= 3;\r
+       while (len > 0) {\r
+               if (cp->ppm_previous == 0) {\r
+                       N_ppm = cio_read(cio, 4);       /* N_ppm */\r
+                       len -= 4;\r
+               } else {\r
+                       N_ppm = cp->ppm_previous;\r
+               }\r
+               j = cp->ppm_store;\r
+               if (Z_ppm == 0) {       /* First PPM marker */\r
+                       cp->ppm_data = (unsigned char *) opj_malloc(N_ppm * sizeof(unsigned char));\r
+                       cp->ppm_data_first = cp->ppm_data;\r
+                       cp->ppm_len = N_ppm;\r
+               } else {                        /* NON-first PPM marker */\r
+                       cp->ppm_data = (unsigned char *) opj_realloc(cp->ppm_data, (N_ppm +     cp->ppm_store) * sizeof(unsigned char));\r
+                       cp->ppm_data_first = cp->ppm_data;\r
+                       cp->ppm_len = N_ppm + cp->ppm_store;\r
+               }\r
+               for (i = N_ppm; i > 0; i--) {   /* Read packet header */\r
+                       cp->ppm_data[j] = cio_read(cio, 1);\r
+                       j++;\r
+                       len--;\r
+                       if (len == 0)\r
+                               break;                  /* Case of non-finished packet header in present marker but finished in next one */\r
+               }\r
+               cp->ppm_previous = i - 1;\r
+               cp->ppm_store = j;\r
+       }\r
+}\r
+\r
+static void j3d_read_ppt(opj_j3d_t *j3d) {\r
+       int len, Z_ppt, i, j = 0;\r
+\r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_tcp_t *tcp = cp->tcps + j3d->curtileno;\r
+       opj_cio_t *cio = j3d->cio;\r
+\r
+       len = cio_read(cio, 2);\r
+       Z_ppt = cio_read(cio, 1);\r
+       tcp->ppt = 1;\r
+       if (Z_ppt == 0) {               /* First PPT marker */\r
+               tcp->ppt_data = (unsigned char *) opj_malloc((len - 3) * sizeof(unsigned char));\r
+               tcp->ppt_data_first = tcp->ppt_data;\r
+               tcp->ppt_store = 0;\r
+               tcp->ppt_len = len - 3;\r
+       } else {                        /* NON-first PPT marker */\r
+               tcp->ppt_data = (unsigned char *) opj_realloc(tcp->ppt_data, (len - 3 + tcp->ppt_store) * sizeof(unsigned char));\r
+               tcp->ppt_data_first = tcp->ppt_data;\r
+               tcp->ppt_len = len - 3 + tcp->ppt_store;\r
+       }\r
+       j = tcp->ppt_store;\r
+       for (i = len - 3; i > 0; i--) {\r
+               tcp->ppt_data[j] = cio_read(cio, 1);\r
+               j++;\r
+       }\r
+       tcp->ppt_store = j;\r
+}\r
+\r
+static void j3d_write_sot(opj_j3d_t *j3d) {\r
+       int lenp, len;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+\r
+       j3d->sot_start = cio_tell(cio);\r
+       cio_write(cio, J3D_MS_SOT, 2);          /* SOT */\r
+       lenp = cio_tell(cio);\r
+       cio_skip(cio, 2);                                       /* Lsot (further) */\r
+       cio_write(cio, j3d->curtileno, 2);      /* Isot */\r
+       cio_skip(cio, 4);                                       /* Psot (further in j3d_write_sod) */\r
+       cio_write(cio, 0, 1);                           /* TPsot */\r
+       cio_write(cio, 1, 1);                           /* TNsot (no of tile-parts of this tile in this codestream)*/\r
+       len = cio_tell(cio) - lenp;\r
+       cio_seek(cio, lenp);\r
+       cio_write(cio, len, 2);                         /* Lsot */\r
+       cio_seek(cio, lenp + len);\r
+}\r
+\r
+static void j3d_read_sot(opj_j3d_t *j3d) {\r
+       int len, tileno, totlen, partno, numparts, i;\r
+       opj_tcp_t *tcp = NULL;\r
+       char status = 0;\r
+\r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       len = cio_read(cio, 2);\r
+       tileno = cio_read(cio, 2);\r
+       \r
+       if (cp->tileno_size == 0) {\r
+               cp->tileno[cp->tileno_size] = tileno;\r
+               cp->tileno_size++;\r
+       } else {\r
+               i = 0;\r
+               while (i < cp->tileno_size && status == 0) {\r
+                       status = cp->tileno[i] == tileno ? 1 : 0;\r
+                       i++;\r
+               }\r
+               if (status == 0) {\r
+                       cp->tileno[cp->tileno_size] = tileno;\r
+                       cp->tileno_size++;\r
+               }\r
+       }\r
+       \r
+       totlen = cio_read(cio, 4);\r
+       if (!totlen)\r
+               totlen = cio_numbytesleft(cio) + 8;\r
+       \r
+       partno = cio_read(cio, 1);\r
+       numparts = cio_read(cio, 1);\r
+       \r
+       j3d->curtileno = tileno;\r
+       j3d->eot = cio_getbp(cio) - 12 + totlen;\r
+       j3d->state = J3D_STATE_TPH;\r
+       tcp = &cp->tcps[j3d->curtileno];\r
+       \r
+       if (tcp->first == 1) {\r
+               \r
+               /* Initialization PPT */\r
+               opj_tccp_t *tmp = tcp->tccps;\r
+               memcpy(tcp, j3d->default_tcp, sizeof(opj_tcp_t));\r
+               tcp->ppt = 0;\r
+               tcp->ppt_data = NULL;\r
+               tcp->ppt_data_first = NULL;\r
+               tcp->tccps = tmp;\r
+\r
+               for (i = 0; i < j3d->volume->numcomps; i++) {\r
+                       tcp->tccps[i] = j3d->default_tcp->tccps[i];\r
+               }\r
+               cp->tcps[j3d->curtileno].first = 0;\r
+       }\r
+}\r
+\r
+static void j3d_write_sod(opj_j3d_t *j3d, void *tile_coder) {\r
+       int l, layno;\r
+       int totlen;\r
+       opj_tcp_t *tcp = NULL;\r
+       opj_volume_info_t *volume_info = NULL;\r
+       \r
+       opj_tcd_t *tcd = (opj_tcd_t*)tile_coder;        /* cast is needed because of conflicts in header inclusions */\r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_cio_t *cio = j3d->cio;\r
+       \r
+       cio_write(cio, J3D_MS_SOD, 2);\r
+       if (j3d->curtileno == 0) {\r
+               j3d->sod_start = cio_tell(cio) + j3d->pos_correction;\r
+       }\r
+       \r
+       /* INDEX >> */\r
+       volume_info = j3d->volume_info;\r
+       if (volume_info && volume_info->index_on) {\r
+               volume_info->tile[j3d->curtileno].end_header = cio_tell(cio) + j3d->pos_correction - 1;\r
+       }\r
+       /* << INDEX */\r
+       \r
+       tcp = &cp->tcps[j3d->curtileno];\r
+       for (layno = 0; layno < tcp->numlayers; layno++) {\r
+               tcp->rates[layno] -= tcp->rates[layno] ? (j3d->sod_start / (cp->th * cp->tw * cp->tl)) : 0;\r
+       }\r
+       \r
+       if(volume_info) {\r
+               volume_info->num = 0;\r
+       }\r
+\r
+       l = tcd_encode_tile(tcd, j3d->curtileno, cio_getbp(cio), cio_numbytesleft(cio) - 2, volume_info);\r
+       \r
+       /* Writing Psot in SOT marker */\r
+       totlen = cio_tell(cio) + l - j3d->sot_start;\r
+       cio_seek(cio, j3d->sot_start + 6);\r
+       cio_write(cio, totlen, 4);\r
+       cio_seek(cio, j3d->sot_start + totlen);\r
+}\r
+\r
+static void j3d_read_sod(opj_j3d_t *j3d) {\r
+       int len, truncate = 0, i;\r
+       unsigned char *data = NULL, *data_ptr = NULL;\r
+\r
+       opj_cio_t *cio = j3d->cio;\r
+       int curtileno = j3d->curtileno;\r
+       \r
+       len = int_min(j3d->eot - cio_getbp(cio), cio_numbytesleft(cio) + 1);\r
+       \r
+       if (len == cio_numbytesleft(cio) + 1) {\r
+               truncate = 1;           /* Case of a truncate codestream */\r
+       }\r
+       \r
+       data = (unsigned char *) opj_malloc((j3d->tile_len[curtileno] + len) * sizeof(unsigned char));\r
+\r
+       for (i = 0; i < j3d->tile_len[curtileno]; i++) {\r
+               data[i] = j3d->tile_data[curtileno][i];\r
+       }\r
+\r
+       data_ptr = data + j3d->tile_len[curtileno];\r
+       for (i = 0; i < len; i++) {\r
+               data_ptr[i] = cio_read(cio, 1);\r
+       }\r
+       \r
+       j3d->tile_len[curtileno] += len;\r
+       opj_free(j3d->tile_data[curtileno]);\r
+       j3d->tile_data[curtileno] = data;\r
+       \r
+       if (!truncate) {\r
+               j3d->state = J3D_STATE_TPHSOT;\r
+       } else {\r
+               j3d->state = J3D_STATE_NEOC;    /* RAJOUTE !! */\r
+       }\r
+}\r
+\r
+static void j3d_write_rgn(opj_j3d_t *j3d, int compno, int tileno) {\r
+       \r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_tcp_t *tcp = &cp->tcps[tileno];\r
+       opj_cio_t *cio = j3d->cio;\r
+       int numcomps = j3d->volume->numcomps;\r
+       \r
+       cio_write(cio, J3D_MS_RGN, 2);                                          /* RGN  */\r
+       cio_write(cio, numcomps <= 256 ? 5 : 6, 2);                     /* Lrgn */\r
+       cio_write(cio, compno, numcomps <= 256 ? 1 : 2);        /* Crgn */\r
+       cio_write(cio, 0, 1);                                                           /* Srgn */\r
+       cio_write(cio, tcp->tccps[compno].roishift, 1);         /* SPrgn */\r
+}\r
+\r
+static void j3d_read_rgn(opj_j3d_t *j3d) {\r
+       int len, compno, roisty;\r
+\r
+       opj_cp_t *cp = j3d->cp;\r
+       opj_tcp_t *tcp = j3d->state == J3D_STATE_TPH ? &cp->tcps[j3d->curtileno] : j3d->default_tcp;\r
+       opj_cio_t *cio = j3d->cio;\r
+       int numcomps = j3d->volume->numcomps;\r
+\r
+       len = cio_read(cio, 2);                                                                         /* Lrgn */\r
+       compno = cio_read(cio, numcomps <= 256 ? 1 : 2);                        /* Crgn */\r
+       roisty = cio_read(cio, 1);                                                                      /* Srgn */\r
+       tcp->tccps[compno].roishift = cio_read(cio, 1);                         /* SPrgn */\r
+}\r
+\r
+static void j3d_write_eoc(opj_j3d_t *j3d) {\r
+       opj_cio_t *cio = j3d->cio;\r
+       /* opj_event_msg(j3d->cinfo, "%.8x: EOC\n", cio_tell(cio) + j3d->pos_correction); */\r
+       cio_write(cio, J3D_MS_EOC, 2);\r
+}\r
+\r
+static void j3d_read_eoc(opj_j3d_t *j3d) {\r
+       int i, tileno;\r
+\r
+#ifndef NO_PACKETS_DECODING  \r
+       opj_tcd_t *tcd = tcd_create(j3d->cinfo);\r
+    tcd_malloc_decode(tcd, j3d->volume, j3d->cp);\r
+       /*j3d_dump_volume(stdout, tcd->volume);\r
+       j3d_dump_cp(stdout, tcd->volume, tcd->cp);*/\r
+       for (i = 0; i < j3d->cp->tileno_size; i++) {\r
+               tileno = j3d->cp->tileno[i];\r
+               //opj_event_msg(j3d->cinfo, EVT_INFO, "tcd_decode_tile \n");\r
+               tcd_decode_tile(tcd, j3d->tile_data[tileno], j3d->tile_len[tileno], tileno);\r
+               opj_free(j3d->tile_data[tileno]);\r
+               j3d->tile_data[tileno] = NULL;\r
+       }\r
+       tcd_free_decode(tcd);\r
+       tcd_destroy(tcd);\r
+#else \r
+       for (i = 0; i < j3d->cp->tileno_size; i++) {\r
+               tileno = j3d->cp->tileno[i];\r
+               opj_free(j3d->tile_data[tileno]);\r
+               j3d->tile_data[tileno] = NULL;\r
+       }\r
+#endif\r
+       \r
+       j3d->state = J3D_STATE_MT;\r
+}\r
+\r
+static void j3d_read_unk(opj_j3d_t *j3d) {\r
+       opj_event_msg(j3d->cinfo, EVT_WARNING, "Unknown marker\n");\r
+}\r
+\r
+static opj_atk_t atk_info_wt[] = {\r
+       {0, 1, J3D_ATK_WS, J3D_ATK_IRR, 0, J3D_ATK_WS, 1.230174104, 4, {0}, {0}, {0}, {1,1,1,1}, {-1.586134342059924, -0.052980118572961, 0.882911075530934, 0.443506852043971}},/* WT 9-7 IRR*/\r
+       {1, 0, J3D_ATK_WS, J3D_ATK_REV, 0, J3D_ATK_WS, 0, 2, {0}, {1,2}, {1,2}, {1,1}, {-1.0,1.0}},/* WT 5-3 REV*/\r
+       {2, 0, J3D_ATK_ARB, J3D_ATK_REV, 0, J3D_ATK_CON, 0, 2, {0,0}, {0,1}, {0,1}, {1,1}, {{-1.0},{1.0}}}, /* WT 2-2 REV*/\r
+       {3, 0, J3D_ATK_ARB, J3D_ATK_REV, 1, J3D_ATK_CON, 0, 3, {0,0,-1}, {0,1,2}, {0,1,2}, {1,1,3}, {{-1.0},{1.0},{1.0,0.0,-1.0}}}, /* WT 2-6 REV*/\r
+       {4, 0, J3D_ATK_ARB, J3D_ATK_REV, 1, J3D_ATK_CON, 0, 3, {0,0,-2}, {0,1,6}, {0,1,32}, {1,1,5}, {{-1},{1},{-3.0,22.0,0.0,-22.0,3.0}}}, /* WT 2-10 REV*/\r
+       {5, 1, J3D_ATK_ARB, J3D_ATK_IRR, 1, J3D_ATK_WS, 1, 7, {0}, {0}, {0}, {1,1,2,1,2,1,3},{{-1},{1.58613434206},{-0.460348209828, 0.460348209828},{0.25},{0.374213867768,-0.374213867768},{-1.33613434206},{0.29306717103,0,-0.29306717103}}}, /* WT 6-10 IRR*/\r
+       {6, 1, J3D_ATK_ARB, J3D_ATK_IRR, 0, J3D_ATK_WS, 1, 11, {0}, {0}, {0}, {1,1,2,1,2,1,2,1,2,1,5},{{-1},{0,99715069105},{-1.00573127827, 1.00573127827},{-0.27040357631},{2.20509972343, -2.20509972343},{0.08059995736},\r
+               {-1.62682532350, 1.62682532350},{0.52040357631},{0.60404664250, -0.60404664250},{-0.82775064841},{-0.06615812964, 0.29402137720, 0, -0.29402137720, 0.06615812964}}}, /* WT 10-18 IRR*/\r
+       {7, 1, J3D_ATK_WS, J3D_ATK_IRR, 0, J3D_ATK_WS, 1, 2, {0}, {0}, {0}, {1,1}, {-0.5, 0.25}},       /* WT 5-3 IRR*/\r
+       {8, 0, J3D_ATK_WS, J3D_ATK_REV, 0, J3D_ATK_WS, 0, 2, {0}, {4,4}, {8,8}, {2,2}, {{-9,1},{5,-1}}}         /* WT 13-7 REV*/\r
+};\r
+\r
+typedef struct opj_dec_mstabent {\r
+       /** marker value */\r
+       int id;\r
+       /** value of the state when the marker can appear */\r
+       int states;\r
+       /** action linked to the marker */\r
+       void (*handler) (opj_j3d_t *j3d);\r
+} opj_dec_mstabent_t;\r
+\r
+opj_dec_mstabent_t j3d_dec_mstab[] = {\r
+  {J3D_MS_SOC, J3D_STATE_MHSOC, j3d_read_soc},\r
+  {J3D_MS_SOT, J3D_STATE_MH | J3D_STATE_TPHSOT, j3d_read_sot},\r
+  {J3D_MS_SOD, J3D_STATE_TPH, j3d_read_sod},\r
+  {J3D_MS_EOC, J3D_STATE_TPHSOT, j3d_read_eoc},\r
+  {J3D_MS_CAP, J3D_STATE_MHSIZ, j3d_read_cap},\r
+  {J3D_MS_SIZ, J3D_STATE_MHSIZ, j3d_read_siz},\r
+  {J3D_MS_ZSI, J3D_STATE_MHSIZ, j3d_read_zsi},\r
+  {J3D_MS_COD, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_cod},\r
+  {J3D_MS_COC, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_coc},\r
+  {J3D_MS_RGN, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_rgn},\r
+  {J3D_MS_QCD, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_qcd},\r
+  {J3D_MS_QCC, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_qcc},\r
+  {J3D_MS_POC, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_poc},\r
+  {J3D_MS_TLM, J3D_STATE_MH, j3d_read_tlm},\r
+  {J3D_MS_PLM, J3D_STATE_MH, j3d_read_plm},\r
+  {J3D_MS_PLT, J3D_STATE_TPH, j3d_read_plt},\r
+  {J3D_MS_PPM, J3D_STATE_MH, j3d_read_ppm},\r
+  {J3D_MS_PPT, J3D_STATE_TPH, j3d_read_ppt},\r
+  {J3D_MS_SOP, 0, 0},\r
+  {J3D_MS_CRG, J3D_STATE_MH, j3d_read_crg},\r
+  {J3D_MS_COM, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_com},\r
+  {J3D_MS_DCO, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_dco},\r
+  {J3D_MS_ATK, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_atk},\r
+  {0, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_unk}\r
+  /*, -->must define the j3d_read functions\r
+  {J3D_MS_CBD, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_cbd},\r
+  {J3D_MS_MCT, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_mct},\r
+  {J3D_MS_MCC, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_mcc},\r
+  {J3D_MS_MCO, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_mco},\r
+  {J3D_MS_NLT, J3D_STATE_MH | J3D_STATE_TPH, j3d_read_nlt},\r
+  {J3D_MS_VMS, J3D_STATE_MH, j3d_read_vms},\r
+  {J3D_MS_DFS, J3D_STATE_MH, j3d_read_dfs},\r
+  {J3D_MS_ADS, J3D_STATE_MH, j3d_read_ads},\r
+  {J3D_MS_QPD, J3D_STATE_MH, j3d_read_qpd},\r
+  {J3D_MS_QPC, J3D_STATE_TPH, j3d_read_qpc}*/\r
+};\r
+\r
+/**\r
+Read the lookup table containing all the marker, status and action\r
+@param id Marker value\r
+*/\r
+static opj_dec_mstabent_t *j3d_dec_mstab_lookup(int id) {\r
+       opj_dec_mstabent_t *e;\r
+       for (e = j3d_dec_mstab; e->id != 0; e++) {\r
+               if (e->id == id) {\r
+                       break;\r
+               }\r
+       }\r
+       return e;\r
+}\r
+\r
+/* ----------------------------------------------------------------------- */\r
+/* J3D / JPT decoder interface                                             */\r
+/* ----------------------------------------------------------------------- */\r
+\r
+opj_j3d_t* j3d_create_decompress(opj_common_ptr cinfo) {\r
+       opj_j3d_t *j3d = (opj_j3d_t*)opj_malloc(sizeof(opj_j3d_t));\r
+       if(j3d) {\r
+               j3d->cinfo = cinfo;\r
+               j3d->default_tcp = (opj_tcp_t*)opj_malloc(sizeof(opj_tcp_t));\r
+               if(!j3d->default_tcp) {\r
+                       opj_free(j3d);\r
+                       return NULL;\r
+               }\r
+       }\r
+       return j3d;\r
+}\r
+\r
+void j3d_destroy_decompress(opj_j3d_t *j3d) {\r
+       int i = 0;\r
+\r
+       if(j3d->tile_len != NULL) {\r
+               opj_free(j3d->tile_len);\r
+       }\r
+       if(j3d->tile_data != NULL) {\r
+               opj_free(j3d->tile_data);\r
+       }\r
+       if(j3d->default_tcp != NULL) {\r
+               opj_tcp_t *default_tcp = j3d->default_tcp;\r
+               if(default_tcp->ppt_data_first != NULL) {\r
+                       opj_free(default_tcp->ppt_data_first);\r
+               }\r
+               if(j3d->default_tcp->tccps != NULL) {\r
+                       opj_free(j3d->default_tcp->tccps);\r
+               }\r
+               opj_free(j3d->default_tcp);\r
+       }\r
+       if(j3d->cp != NULL) {\r
+               opj_cp_t *cp = j3d->cp;\r
+               if(cp->tcps != NULL) {\r
+                       for(i = 0; i < cp->tw * cp->th * cp->tl; i++) {\r
+                               if(cp->tcps[i].ppt_data_first != NULL) {\r
+                                       opj_free(cp->tcps[i].ppt_data_first);\r
+                               }\r
+                               if(cp->tcps[i].tccps != NULL) {\r
+                                       opj_free(cp->tcps[i].tccps);\r
+                               }\r
+                       }\r
+                       opj_free(cp->tcps);\r
+               }\r
+               if(cp->ppm_data_first != NULL) {\r
+                       opj_free(cp->ppm_data_first);\r
+               }\r
+               if(cp->tileno != NULL) {\r
+                       opj_free(cp->tileno);  \r
+               }\r
+               if(cp->comment != NULL) {\r
+                       opj_free(cp->comment);\r
+               }\r
+\r
+               opj_free(cp);\r
+       }\r
+\r
+       opj_free(j3d);\r
+}\r
+\r
+void j3d_setup_decoder(opj_j3d_t *j3d, opj_dparameters_t *parameters) {\r
+       if(j3d && parameters) {\r
+               /* create and initialize the coding parameters structure */\r
+               opj_cp_t *cp = (opj_cp_t*)opj_malloc(sizeof(opj_cp_t));\r
+               cp->reduce[0] = parameters->cp_reduce[0];\r
+               cp->reduce[1] = parameters->cp_reduce[1];\r
+               cp->reduce[2] = parameters->cp_reduce[2];\r
+               cp->layer = parameters->cp_layer;\r
+               cp->bigendian = parameters->bigendian;\r
+               \r
+               \r
+               cp->encoding_format = ENCOD_2EB;\r
+               cp->transform_format = TRF_2D_DWT;\r
+               \r
+               /* keep a link to cp so that we can destroy it later in j3d_destroy_decompress */\r
+               j3d->cp = cp;\r
+       }\r
+}\r
+\r
+opj_volume_t* j3d_decode(opj_j3d_t *j3d, opj_cio_t *cio) {\r
+       opj_volume_t *volume = NULL;\r
+\r
+       opj_common_ptr cinfo = j3d->cinfo;\r
+\r
+       j3d->cio = cio;\r
+\r
+       /* create an empty volume */\r
+       volume = (opj_volume_t*)opj_malloc(sizeof(opj_volume_t));\r
+       j3d->volume = volume;\r
+\r
+       j3d->state = J3D_STATE_MHSOC;\r
+       \r
+       for (;;) {\r
+               opj_dec_mstabent_t *e;\r
+               int id = cio_read(cio, 2);\r
+               if (id >> 8 != 0xff) {\r
+                       opj_volume_destroy(volume);\r
+                       opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);\r
+                       return 0;\r
+               }\r
+               e = j3d_dec_mstab_lookup(id);\r
+               //opj_event_msg(cinfo, EVT_INFO, "MARKER %x PREVSTATE %d E->STATE %d\n",e->id,j3d->state,e->states);\r
+               if (!(j3d->state & e->states)) {\r
+                       opj_volume_destroy(volume);\r
+                       opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id);\r
+                       return 0;\r
+               }\r
+               if (e->handler) {\r
+                       (*e->handler)(j3d);\r
+               }\r
+               //opj_event_msg(cinfo, EVT_INFO, "POSTSTATE %d\n",j3d->state);\r
+               if (j3d->state == J3D_STATE_MT) {\r
+                       break;\r
+               }\r
+               if (j3d->state == J3D_STATE_NEOC) {\r
+                       break;\r
+               }\r
+       }\r
+       if (j3d->state == J3D_STATE_NEOC) {\r
+               j3d_read_eoc(j3d);\r
+       }\r
+\r
+       if (j3d->state != J3D_STATE_MT) {\r
+               opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n");\r
+       }\r
+       \r
+       return volume;\r
+}\r
+\r
+/* ----------------------------------------------------------------------- */\r
+/* J3D encoder interface                                                       */\r
+/* ----------------------------------------------------------------------- */\r
+\r
+opj_j3d_t* j3d_create_compress(opj_common_ptr cinfo) {\r
+       opj_j3d_t *j3d = (opj_j3d_t*)opj_malloc(sizeof(opj_j3d_t));\r
+       if(j3d) {\r
+               j3d->cinfo = cinfo;\r
+       }\r
+       return j3d;\r
+}\r
+\r
+void j3d_destroy_compress(opj_j3d_t *j3d) {\r
+       int tileno;\r
+\r
+       if(!j3d) return;\r
+\r
+       if(j3d->volume_info != NULL) {\r
+               opj_volume_info_t *volume_info = j3d->volume_info;\r
+               if (volume_info->index_on && j3d->cp) {\r
+                       opj_cp_t *cp = j3d->cp;\r
+                       for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {\r
+                               opj_tile_info_t *tile_info = &volume_info->tile[tileno];\r
+                               opj_free(tile_info->thresh);\r
+                               opj_free(tile_info->packet);\r
+                       }\r
+                       opj_free(volume_info->tile);\r
+               }\r
+               opj_free(volume_info);\r
+       }\r
+       if(j3d->cp != NULL) {\r
+               opj_cp_t *cp = j3d->cp;\r
+\r
+               if(cp->comment) {\r
+                       opj_free(cp->comment);\r
+               }\r
+               if(cp->matrice) {\r
+                       opj_free(cp->matrice);\r
+               }\r
+               for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {\r
+                       opj_free(cp->tcps[tileno].tccps);\r
+               }\r
+               opj_free(cp->tcps);\r
+               opj_free(cp);\r
+       }\r
+\r
+       opj_free(j3d);\r
+}\r
+\r
+void j3d_setup_encoder(opj_j3d_t *j3d, opj_cparameters_t *parameters, opj_volume_t *volume) {\r
+       int i, j, tileno, numpocs_tile;\r
+       opj_cp_t *cp = NULL;\r
+\r
+       if(!j3d || !parameters || ! volume) {\r
+               return;\r
+       }\r
+\r
+       /* create and initialize the coding parameters structure */\r
+       cp = (opj_cp_t*)opj_malloc(sizeof(opj_cp_t));\r
+\r
+       /* keep a link to cp so that we can destroy it later in j3d_destroy_compress */\r
+       j3d->cp = cp;\r
+\r
+       /* set default values for cp */\r
+       cp->tw = 1;\r
+       cp->th = 1;\r
+       cp->tl = 1;\r
+\r
+       /* copy user encoding parameters */\r
+       cp->disto_alloc = parameters->cp_disto_alloc;\r
+       cp->fixed_alloc = parameters->cp_fixed_alloc;\r
+       cp->fixed_quality = parameters->cp_fixed_quality;\r
+\r
+       /* transform and coding method */\r
+       cp->transform_format = parameters->transform_format;\r
+       cp->encoding_format = parameters->encoding_format;\r
+\r
+       /* mod fixed_quality */\r
+       if(parameters->cp_matrice) {\r
+               size_t array_size = parameters->tcp_numlayers * 3 * parameters->numresolution[0] * sizeof(int);\r
+               cp->matrice = (int *) opj_malloc(array_size);\r
+               memcpy(cp->matrice, parameters->cp_matrice, array_size);\r
+       } \r
+\r
+       /* creation of an index file ? */\r
+       cp->index_on = parameters->index_on;\r
+       if(cp->index_on) {\r
+               j3d->volume_info = (opj_volume_info_t*)opj_malloc(sizeof(opj_volume_info_t));\r
+       }\r
+       \r
+       /* tiles */\r
+       cp->tdx = parameters->cp_tdx;\r
+       cp->tdy = parameters->cp_tdy;\r
+       cp->tdz = parameters->cp_tdz;\r
+       /* tile offset */\r
+       cp->tx0 = parameters->cp_tx0;\r
+       cp->ty0 = parameters->cp_ty0;\r
+       cp->tz0 = parameters->cp_tz0;\r
+       /* comment string */\r
+       if(parameters->cp_comment) {\r
+               cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1);\r
+               if(cp->comment) {\r
+                       strcpy(cp->comment, parameters->cp_comment);\r
+               }\r
+       }\r
+\r
+       /*calculate other encoding parameters*/\r
+       if (parameters->tile_size_on) {\r
+               cp->tw = int_ceildiv(volume->x1 - cp->tx0, cp->tdx);\r
+               cp->th = int_ceildiv(volume->y1 - cp->ty0, cp->tdy);\r
+               cp->tl = int_ceildiv(volume->z1 - cp->tz0, cp->tdz);\r
+       } else {\r
+               cp->tdx = volume->x1 - cp->tx0;\r
+               cp->tdy = volume->y1 - cp->ty0;\r
+               cp->tdz = volume->z1 - cp->tz0;\r
+       }\r
+\r
+       /* initialize the multiple tiles */\r
+       /* ---------------------------- */\r
+       cp->tcps = (opj_tcp_t *) opj_malloc(cp->tw * cp->th * cp->tl * sizeof(opj_tcp_t));\r
+\r
+       for (tileno = 0; tileno < cp->tw * cp->th * cp->tl; tileno++) {\r
+               opj_tcp_t *tcp = &cp->tcps[tileno];\r
+               tcp->numlayers = parameters->tcp_numlayers;\r
+               for (j = 0; j < tcp->numlayers; j++) {\r
+                       if (cp->fixed_quality) {        /* add fixed_quality */\r
+                               tcp->distoratio[j] = parameters->tcp_distoratio[j];\r
+                       } else {\r
+                               tcp->rates[j] = parameters->tcp_rates[j];\r
+                       }\r
+               }\r
+               tcp->csty = parameters->csty;\r
+               tcp->prg = parameters->prog_order;\r
+               tcp->mct = volume->numcomps == 3 ? 1 : 0;\r
+\r
+               numpocs_tile = 0;\r
+               tcp->POC = 0;\r
+               if (parameters->numpocs) {\r
+                       /* initialisation of POC */\r
+                       tcp->POC = 1;\r
+                       for (i = 0; i < parameters->numpocs; i++) {\r
+                               if((tileno == parameters->POC[i].tile - 1) || (parameters->POC[i].tile == -1)) {\r
+                                       opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];\r
+                                       tcp_poc->resno0         = parameters->POC[numpocs_tile].resno0;\r
+                                       tcp_poc->compno0        = parameters->POC[numpocs_tile].compno0;\r
+                                       tcp_poc->layno1         = parameters->POC[numpocs_tile].layno1;\r
+                                       tcp_poc->resno1         = parameters->POC[numpocs_tile].resno1;\r
+                                       tcp_poc->compno1        = parameters->POC[numpocs_tile].compno1;\r
+                                       tcp_poc->prg            = parameters->POC[numpocs_tile].prg;\r
+                                       tcp_poc->tile           = parameters->POC[numpocs_tile].tile;\r
+                                       numpocs_tile++;\r
+                               }\r
+                       }\r
+               }\r
+               tcp->numpocs = numpocs_tile;\r
+\r
+               tcp->tccps = (opj_tccp_t *) opj_malloc(volume->numcomps * sizeof(opj_tccp_t));\r
+               \r
+               for (i = 0; i < volume->numcomps; i++) {\r
+                       opj_tccp_t *tccp = &tcp->tccps[i];\r
+                       tccp->csty = parameters->csty & J3D_CCP_CSTY_PRT;       /* 0 => standard precint || 1 => custom-defined precinct  */\r
+                       tccp->numresolution[0] = parameters->numresolution[0];\r
+                       tccp->numresolution[1] = parameters->numresolution[1];\r
+                       tccp->numresolution[2] = parameters->numresolution[2];\r
+                                               assert (parameters->cblock_init[0] <= T1_MAXCBLKW);\r
+                                               assert (parameters->cblock_init[0] >= T1_MINCBLKW);\r
+                                               assert (parameters->cblock_init[1] <= T1_MAXCBLKH);\r
+                                               assert (parameters->cblock_init[1] >= T1_MINCBLKH);\r
+                                               assert (parameters->cblock_init[2] <= T1_MAXCBLKD);\r
+                                               assert (parameters->cblock_init[2] >= T1_MINCBLKD);\r
+                       tccp->cblk[0] = int_floorlog2(parameters->cblock_init[0]); \r
+                       tccp->cblk[1] = int_floorlog2(parameters->cblock_init[1]); \r
+                       tccp->cblk[2] = int_floorlog2(parameters->cblock_init[2]); \r
+                                               assert (tccp->cblk[0]+tccp->cblk[1]+tccp->cblk[1] <= T1_MAXWHD);\r
+                       tccp->cblksty = parameters->mode; //Codeblock style --> Table A.19 (default 0)\r
+\r
+                       /*ATK / transform */\r
+                       tccp->reversible = parameters->irreversible ? 0 : 1; /* 0 => DWT 9-7 || 1 => DWT 5-3  */\r
+                       for (j = 0; j < 3; j++) {\r
+                                       tccp->dwtid[j] = parameters->irreversible ? 0 : 1; /* 0 => DWT 9-7 || 1 => DWT 5-3  */\r
+                       }\r
+                                               \r
+                       /* Quantification: SEQNT (Scalar Expounded, value for each subband) / NOQNT (no quant)*/\r
+                       tccp->qntsty = parameters->irreversible ? J3D_CCP_QNTSTY_SEQNT : J3D_CCP_QNTSTY_NOQNT;\r
+                       tccp->numgbits = 2;\r
+                       if (i == parameters->roi_compno) {\r
+                               tccp->roishift = parameters->roi_shift;\r
+                       } else {\r
+                               tccp->roishift = 0;\r
+                       }\r
+                       /* Custom defined precints */\r
+                       if (parameters->csty & J3D_CCP_CSTY_PRT) {\r
+                               int k;\r
+                               for (k = 0; k < 3; k++) {\r
+                                       int p = 0;\r
+                                       for (j = tccp->numresolution[k] - 1; j >= 0; j--) {\r
+                                               if (p < parameters->res_spec) {/* p < number of precinct size specifications */\r
+                                                       if (parameters->prct_init[k][p] < 1) {\r
+                                                               tccp->prctsiz[k][j] = 1;\r
+                                                       } else {\r
+                                                               tccp->prctsiz[k][j] = int_floorlog2(parameters->prct_init[k][p]);\r
+                                                       }\r
+                                               } else {\r
+                                                       int res_spec = parameters->res_spec;\r
+                                                       int size_prct = parameters->prct_init[k][res_spec - 1] >> (p - (res_spec - 1));\r
+                                                       if (size_prct < 1) {\r
+                                                               tccp->prctsiz[k][j] = 1;\r
+                                                       } else {\r
+                                                               tccp->prctsiz[k][j] = int_floorlog2(size_prct);\r
+                                                       }\r
+                                               }\r
+                                       }\r
+                                       p++;\r
+                               }\r
+                       } else {\r
+                               int k;\r
+                               for (k = 0; k < 3; k++) {\r
+                    for (j = 0; j < tccp->numresolution[k]; j++) {\r
+                        tccp->prctsiz[k][j] = 15;\r
+                                       }\r
+                               }\r
+                       }\r
+                       //Calcular stepsize for each subband (if NOQNT -->stepsize = 1.0)\r
+                       dwt_calc_explicit_stepsizes(tccp, volume->comps[i].prec);\r
+               }\r
+       }\r
+}\r
+\r
+/**\r
+Create an index file\r
+@param j3d\r
+@param cio\r
+@param volume_info\r
+@param index Index filename\r
+@return Returns 1 if successful, returns 0 otherwise\r
+*/\r
+static int j3d_create_index(opj_j3d_t *j3d, opj_cio_t *cio, opj_volume_info_t *volume_info, char *index) {\r
+       \r
+       int tileno, compno, layno, resno, precno, pack_nb, x, y, z;\r
+       FILE *stream = NULL;\r
+       double total_disto = 0;\r
+\r
+       volume_info->codestream_size = cio_tell(cio) + j3d->pos_correction;     /* Correction 14/4/03 suite rmq de Patrick */\r
+\r
+       stream = fopen(index, "w");\r
+       if (!stream) {\r
+               opj_event_msg(j3d->cinfo, EVT_ERROR, "failed to open %s for writing\n", index);\r
+               return 0;\r
+       }\r
+       \r
+       fprintf(stream, "w %d\t h %d\t l %d\n", volume_info->volume_w, volume_info->volume_h, volume_info->volume_l);\r
+       fprintf(stream, "TRASNFORM\t%d\n", volume_info->transform_format);\r
+       fprintf(stream, "ENTROPY CODING\t%d\n", volume_info->encoding_format);\r
+       fprintf(stream, "PROG\t%d\n", volume_info->prog);\r
+       fprintf(stream, "TILE\tx %d y %d z %d\n", volume_info->tile_x, volume_info->tile_y, volume_info->tile_z);\r
+       fprintf(stream, "NOTILE\tx %d y %d z %d\n", volume_info->tw, volume_info->th, volume_info->tl);\r
+       fprintf(stream, "COMPONENTS\t%d\n", volume_info->comp);\r
+       fprintf(stream, "LAYER\t%d\n", volume_info->layer);\r
+       fprintf(stream, "RESOLUTIONS\tx %d y %d z %d\n", volume_info->decomposition[0], volume_info->decomposition[1], volume_info->decomposition[2]);\r
+       \r
+       fprintf(stream, "Precint sizes for each resolution:\n");\r
+       for (resno = volume_info->decomposition[0]; resno >= 0; resno--) {\r
+               fprintf(stream, "Resno %d \t [%d,%d,%d] \n", resno,\r
+                       (1 << volume_info->tile[0].prctsiz[0][resno]), (1 << volume_info->tile[0].prctsiz[0][resno]), (1 << volume_info->tile[0].prctsiz[2][resno]));   /* based on tile 0 */\r
+       }\r
+       fprintf(stream, "HEADER_END\t%d\n", volume_info->main_head_end);\r
+       fprintf(stream, "CODESTREAM\t%d\n", volume_info->codestream_size);\r
+       fprintf(stream, "Num_tile Start_pos End_header End_pos Distotile Nbpix Ratio\n");\r
+       for (tileno = 0; tileno < (volume_info->tw * volume_info->th * volume_info->tl); tileno++) {\r
+               fprintf(stream, "%4d\t%9d\t%9d\t%9d\t%9e\t%9d\t%9e\n",\r
+                       volume_info->tile[tileno].num_tile,\r
+                       volume_info->tile[tileno].start_pos,\r
+                       volume_info->tile[tileno].end_header,\r
+                       volume_info->tile[tileno].end_pos,\r
+                       volume_info->tile[tileno].distotile, volume_info->tile[tileno].nbpix,\r
+                       volume_info->tile[tileno].distotile / volume_info->tile[tileno].nbpix);\r
+       }\r
+       \r
+       for (tileno = 0; tileno < (volume_info->tw * volume_info->th * volume_info->tl); tileno++) {\r
+               int start_pos, end_pos;\r
+               double disto = 0;\r
+               pack_nb = 0;\r
+               if (volume_info->prog == LRCP) {        /* LRCP */\r
+                       fprintf(stream, "pack_nb tileno layno resno compno precno start_pos  end_pos   disto\n");\r
+                       for (layno = 0; layno < volume_info->layer; layno++) {\r
+                               for (resno = 0; resno < volume_info->decomposition[0] + 1; resno++) {\r
+                                       for (compno = 0; compno < volume_info->comp; compno++) {\r
+                                               int prec_max = volume_info->tile[tileno].prctno[0][resno] * volume_info->tile[tileno].prctno[1][resno] * volume_info->tile[tileno].prctno[2][resno];\r
+                                               for (precno = 0; precno < prec_max; precno++) {\r
+                                                       start_pos = volume_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                       end_pos = volume_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                       disto = volume_info->tile[tileno].packet[pack_nb].disto;\r
+                                                       fprintf(stream, "%4d %6d %7d %5d %6d %6d %9d %9d %8e\n",pack_nb, tileno, layno, resno, compno, precno, start_pos, end_pos, disto);\r
+                                                       total_disto += disto;\r
+                                                       pack_nb++;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               } /* LRCP */\r
+               else if (volume_info->prog == RLCP) {   /* RLCP */\r
+                       /*\r
+                       fprintf(stream, "pack_nb tileno resno layno compno precno start_pos  end_pos   disto");\r
+                       */\r
+                       for (resno = 0; resno < volume_info->decomposition[0] + 1; resno++) {\r
+                               for (layno = 0; layno < volume_info->layer; layno++) {\r
+                                       for (compno = 0; compno < volume_info->comp; compno++) {\r
+                                               int prec_max = volume_info->tile[tileno].prctno[0][resno] * volume_info->tile[tileno].prctno[1][resno]* volume_info->tile[tileno].prctno[2][resno];\r
+                                               for (precno = 0; precno < prec_max; precno++) {\r
+                                                       start_pos = volume_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                       end_pos = volume_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                       disto = volume_info->tile[tileno].packet[pack_nb].disto;\r
+                                                       fprintf(stream, "%4d %6d %5d %7d %6d %6d %9d %9d %8e\n",\r
+                                                               pack_nb, tileno, resno, layno, compno, precno, start_pos, end_pos, disto);\r
+                                                       total_disto += disto;\r
+                                                       pack_nb++;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               } /* RLCP */\r
+               else if (volume_info->prog == RPCL) {   /* RPCL */\r
+                       /*\r
+                       fprintf(stream, "\npack_nb tileno resno precno compno layno start_pos  end_pos   disto\n"); \r
+                       */\r
+                       for (resno = 0; resno < volume_info->decomposition[0] + 1; resno++) {\r
+                               /* I suppose components have same XRsiz, YRsiz */\r
+                               //int x0 = volume_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)volume_info->tw ) * volume_info->tw * volume_info->tile_x;\r
+                               //int y0 = volume_info->tile_Ox + (int)floor( (float)tileno/(float)volume_info->tw ) * volume_info->tile_y;\r
+                               int x0 = volume_info->tile_Ox + (int)floor( (float)tileno/(float)volume_info->tw ) * volume_info->tile_x;\r
+                               int y0 = volume_info->tile_Oy + (int)floor( (float)tileno/(float)volume_info->th ) * volume_info->tile_y;\r
+                               int z0 = volume_info->tile_Ox + (int)floor( (float)tileno/(float)volume_info->tl ) * volume_info->tile_z;\r
+                               int x1 = x0 + volume_info->tile_x;\r
+                               int y1 = y0 + volume_info->tile_y;\r
+                               int z1 = z0 + volume_info->tile_z;\r
+                               for(z = z0; z < z1; z++) {\r
+                                       for(y = y0; y < y1; y++) {\r
+                                               for(x = x0; x < x1; x++) {\r
+                                                       for (compno = 0; compno < volume_info->comp; compno++) {\r
+                                                               int prec_max = volume_info->tile[tileno].prctno[0][resno] * volume_info->tile[tileno].prctno[1][resno] * volume_info->tile[tileno].prctno[2][resno];\r
+                                                               for (precno = 0; precno < prec_max; precno++) {\r
+                                                                       int pcnx = volume_info->tile[tileno].prctno[0][resno];\r
+                                                                       int pcx = (int) pow( 2, volume_info->tile[tileno].prctsiz[0][resno] + volume_info->decomposition[0] - resno );\r
+                                                                       int pcy = (int) pow( 2, volume_info->tile[tileno].prctsiz[1][resno] + volume_info->decomposition[1] - resno );\r
+                                                                       int pcz = (int) pow( 2, volume_info->tile[tileno].prctsiz[2][resno] + volume_info->decomposition[2] - 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_y*pcy == y ) {\r
+                                                                               if (precno_x*pcx == x ) {\r
+                                                                                       for (layno = 0; layno < volume_info->layer; layno++) {\r
+                                                                                               start_pos = volume_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                                                               end_pos = volume_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                                                               disto = volume_info->tile[tileno].packet[pack_nb].disto;\r
+                                                                                               fprintf(stream, "%4d %6d %5d %6d %6d %7d %9d %9d %8e\n",\r
+                                                                                                       pack_nb, tileno, resno, precno, compno, layno, start_pos, end_pos, disto); \r
+                                                                                               total_disto += disto;\r
+                                                                                               pack_nb++; \r
+                                                                                       }\r
+                                                                               }\r
+                                                                       }\r
+                                                               } /* precno */\r
+                                                       } /* compno */\r
+                                               } /* x = x0..x1 */\r
+                                       } /* y = y0..y1 */\r
+                               } /* z = z0..z1 */\r
+                       } /* resno */\r
+               } /* RPCL */\r
+               else if (volume_info->prog == PCRL) {   /* PCRL */\r
+                       /* I suppose components have same XRsiz, YRsiz */\r
+                       int x0 = volume_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)volume_info->tw ) * volume_info->tw * volume_info->tile_x;\r
+                       int y0 = volume_info->tile_Ox + (int)floor( (float)tileno/(float)volume_info->tw ) * volume_info->tile_y;\r
+                       int z0 = volume_info->tile_Oz + (int)floor( (float)tileno/(float)volume_info->tw ) * volume_info->tile_z;\r
+                       int x1 = x0 + volume_info->tile_x;\r
+                       int y1 = y0 + volume_info->tile_y;\r
+                       int z1 = z0 + volume_info->tile_z;\r
+                       /*\r
+                       fprintf(stream, "\npack_nb tileno precno compno resno layno start_pos  end_pos   disto\n"); \r
+                       */\r
+                       for(z = z0; z < z1; z++) {\r
+                               for(y = y0; y < y1; y++) {\r
+                                       for(x = x0; x < x1; x++) {\r
+                                               for (compno = 0; compno < volume_info->comp; compno++) {\r
+                                                       for (resno = 0; resno < volume_info->decomposition[0] + 1; resno++) {\r
+                                                               int prec_max = volume_info->tile[tileno].prctno[0][resno] * volume_info->tile[tileno].prctno[1][resno];\r
+                                                               for (precno = 0; precno < prec_max; precno++) {\r
+                                                               int pcnx = volume_info->tile[tileno].prctno[0][resno];\r
+                                                               int pcx = (int) pow( 2, volume_info->tile[tileno].prctsiz[0][resno] + volume_info->decomposition[0] - resno );\r
+                                                               int pcy = (int) pow( 2, volume_info->tile[tileno].prctsiz[1][resno] + volume_info->decomposition[1] - resno );\r
+                                                               int pcz = (int) pow( 2, volume_info->tile[tileno].prctsiz[2][resno] + volume_info->decomposition[2] - resno );\r
+                                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
+                                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
+                                                               int precno_z = (int) floor( (float)precno/(float)pcnx );\r
+                                                               if (precno_z*pcz == z ) {\r
+                                                                       if (precno_y*pcy == y ) {\r
+                                                                               if (precno_x*pcx == x ) {\r
+                                                                                       for (layno = 0; layno < volume_info->layer; layno++) {\r
+                                                                                               start_pos = volume_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                                                               end_pos = volume_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                                                               disto = volume_info->tile[tileno].packet[pack_nb].disto;\r
+                                                                                               fprintf(stream, "%4d %6d %6d %6d %5d %7d %9d %9d %8e\n",\r
+                                                                                                       pack_nb, tileno, precno, compno, resno, layno, start_pos, end_pos, disto); \r
+                                                                                               total_disto += disto;\r
+                                                                                               pack_nb++; \r
+                                                                                       }\r
+                                                                               }\r
+                                                                       }\r
+                                                               }\r
+                                                       } /* precno */\r
+                                               } /* resno */\r
+                                       } /* compno */\r
+                               } /* x = x0..x1 */\r
+                       } /* y = y0..y1 */\r
+                       }\r
+               } /* PCRL */\r
+               else {  /* CPRL */\r
+                       /*\r
+                       fprintf(stream, "\npack_nb tileno compno precno resno layno start_pos  end_pos   disto\n"); \r
+                       */\r
+                       for (compno = 0; compno < volume_info->comp; compno++) {\r
+                               /* I suppose components have same XRsiz, YRsiz */\r
+                               int x0 = volume_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)volume_info->tw ) * volume_info->tw * volume_info->tile_x;\r
+                               int y0 = volume_info->tile_Ox + (int)floor( (float)tileno/(float)volume_info->tw ) * volume_info->tile_y;\r
+                               int z0 = volume_info->tile_Oz + (int)floor( (float)tileno/(float)volume_info->tw ) * volume_info->tile_z;\r
+                               int x1 = x0 + volume_info->tile_x;\r
+                               int y1 = y0 + volume_info->tile_y;\r
+                               int z1 = z0 + volume_info->tile_z;\r
+                               for(z = z0; z < z1; z++) {\r
+                                       for(y = y0; y < y1; y++) {\r
+                                               for(x = x0; x < x1; x++) {\r
+                                                       for (resno = 0; resno < volume_info->decomposition[0] + 1; resno++) {\r
+                                                               int prec_max = volume_info->tile[tileno].prctno[0][resno] * volume_info->tile[tileno].prctno[1][resno] * volume_info->tile[tileno].prctno[2][resno];\r
+                                                               for (precno = 0; precno < prec_max; precno++) {\r
+                                                                       int pcnx = volume_info->tile[tileno].prctno[0][resno];\r
+                                                                       int pcny = volume_info->tile[tileno].prctno[1][resno];\r
+                                                                       int pcx = (int) pow( 2, volume_info->tile[tileno].prctsiz[0][resno] + volume_info->decomposition[0] - resno );\r
+                                                                       int pcy = (int) pow( 2, volume_info->tile[tileno].prctsiz[1][resno] + volume_info->decomposition[1] - resno );\r
+                                                                       int pcz = (int) pow( 2, volume_info->tile[tileno].prctsiz[2][resno] + volume_info->decomposition[2] - resno );\r
+                                                                       int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
+                                                                       int precno_y = (int) floor( (float)precno/(float)pcnx );\r
+                                                                       int precno_z = 0; /*???*/\r
+                                                                       if (precno_z*pcz == z ) {\r
+                                                                               if (precno_y*pcy == y ) {\r
+                                                                                       if (precno_x*pcx == x ) {\r
+                                                                                               for (layno = 0; layno < volume_info->layer; layno++) {\r
+                                                                                                       start_pos = volume_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                                                                       end_pos = volume_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                                                                       disto = volume_info->tile[tileno].packet[pack_nb].disto;\r
+                                                                                                       fprintf(stream, "%4d %6d %6d %6d %5d %7d %9d %9d %8e\n",\r
+                                                                                                               pack_nb, tileno, compno, precno, resno, layno, start_pos, end_pos, disto); \r
+                                                                                                       total_disto += disto;\r
+                                                                                                       pack_nb++; \r
+                                                                                               }\r
+                                                                                       }\r
+                                                                               }\r
+                                                                       }\r
+                                                               } /* precno */\r
+                                                       } /* resno */\r
+                                               } /* x = x0..x1 */\r
+                                       } /* y = y0..y1 */\r
+                               } /* z = z0..z1 */\r
+                       } /* comno */\r
+               } /* CPRL */   \r
+       } /* tileno */\r
+       \r
+       fprintf(stream, "SE_MAX\t%8e\n", volume_info->D_max);   /* SE max */\r
+       fprintf(stream, "SE_TOTAL\t%.8e\n", total_disto);                       /* SE totale */\r
+       \r
+\r
+       fclose(stream);\r
+\r
+       return 1;\r
+}\r
+\r
+bool j3d_encode(opj_j3d_t *j3d, opj_cio_t *cio, opj_volume_t *volume, char *index) {\r
+       int tileno, compno;\r
+       opj_volume_info_t *volume_info = NULL;\r
+       opj_cp_t *cp = NULL;\r
+       opj_tcd_t *tcd = NULL;  /* TCD component */\r
+\r
+       j3d->cio = cio; \r
+       j3d->volume = volume;\r
+       cp = j3d->cp;\r
+\r
+       /*j3d_dump_volume(stdout, volume);\r
+       j3d_dump_cp(stdout, volume, cp);*/\r
+\r
+       /* INDEX >> */\r
+       volume_info = j3d->volume_info;\r
+       if (volume_info && cp->index_on) {\r
+               volume_info->index_on = cp->index_on;\r
+               volume_info->tile = (opj_tile_info_t *) opj_malloc(cp->tw * cp->th * cp->tl * sizeof(opj_tile_info_t));\r
+               volume_info->volume_w = volume->x1 - volume->x0;\r
+               volume_info->volume_h = volume->y1 - volume->y0;\r
+               volume_info->volume_l = volume->z1 - volume->z0;\r
+               volume_info->prog = (&cp->tcps[0])->prg;\r
+               volume_info->tw = cp->tw;\r
+               volume_info->th = cp->th;\r
+               volume_info->tl = cp->tl;\r
+               volume_info->tile_x = cp->tdx;  /* new version parser */\r
+               volume_info->tile_y = cp->tdy;  /* new version parser */\r
+               volume_info->tile_z = cp->tdz;  /* new version parser */\r
+               volume_info->tile_Ox = cp->tx0; /* new version parser */\r
+               volume_info->tile_Oy = cp->ty0; /* new version parser */\r
+               volume_info->tile_Oz = cp->tz0; /* new version parser */\r
+               volume_info->transform_format = cp->transform_format;\r
+               volume_info->encoding_format = cp->encoding_format;\r
+               volume_info->comp = volume->numcomps;\r
+               volume_info->layer = (&cp->tcps[0])->numlayers;\r
+               volume_info->decomposition[0] = (&cp->tcps[0])->tccps->numresolution[0] - 1;\r
+               volume_info->decomposition[1] = (&cp->tcps[0])->tccps->numresolution[1] - 1;\r
+               volume_info->decomposition[2] = (&cp->tcps[0])->tccps->numresolution[2] - 1;\r
+               volume_info->D_max = 0;         /* ADD Marcela */\r
+       }\r
+       /* << INDEX */\r
+\r
+       j3d_write_soc(j3d);\r
+       j3d_write_siz(j3d);\r
+       if (j3d->cinfo->codec_format == CODEC_J3D) {\r
+               j3d_write_cap(j3d);\r
+               j3d_write_zsi(j3d);\r
+       }\r
+       j3d_write_cod(j3d);\r
+       j3d_write_qcd(j3d);\r
+       for (compno = 0; compno < volume->numcomps; compno++) {\r
+               opj_tcp_t *tcp = &cp->tcps[0];\r
+               if (tcp->tccps[compno].roishift)\r
+                       j3d_write_rgn(j3d, compno, 0);                  \r
+       }\r
+       /*Optional 15444-2 markers*/\r
+       if (j3d->cp->tcps->tccps[0].atk != NULL)\r
+        j3d_write_atk(j3d);\r
+       if (j3d->volume->comps[0].dcoffset != 0)\r
+        j3d_write_dco(j3d);\r
+\r
+       if (j3d->cp->transform_format != TRF_2D_DWT || j3d->cp->encoding_format != ENCOD_2EB)\r
+               j3d_write_com(j3d);\r
+       \r
+       /* INDEX >> */\r
+       if(volume_info && volume_info->index_on) {\r
+               volume_info->main_head_end = cio_tell(cio) - 1;\r
+       }\r
+       /* << INDEX */\r
+\r
+       /* create the tile encoder */\r
+       tcd = tcd_create(j3d->cinfo);\r
+\r
+       /* encode each tile */\r
+       for (tileno = 0; tileno < cp->tw * cp->th * cp->tl; tileno++) {\r
+               opj_event_msg(j3d->cinfo, EVT_INFO, "tile number %d / %d\n", tileno + 1, cp->tw * cp->th * cp->tl);\r
+               \r
+               j3d->curtileno = tileno;\r
+\r
+               /* initialisation before tile encoding  */\r
+               if (tileno == 0) {      \r
+                       tcd_malloc_encode(tcd, volume, cp, j3d->curtileno);\r
+               } else {\r
+                       tcd_init_encode(tcd, volume, cp, j3d->curtileno);\r
+               }\r
+               \r
+               /* INDEX >> */\r
+               if(volume_info && volume_info->index_on) {\r
+                       volume_info->tile[j3d->curtileno].num_tile = j3d->curtileno;\r
+                       volume_info->tile[j3d->curtileno].start_pos = cio_tell(cio) + j3d->pos_correction;\r
+               }\r
+               /* << INDEX */\r
+               \r
+               j3d_write_sot(j3d);\r
+       \r
+               for (compno = 1; compno < volume->numcomps; compno++) {\r
+                       j3d_write_coc(j3d, compno);\r
+                       j3d_write_qcc(j3d, compno);\r
+               }\r
+\r
+               if (cp->tcps[tileno].numpocs) {\r
+                       j3d_write_poc(j3d);\r
+               }\r
+               j3d_write_sod(j3d, tcd); //--> tcd_encode_tile\r
+\r
+               /* INDEX >> */\r
+               if(volume_info && volume_info->index_on) {\r
+                       volume_info->tile[j3d->curtileno].end_pos = cio_tell(cio) + j3d->pos_correction - 1;\r
+               }\r
+               /* << INDEX */          \r
+       }\r
+       \r
+       /* destroy the tile encoder */\r
+       tcd_free_encode(tcd);\r
+       tcd_destroy(tcd);\r
+\r
+       j3d_write_eoc(j3d);\r
+       \r
+       /* Creation of the index file */\r
+       if(volume_info && volume_info->index_on) {\r
+               if(!j3d_create_index(j3d, cio, volume_info, index)) {\r
+                       opj_event_msg(j3d->cinfo, EVT_ERROR, "failed to create index file %s\n", index);\r
+                       return false;\r
+               }\r
+       }\r
+         \r
+       return true;\r
+}\r
+\r
diff --git a/src/lib/openjp3d/jp3d.h b/src/lib/openjp3d/jp3d.h
new file mode 100755 (executable)
index 0000000..5d0978c
--- /dev/null
@@ -0,0 +1,518 @@
+/*\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) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain\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
+#ifndef __J3D_H\r
+#define __J3D_H\r
+/**\r
+@file j3d.h\r
+@brief The JPEG-2000 Codestream Reader/Writer (J3D)\r
+\r
+The functions in J3D.C have for goal to read/write the several parts of the codestream: markers and data.\r
+*/\r
+\r
+/** @defgroup J3D J3D - JPEG-2000 codestream reader/writer */\r
+/*@{*/\r
+\r
+#define J3D_CP_CSTY_PRT 0x01\r
+#define J3D_CP_CSTY_SOP 0x02\r
+#define J3D_CP_CSTY_EPH 0x04\r
+#define J3D_CCP_CSTY_PRT 0x01\r
+/** Table A-8 */\r
+#define J3D_CCP_CBLKSTY_LAZY 0x01       /* Selective arithmetic coding bypass */\r
+#define J3D_CCP_CBLKSTY_RESET 0x02   /* Reset context probabilities on coding pass boundaries */\r
+#define J3D_CCP_CBLKSTY_TERMALL 0x04 /* Termination on each coding pass */\r
+#define J3D_CCP_CBLKSTY_VSC 0x08        /* Vertically causal context, add also hook for switching off and on 3D context models */      \r
+#define J3D_CCP_CBLKSTY_PTERM 0x10      /* Predictable termination */\r
+#define J3D_CCP_CBLKSTY_SEGSYM 0x20     /* Segmentation symbols are used */\r
+#define J3D_CCP_CBLKSTY_3DCTXT 0x40  /* 3D context models (3D-EBCOT) vs 2D context models */\r
+\r
+#define J3D_CCP_QNTSTY_NOQNT 0 /* Quantization style : no quantization */\r
+#define J3D_CCP_QNTSTY_SIQNT 1 /* Quantization style : scalar derived (values signalled only in LLL subband) */\r
+#define J3D_CCP_QNTSTY_SEQNT 2 /* Quantization style : scalar expounded (values signalled for each subband) */\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+#define J3D_MS_SOC 0xff4f      /**< SOC marker value */\r
+#define J3D_MS_SOT 0xff90      /**< SOT marker value */\r
+#define J3D_MS_SOD 0xff93      /**< SOD marker value */\r
+#define J3D_MS_EOC 0xffd9      /**< EOC marker value */\r
+#define J3D_MS_CAP 0xff50      /**< CAP marker value */\r
+#define J3D_MS_SIZ 0xff51      /**< SIZ marker value */\r
+#define J3D_MS_ZSI 0xff54      /**< ZSI marker value */\r
+#define J3D_MS_COD 0xff52      /**< COD marker value */\r
+#define J3D_MS_COC 0xff53      /**< COC marker value */\r
+#define J3D_MS_RGN 0xff5e      /**< RGN marker value */\r
+#define J3D_MS_QCD 0xff5c      /**< QCD marker value */\r
+#define J3D_MS_QCC 0xff5d      /**< QCC marker value */\r
+#define J3D_MS_POC 0xff5f      /**< POC marker value */\r
+#define J3D_MS_TLM 0xff55      /**< TLM marker value */\r
+#define J3D_MS_PLM 0xff57      /**< PLM marker value */\r
+#define J3D_MS_PLT 0xff58      /**< PLT marker value */\r
+#define J3D_MS_PPM 0xff60      /**< PPM marker value */\r
+#define J3D_MS_PPT 0xff61      /**< PPT marker value */\r
+#define J3D_MS_SOP 0xff91      /**< SOP marker value */\r
+#define J3D_MS_EPH 0xff92      /**< EPH marker value */\r
+#define J3D_MS_CRG 0xff63      /**< CRG marker value */\r
+#define J3D_MS_COM 0xff64      /**< COM marker value */\r
+//15444-2\r
+#define J3D_MS_DCO 0xff70      /**< DCO marker value */\r
+#define J3D_MS_VMS 0xff71   /**< VMS marker value */\r
+#define J3D_MS_DFS 0xff72      /**< DFS marker value */\r
+#define J3D_MS_ADS 0xff73      /**< ADS marker value */\r
+#define J3D_MS_ATK 0xff79      /**< ATK marker value */\r
+#define J3D_MS_CBD 0xff78      /**< CBD marker value */\r
+#define J3D_MS_MCT 0xff74      /**< MCT marker value */\r
+#define J3D_MS_MCC 0xff75      /**< MCC marker value */\r
+#define J3D_MS_MCO 0xff77      /**< MCO marker value */\r
+#define J3D_MS_NLT 0xff76      /**< NLT marker value */\r
+#define J3D_MS_QPD 0xff5a      /**< QPD marker value */\r
+#define J3D_MS_QPC 0xff5b      /**< QPC marker value */\r
+\r
+/* ----------------------------------------------------------------------- */\r
+/* Capability RSIZ parameter, extended */\r
+#define J3D_RSIZ_BASIC 0x0000\r
+\r
+#define J3D_RSIZ_DCO   0x8001 /* Required */\r
+#define J3D_RSIZ_VSQNT 0x8002\r
+#define J3D_RSIZ_TCQNT 0x8004\r
+#define J3D_RSIZ_VMASK 0x8008\r
+#define J3D_RSIZ_SSOVL 0x8010\r
+#define J3D_RSIZ_ADECS 0x8020\r
+#define J3D_RSIZ_ATK   0x8040 /*Required*/\r
+#define J3D_RSIZ_SSYMK 0x8080\r
+#define J3D_RSIZ_MCT   0x8100 /*Not compatible with DCO*/\r
+#define J3D_RSIZ_NLT   0x8200 /*Required*/\r
+#define J3D_RSIZ_ASHAP 0x8400\r
+#define J3D_RSIZ_PRQNT 0x8800\r
+\r
+#define J3D_CAP_10             0x00400000\r
+/* Arbitrary transformation kernel, 15444-2 */\r
+#define J3D_ATK_IRR 0\r
+#define J3D_ATK_REV 1\r
+#define J3D_ATK_ARB 0\r
+#define J3D_ATK_WS 1\r
+#define J3D_ATK_CON 0\r
+/* ----------------------------------------------------------------------- */\r
+\r
+/**\r
+Values that specify the status of the decoding process when decoding the main header. \r
+These values may be combined with a | operator. \r
+*/\r
+typedef enum J3D_STATUS {\r
+       /**< a SOC marker is expected */\r
+       J3D_STATE_MHSOC  = 0x0001, \r
+       /**< a SIZ marker is expected */\r
+       J3D_STATE_MHSIZ  = 0x0002, \r
+       /**< the decoding process is in the main header */\r
+       J3D_STATE_MH     = 0x0004, \r
+       /**< the decoding process is in a tile part header and expects a SOT marker */\r
+       J3D_STATE_TPHSOT = 0x0008, \r
+       /**< the decoding process is in a tile part header */\r
+       J3D_STATE_TPH    = 0x0010, \r
+       /**< the EOC marker has just been read */\r
+       J3D_STATE_MT     = 0x0020, \r
+       /**< the decoding process must not expect a EOC marker because the codestream is truncated */\r
+       J3D_STATE_NEOC   = 0x0040  \r
+} J3D_STATUS;\r
+\r
+\r
+\r
+/**\r
+Arbitrary transformation kernel\r
+*/\r
+typedef struct opj_atk {\r
+/** index of wavelet kernel */\r
+       int index;\r
+/** Numerical type of scaling factor and lifting step parameters */\r
+       int coeff_typ;          \r
+/** Wavelet filter category */\r
+       int filt_cat;           \r
+/** Wavelet transformation type (REV/IRR) */\r
+       int wt_typ;                     \r
+/** Initial odd/even subsequence */\r
+       int minit;                      \r
+/** Boundary extension method (constant CON / whole-sample symmetric WS) */\r
+       int exten;                      \r
+/** Scaling factor. Only for wt_typ=IRR */\r
+       double Katk;                    \r
+/** Number of lifting steps */\r
+       int Natk;                       \r
+/** Offset for lifting step s. Only for filt_cat=ARB */\r
+       int Oatk[256];          \r
+/** Base 2 scaling exponent for lifting step s. Only for wt_typ=REV */\r
+       int Eatk[256];          \r
+/** Additive residue for lifting step s. Only for wt_typ=REV */\r
+       int Batk[256];          \r
+/** Number of lifting coefficients signaled for lifting step s  */\r
+       int LCatk[256]; \r
+/** Lifting coefficient k for lifting step s */\r
+       double Aatk[256][256];  \r
+} opj_atk_t;\r
+\r
+\r
+/**\r
+Quantization stepsize\r
+*/\r
+typedef struct opj_stepsize {\r
+/** exponent */\r
+       int expn;       \r
+/** mantissa */\r
+       int mant;       \r
+} opj_stepsize_t;\r
+\r
+/**\r
+Tile-component coding parameters\r
+*/\r
+typedef struct opj_tccp {\r
+       /** coding style */\r
+       int csty;                                                       \r
+       /** number of resolutions of x, y and z-axis */\r
+       int numresolution[3];   \r
+       /** code-blocks width height & depth*/\r
+       int cblk[3];                    \r
+       /** code-block coding style */\r
+       int cblksty;                    \r
+       /** 0: no ATK (only 9-7 or 5-3) 1: ATK defined WT*/\r
+       int atk_wt[3];                          \r
+       /** Arbitrary transformation kernel (15444-2)*/\r
+       opj_atk_t *atk;                 \r
+       /** DWT identifier for x, y and z-axis (0:WT9-7 1:WT5-3 >1:WT-atk->index) */\r
+       int dwtid[3];\r
+       /** reversible/irreversible wavelet transfomation (0:irrev 1:reversible)*/      \r
+       int reversible;                 \r
+       /** quantisation style */\r
+       int qntsty;                             \r
+       /** stepsizes used for quantization */\r
+       opj_stepsize_t stepsizes[J3D_MAXBANDS]; \r
+       /** number of guard bits. Table A28 de 15444-1*/\r
+       int numgbits;                   \r
+       /** Region Of Interest shift */\r
+       int roishift;                   \r
+       /** precinct width heigth & depth*/\r
+       int prctsiz[3][J3D_MAXRLVLS];           \r
+} opj_tccp_t;\r
+\r
+/**\r
+Tile coding parameters : coding/decoding parameters common to all tiles \r
+(information like COD, COC in main header)\r
+*/\r
+typedef struct opj_tcp {\r
+/** 1 : first part-tile of a tile */\r
+       int first;                              \r
+       /** coding style */\r
+       int csty;                               \r
+       /** progression order */\r
+       OPJ_PROG_ORDER prg;             \r
+       /** number of layers */\r
+       int numlayers;                  \r
+       /** multi-component transform identifier */\r
+       int mct;                                \r
+       /** rates of layers */\r
+       float rates[100];                       \r
+       /** number of progression order changes */\r
+       int numpocs;                    \r
+       /** indicates if a POC marker has been used O:NO, 1:YES */\r
+       int POC;                                \r
+       /** progression order changes */\r
+       opj_poc_t pocs[J3D_MAXRLVLS - 1];\r
+       /** add fixed_quality */\r
+       float distoratio[100];\r
+       /** tile-component coding parameters */\r
+       opj_tccp_t *tccps;              \r
+/** packet header store there for futur use in t2_decode_packet */\r
+       unsigned char *ppt_data;                \r
+       /** pointer remaining on the first byte of the first header if ppt is used */\r
+       unsigned char *ppt_data_first;  \r
+       /** If ppt == 1 --> there was a PPT marker for the present tile */\r
+       int ppt;                \r
+       /** used in case of multiple marker PPT (number of info already stored) */\r
+       int ppt_store;  \r
+       int ppt_len;    \r
+} opj_tcp_t;\r
+\r
+/**\r
+Coding parameters\r
+*/\r
+typedef struct opj_cp {\r
+/** transform format 0: 2DWT, 1: 2D1P, 2: 3DWT, 3: 3RLS */\r
+       OPJ_TRANSFORM transform_format;         \r
+       /** entropy coding format 0: 2EB, 1: 3EB, 2: 2GR, 3: 3GR, 4: GRI*/\r
+       OPJ_ENTROPY_CODING encoding_format;     \r
+       /** allocation by rate/distortion */\r
+       int disto_alloc;        \r
+       /** allocation by fixed layer */\r
+       int fixed_alloc;        \r
+       /** add fixed_quality */\r
+       int fixed_quality;      \r
+       /** Rsiz: capabilities */\r
+       int rsiz;                       \r
+       /** if != 0, then original dimension divided by 2^(reduce); if == 0 or not used, volume is decoded to the full resolution */\r
+       int reduce[3];          \r
+       /** if != 0, then only the first "layer" layers are decoded; if == 0 or not used, all the quality layers are decoded */\r
+       int layer;                      \r
+       /** 0 = no index || 1 = index */\r
+       int index_on;           \r
+       /** Big-Endian/Little-endian order */\r
+       int bigendian;\r
+       /** XTOsiz */\r
+       int tx0;        \r
+       /** YTOsiz */\r
+       int ty0;                \r
+       /** ZTOsiz */\r
+       int tz0;        \r
+       /** XTsiz */\r
+       int tdx;        \r
+       /** YTsiz */\r
+       int tdy;        \r
+       /** ZTsiz */\r
+       int tdz;        \r
+       /** comment for coding */\r
+       char *comment;          \r
+       /** number of tiles in width, heigth and depth */\r
+       int tw;         \r
+       int th;\r
+       int tl;\r
+       /** ID number of the tiles present in the codestream */\r
+       int *tileno;    \r
+       /** size of the vector tileno */\r
+       int tileno_size;\r
+       /** tile coding parameters */\r
+       opj_tcp_t *tcps;\r
+       /** fixed layer */\r
+       int *matrice;           \r
+\r
+       /** packet header store there for futur use in t2_decode_packet */\r
+       unsigned char *ppm_data;                \r
+       /** pointer remaining on the first byte of the first header if ppm is used */\r
+       unsigned char *ppm_data_first;  \r
+       /** if ppm == 1 --> there was a PPM marker for the present tile */\r
+       int ppm;                        \r
+       /** use in case of multiple marker PPM (number of info already store) */\r
+       int ppm_store;          \r
+       /** use in case of multiple marker PPM (case on non-finished previous info) */\r
+       int ppm_previous;       \r
+       int ppm_len;            \r
+} opj_cp_t;\r
+\r
+/**\r
+Information concerning a packet inside tile\r
+*/\r
+typedef struct opj_packet_info {\r
+       /** start position */\r
+       int start_pos;  \r
+       /** end position */\r
+       int end_pos;    \r
+       /** distorsion introduced */\r
+       double disto;   \r
+} opj_packet_info_t;\r
+\r
+/**\r
+Index structure : information regarding tiles inside volume\r
+*/\r
+typedef struct opj_tile_info {\r
+       /** value of thresh for each layer by tile cfr. Marcela   */\r
+       double *thresh;         \r
+       /** number of tile */\r
+       int num_tile;           \r
+       /** start position */\r
+       int start_pos;          \r
+       /** end position of the header */\r
+       int end_header;         \r
+       /** end position */\r
+       int end_pos;            \r
+       /** precinct number for each resolution level (width, heigth and depth) */\r
+       int prctno[3][J3D_MAXRLVLS];    \r
+       /** precinct size (in power of 2), in X for each resolution level */\r
+       int prctsiz[3][J3D_MAXRLVLS];   \r
+       /** information concerning packets inside tile */\r
+       opj_packet_info_t *packet;              \r
+       \r
+       /** add fixed_quality */\r
+       int nbpix;                      \r
+       /** add fixed_quality */\r
+       double distotile;       \r
+} opj_tile_info_t;\r
+\r
+/**\r
+Index structure\r
+*/\r
+typedef struct opj_volume_info {\r
+       \r
+       /** transform format 0: 2DWT, 1: 2D1P, 2: 3DWT, 3: 3RLS */\r
+       OPJ_TRANSFORM transform_format;         \r
+       /** output file format 0: 2EB, 1: 3EB, 2: 2GR, 3: 3GR, 4: GRI*/\r
+       OPJ_ENTROPY_CODING encoding_format;     /** 0 = no index || 1 = index */\r
+       int index_on;   \r
+       /** 0 = wt 9-7 || 1 = wt 5-3 || >=2 wt atk defined */\r
+       int dwtid[3];   \r
+       /** maximum distortion reduction on the whole volume (add for Marcela) */\r
+       double D_max;   \r
+       /** packet number */\r
+       int num;                \r
+       /** writing the packet in the index with t2_encode_packets */\r
+       int index_write;        \r
+       /** volume width, height and depth */\r
+       int volume_w;   \r
+       int volume_h;\r
+       int volume_l;\r
+       /** progression order */\r
+       OPJ_PROG_ORDER prog;    \r
+       /** tile size in x, y and z */\r
+       int tile_x;             \r
+       int tile_y;\r
+       int tile_z;\r
+       /** tile origin in x, y and z */\r
+       int tile_Ox;    \r
+       int tile_Oy;\r
+       int tile_Oz;\r
+       /** number of tiles in X, Y and Z */\r
+       int tw;                 \r
+       int th;\r
+       int tl;\r
+       /** component numbers */\r
+       int comp;                               \r
+       /** number of layer */\r
+       int layer;                              \r
+       /** number of decomposition in X, Y and Z*/\r
+       int decomposition[3];   \r
+       /** DC offset (15444-2) */\r
+       int dcoffset;   \r
+       /** main header position */\r
+       int main_head_end;              \r
+       /** codestream's size */\r
+       int codestream_size;    \r
+       /** information regarding tiles inside volume */\r
+       opj_tile_info_t *tile;  \r
+} opj_volume_info_t;\r
+\r
+/**\r
+JPEG-2000 codestream reader/writer\r
+*/\r
+typedef struct opj_j3d {\r
+       /** codec context */\r
+       opj_common_ptr cinfo;   \r
+       /** locate in which part of the codestream the decoder is (main header, tile header, end) */\r
+       int state;                              \r
+       /** number of the tile curently concern by coding/decoding */\r
+       int curtileno;                  \r
+       /** locate the position of the end of the tile in the codestream, used to detect a truncated codestream (in j3d_read_sod)       */\r
+       unsigned char *eot;     \r
+       /**     locate the start position of the SOT marker of the current coded tile:  */\r
+       int sot_start;          \r
+       /*  after encoding the tile, a jump (in j3d_write_sod) is done to the SOT marker to store the value of its length. */\r
+       int sod_start;          \r
+       /**     as the J3D-file is written in several parts during encoding, it enables to make the right correction in position return by cio_tell     */\r
+       int pos_correction;     \r
+       /** array used to store the data of each tile */\r
+       unsigned char **tile_data;      \r
+       /** array used to store the length of each tile */\r
+       int *tile_len;                          \r
+\r
+       /** decompression only : store decoding parameters common to all tiles */\r
+       opj_tcp_t *default_tcp;         \r
+       /** pointer to the encoded / decoded volume */\r
+       opj_volume_t *volume;           \r
+       /** pointer to the coding parameters */\r
+       opj_cp_t *cp;                           \r
+       /** helper used to write the index file */\r
+       opj_volume_info_t *volume_info; \r
+       /** pointer to the byte i/o stream */\r
+    opj_cio_t *cio;                                            \r
+} opj_j3d_t;\r
+\r
+/** @name Funciones generales */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Creates a J3D decompression structure\r
+@param cinfo Codec context info\r
+@return Returns a handle to a J3D decompressor if successful, returns NULL otherwise\r
+*/\r
+opj_j3d_t* j3d_create_decompress(opj_common_ptr cinfo);\r
+/**\r
+Destroy a J3D decompressor handle\r
+@param j3d J3D decompressor handle to destroy\r
+*/\r
+void j3d_destroy_decompress(opj_j3d_t *j3d);\r
+/**\r
+Setup the decoder decoding parameters using user parameters.\r
+Decoding parameters are returned in j3d->cp. \r
+@param j3d J3D decompressor handle\r
+@param parameters decompression parameters\r
+*/\r
+void j3d_setup_decoder(opj_j3d_t *j3d, opj_dparameters_t *parameters);\r
+/**\r
+Decode an volume from a JPEG-2000 codestream\r
+@param j3d J3D decompressor handle\r
+@param cio Input buffer stream\r
+@return Returns a decoded volume if successful, returns NULL otherwise\r
+*/\r
+opj_volume_t* j3d_decode(opj_j3d_t *j3d, opj_cio_t *cio);\r
+/**\r
+Decode an volume form a JPT-stream (JPEG 2000, JPIP)\r
+@param j3d J3D decompressor handle\r
+@param cio Input buffer stream\r
+@return Returns a decoded volume if successful, returns NULL otherwise\r
+*/\r
+opj_volume_t* j3d_decode_jpt_stream(opj_j3d_t *j3d, opj_cio_t *cio);\r
+/**\r
+Creates a J3D compression structure\r
+@param cinfo Codec context info\r
+@return Returns a handle to a J3D compressor if successful, returns NULL otherwise\r
+*/\r
+opj_j3d_t* j3d_create_compress(opj_common_ptr cinfo);\r
+/**\r
+Destroy a J3D compressor handle\r
+@param j3d J3D compressor handle to destroy\r
+*/\r
+void j3d_destroy_compress(opj_j3d_t *j3d);\r
+/**\r
+Setup the encoder parameters using the current volume and using user parameters. \r
+Coding parameters are returned in j3d->cp. \r
+@param j3d J3D compressor handle\r
+@param parameters compression parameters\r
+@param volume input filled volume\r
+*/\r
+void j3d_setup_encoder(opj_j3d_t *j3d, opj_cparameters_t *parameters, opj_volume_t *volume);\r
+/**\r
+Encode an volume into a JPEG-2000 codestream\r
+@param j3d J3D compressor handle\r
+@param cio Output buffer stream\r
+@param volume Volume to encode\r
+@param index Name of the index file if required, NULL otherwise\r
+@return Returns true if successful, returns false otherwise\r
+*/\r
+bool j3d_encode(opj_j3d_t *j3d, opj_cio_t *cio, opj_volume_t *volume, char *index);\r
+/* ----------------------------------------------------------------------- */\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* __J3D_H */\r
diff --git a/src/lib/openjp3d/jp3d_lib.c b/src/lib/openjp3d/jp3d_lib.c
new file mode 100755 (executable)
index 0000000..4445e85
--- /dev/null
@@ -0,0 +1,76 @@
+/*\r
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team\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
+#else\r
+#include <sys/time.h>\r
+#include <sys/resource.h>\r
+#include <sys/times.h>\r
+#endif /* _WIN32 */\r
+#include "opj_includes.h"\r
+\r
+double opj_clock() {\r
+#ifdef _WIN32\r
+       /* WIN32: use QueryPerformance (very accurate) */\r
+    LARGE_INTEGER freq , t ;\r
+    /* freq is the clock speed of the CPU */\r
+    QueryPerformanceFrequency(&freq) ;\r
+       /* cout << "freq = " << ((double) freq.QuadPart) << endl; */\r
+    /* t is the high resolution performance counter (see MSDN) */\r
+    QueryPerformanceCounter ( & t ) ;\r
+    return ( t.QuadPart /(double) freq.QuadPart ) ;\r
+#else\r
+       /* Unix or Linux: use resource usage */\r
+    struct rusage t;\r
+    double procTime;\r
+    /* (1) Get the rusage data structure at this moment (man getrusage) */\r
+    getrusage(0,&t);\r
+    /* (2) What is the elapsed time ? - CPU time = User time + System time */\r
+       /* (2a) Get the seconds */\r
+    procTime = t.ru_utime.tv_sec + t.ru_stime.tv_sec;\r
+    /* (2b) More precisely! Get the microseconds part ! */\r
+    return ( procTime + (t.ru_utime.tv_usec + t.ru_stime.tv_usec) * 1e-6 ) ;\r
+#endif /* _WIN32 */\r
+}\r
+\r
+void* opj_malloc( size_t size ) {\r
+       void *memblock = malloc(size);\r
+       if(memblock) {\r
+               memset(memblock, 0, size);\r
+       }\r
+       return memblock;\r
+}\r
+\r
+void* opj_realloc( void *memblock, size_t size ) {\r
+       return realloc(memblock, size);\r
+}\r
+\r
+void opj_free( void *memblock ) {\r
+       free(memblock);\r
+}\r
+\r
+\r
diff --git a/src/lib/openjp3d/jp3d_lib.h b/src/lib/openjp3d/jp3d_lib.h
new file mode 100755 (executable)
index 0000000..a2fb05b
--- /dev/null
@@ -0,0 +1,75 @@
+/*\r
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team\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
+#ifndef __J3D_LIB_H\r
+#define __J3D_LIB_H\r
+/**\r
+@file jp3d_lib.h\r
+@brief Internal functions\r
+\r
+The functions in JP3D_LIB.C are internal utilities mainly used for memory management.\r
+*/\r
+\r
+/** @defgroup MISC MISC - Miscellaneous internal functions */\r
+/*@{*/\r
+\r
+/** @name Funciones generales */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+\r
+/**\r
+Difference in successive opj_clock() calls tells you the elapsed time\r
+@return Returns time in seconds\r
+*/\r
+double opj_clock();\r
+\r
+/**\r
+Allocate a memory block with elements initialized to 0\r
+@param size Bytes to allocate\r
+@return Returns a void pointer to the allocated space, or NULL if there is insufficient memory available\r
+*/\r
+void* opj_malloc( size_t size );\r
+\r
+/**\r
+Reallocate memory blocks.\r
+@param memblock Pointer to previously allocated memory block\r
+@param size New size in bytes\r
+@return Returns a void pointer to the reallocated (and possibly moved) memory block\r
+*/\r
+void* opj_realloc( void *memblock, size_t size );\r
+\r
+/**\r
+Deallocates or frees a memory block.\r
+@param memblock Previously allocated memory block to be freed\r
+*/\r
+void opj_free( void *memblock );\r
+\r
+/* ----------------------------------------------------------------------- */\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* __J3D_LIB_H */\r
+\r
diff --git a/src/lib/openjp3d/mct.c b/src/lib/openjp3d/mct.c
new file mode 100755 (executable)
index 0000000..e915e39
--- /dev/null
@@ -0,0 +1,131 @@
+/*\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
+ * 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 "opj_includes.h"\r
+\r
+/* <summary> */\r
+/* This table contains the norms of the basis function of the reversible MCT. */\r
+/* </summary> */\r
+static const double mct_norms[3] = { 1.732, .8292, .8292 };\r
+\r
+/* <summary> */\r
+/* This table contains the norms of the basis function of the irreversible MCT. */\r
+/* </summary> */\r
+static const double mct_norms_real[3] = { 1.732, 1.805, 1.573 };\r
+\r
+/* <summary> */\r
+/* Foward reversible MCT. */\r
+/* </summary> */\r
+void mct_encode(int *c0, int *c1, int *c2, int n) {\r
+       int i;\r
+       for (i = 0; i < n; i++) {\r
+               int r, g, b, y, u, v;\r
+               r = c0[i];\r
+               g = c1[i];\r
+               b = c2[i];\r
+               y = (r + (g << 1) + b) >> 2;\r
+               u = b - g;\r
+               v = r - g;\r
+               c0[i] = y;\r
+               c1[i] = u;\r
+               c2[i] = v;\r
+       }\r
+}\r
+\r
+/* <summary> */\r
+/* Inverse reversible MCT. */\r
+/* </summary> */\r
+void mct_decode(int *c0, int *c1, int *c2, int n) {\r
+       int i;\r
+       for (i = 0; i < n; i++) {\r
+               int y, u, v, r, g, b;\r
+               y = c0[i];\r
+               u = c1[i];\r
+               v = c2[i];\r
+               g = y - ((u + v) >> 2);\r
+               r = v + g;\r
+               b = u + g;\r
+               c0[i] = r;\r
+               c1[i] = g;\r
+               c2[i] = b;\r
+       }\r
+}\r
+\r
+/* <summary> */\r
+/* Get norm of basis function of reversible MCT. */\r
+/* </summary> */\r
+double mct_getnorm(int compno) {\r
+       return mct_norms[compno];\r
+}\r
+\r
+/* <summary> */\r
+/* Foward irreversible MCT. */\r
+/* </summary> */\r
+void mct_encode_real(int *c0, int *c1, int *c2, int n) {\r
+       int i;\r
+       for (i = 0; i < n; i++) {\r
+               int r, g, b, y, u, v;\r
+               r = c0[i];\r
+               g = c1[i];\r
+               b = c2[i];\r
+               y = fix_mul(r, 2449) + fix_mul(g, 4809) + fix_mul(b, 934);\r
+               u = -fix_mul(r, 1382) - fix_mul(g, 2714) + fix_mul(b, 4096);\r
+               v = fix_mul(r, 4096) - fix_mul(g, 3430) - fix_mul(b, 666);\r
+               c0[i] = y;\r
+               c1[i] = u;\r
+               c2[i] = v;\r
+       }\r
+}\r
+\r
+/* <summary> */\r
+/* Inverse irreversible MCT. */\r
+/* </summary> */\r
+void mct_decode_real(int *c0, int *c1, int *c2, int n) {\r
+       int i;\r
+       for (i = 0; i < n; i++) {\r
+               int y, u, v, r, g, b;\r
+               y = c0[i];\r
+               u = c1[i];\r
+               v = c2[i];\r
+               r = y + fix_mul(v, 11485);\r
+               g = y - fix_mul(u, 2819) - fix_mul(v, 5850);\r
+               b = y + fix_mul(u, 14516);\r
+               c0[i] = r;\r
+               c1[i] = g;\r
+               c2[i] = b;\r
+       }\r
+}\r
+\r
+/* <summary> */\r
+/* Get norm of basis function of irreversible MCT. */\r
+/* </summary> */\r
+double mct_getnorm_real(int compno) {\r
+       return mct_norms_real[compno];\r
+}\r
diff --git a/src/lib/openjp3d/mct.h b/src/lib/openjp3d/mct.h
new file mode 100755 (executable)
index 0000000..0b8edb7
--- /dev/null
@@ -0,0 +1,97 @@
+/*\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
+ * 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 __MCT_H\r
+#define __MCT_H\r
+/**\r
+@file mct.h\r
+@brief Implementation of a multi-component transforms (MCT)\r
+\r
+The functions in MCT.C have for goal to realize reversible and irreversible multicomponent\r
+transform. The functions in MCT.C are used by some function in TCD.C.\r
+*/\r
+\r
+/** @defgroup MCT MCT - Implementation of a multi-component transform */\r
+/*@{*/\r
+\r
+/** @name Funciones generales */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Apply a reversible multi-component transform to an image\r
+@param c0 Samples for red component\r
+@param c1 Samples for green component\r
+@param c2 Samples blue component\r
+@param n Number of samples for each component\r
+*/\r
+void mct_encode(int *c0, int *c1, int *c2, int n);\r
+/**\r
+Apply a reversible multi-component inverse transform to an image\r
+@param c0 Samples for luminance component\r
+@param c1 Samples for red chrominance component\r
+@param c2 Samples for blue chrominance component\r
+@param n Number of samples for each component\r
+*/\r
+void mct_decode(int *c0, int *c1, int *c2, int n);\r
+/**\r
+Get norm of the basis function used for the reversible multi-component transform\r
+@param compno Number of the component (0->Y, 1->U, 2->V)\r
+@return \r
+*/\r
+double mct_getnorm(int compno);\r
+\r
+/**\r
+Apply an irreversible multi-component transform to an image\r
+@param c0 Samples for red component\r
+@param c1 Samples for green component\r
+@param c2 Samples blue component\r
+@param n Number of samples for each component\r
+*/\r
+void mct_encode_real(int *c0, int *c1, int *c2, int n);\r
+/**\r
+Apply an irreversible multi-component inverse transform to an image\r
+@param c0 Samples for luminance component\r
+@param c1 Samples for red chrominance component\r
+@param c2 Samples for blue chrominance component\r
+@param n Number of samples for each component\r
+*/\r
+void mct_decode_real(int *c0, int *c1, int *c2, int n);\r
+/**\r
+Get norm of the basis function used for the irreversible multi-component transform\r
+@param compno Number of the component (0->Y, 1->U, 2->V)\r
+@return \r
+*/\r
+double mct_getnorm_real(int compno);\r
+/* ----------------------------------------------------------------------- */\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* __MCT_H */\r
diff --git a/src/lib/openjp3d/mqc.c b/src/lib/openjp3d/mqc.c
new file mode 100755 (executable)
index 0000000..12ac90d
--- /dev/null
@@ -0,0 +1,548 @@
+/*\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
+ * 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 "opj_includes.h"\r
+\r
+/** @defgroup MQC MQC - Implementation of an MQ-Coder */\r
+/*@{*/\r
+\r
+/** @name Local static functions */\r
+/*@{*/\r
+\r
+/**\r
+Output a byte, doing bit-stuffing if necessary.\r
+After a 0xff byte, the next byte must be smaller than 0x90.\r
+@param mqc MQC handle\r
+*/\r
+static void mqc_byteout(opj_mqc_t *mqc);\r
+/**\r
+Renormalize mqc->a and mqc->c while encoding, so that mqc->a stays between 0x8000 and 0x10000\r
+@param mqc MQC handle\r
+*/\r
+static void mqc_renorme(opj_mqc_t *mqc);\r
+/**\r
+Encode the most probable symbol\r
+@param mqc MQC handle\r
+*/\r
+static void mqc_codemps(opj_mqc_t *mqc);\r
+/**\r
+Encode the most least symbol\r
+@param mqc MQC handle\r
+*/\r
+static void mqc_codelps(opj_mqc_t *mqc);\r
+/**\r
+Fill mqc->c with 1's for flushing\r
+@param mqc MQC handle\r
+*/\r
+static void mqc_setbits(opj_mqc_t *mqc);\r
+/**\r
+Exchange MPS with LPS\r
+@param mqc MQC handle\r
+@return \r
+*/\r
+static int mqc_mpsexchange(opj_mqc_t *mqc);\r
+/**\r
+Exchange LPS with MPS\r
+@param mqc MQC handle\r
+@return \r
+*/\r
+static int mqc_lpsexchange(opj_mqc_t *mqc);\r
+/**\r
+Input a byte\r
+@param mqc MQC handle\r
+*/\r
+static void mqc_bytein(opj_mqc_t *mqc);\r
+/**\r
+Renormalize mqc->a and mqc->c while decoding\r
+@param mqc MQC handle\r
+*/\r
+static void mqc_renormd(opj_mqc_t *mqc);\r
+\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+/* <summary> */\r
+/* This array defines all the possible states for a context. */\r
+/* </summary> */\r
+static opj_mqc_state_t mqc_states[47 * 2] = {\r
+       {0x5601, 0, &mqc_states[2], &mqc_states[3]},\r
+       {0x5601, 1, &mqc_states[3], &mqc_states[2]},\r
+       {0x3401, 0, &mqc_states[4], &mqc_states[12]},\r
+       {0x3401, 1, &mqc_states[5], &mqc_states[13]},\r
+       {0x1801, 0, &mqc_states[6], &mqc_states[18]},\r
+       {0x1801, 1, &mqc_states[7], &mqc_states[19]},\r
+       {0x0ac1, 0, &mqc_states[8], &mqc_states[24]},\r
+       {0x0ac1, 1, &mqc_states[9], &mqc_states[25]},\r
+       {0x0521, 0, &mqc_states[10], &mqc_states[58]},\r
+       {0x0521, 1, &mqc_states[11], &mqc_states[59]},\r
+       {0x0221, 0, &mqc_states[76], &mqc_states[66]},\r
+       {0x0221, 1, &mqc_states[77], &mqc_states[67]},\r
+       {0x5601, 0, &mqc_states[14], &mqc_states[13]},\r
+       {0x5601, 1, &mqc_states[15], &mqc_states[12]},\r
+       {0x5401, 0, &mqc_states[16], &mqc_states[28]},\r
+       {0x5401, 1, &mqc_states[17], &mqc_states[29]},\r
+       {0x4801, 0, &mqc_states[18], &mqc_states[28]},\r
+       {0x4801, 1, &mqc_states[19], &mqc_states[29]},\r
+       {0x3801, 0, &mqc_states[20], &mqc_states[28]},\r
+       {0x3801, 1, &mqc_states[21], &mqc_states[29]},\r
+       {0x3001, 0, &mqc_states[22], &mqc_states[34]},\r
+       {0x3001, 1, &mqc_states[23], &mqc_states[35]},\r
+       {0x2401, 0, &mqc_states[24], &mqc_states[36]},\r
+       {0x2401, 1, &mqc_states[25], &mqc_states[37]},\r
+       {0x1c01, 0, &mqc_states[26], &mqc_states[40]},\r
+       {0x1c01, 1, &mqc_states[27], &mqc_states[41]},\r
+       {0x1601, 0, &mqc_states[58], &mqc_states[42]},\r
+       {0x1601, 1, &mqc_states[59], &mqc_states[43]},\r
+       {0x5601, 0, &mqc_states[30], &mqc_states[29]},\r
+       {0x5601, 1, &mqc_states[31], &mqc_states[28]},\r
+       {0x5401, 0, &mqc_states[32], &mqc_states[28]},\r
+       {0x5401, 1, &mqc_states[33], &mqc_states[29]},\r
+       {0x5101, 0, &mqc_states[34], &mqc_states[30]},\r
+       {0x5101, 1, &mqc_states[35], &mqc_states[31]},\r
+       {0x4801, 0, &mqc_states[36], &mqc_states[32]},\r
+       {0x4801, 1, &mqc_states[37], &mqc_states[33]},\r
+       {0x3801, 0, &mqc_states[38], &mqc_states[34]},\r
+       {0x3801, 1, &mqc_states[39], &mqc_states[35]},\r
+       {0x3401, 0, &mqc_states[40], &mqc_states[36]},\r
+       {0x3401, 1, &mqc_states[41], &mqc_states[37]},\r
+       {0x3001, 0, &mqc_states[42], &mqc_states[38]},\r
+       {0x3001, 1, &mqc_states[43], &mqc_states[39]},\r
+       {0x2801, 0, &mqc_states[44], &mqc_states[38]},\r
+       {0x2801, 1, &mqc_states[45], &mqc_states[39]},\r
+       {0x2401, 0, &mqc_states[46], &mqc_states[40]},\r
+       {0x2401, 1, &mqc_states[47], &mqc_states[41]},\r
+       {0x2201, 0, &mqc_states[48], &mqc_states[42]},\r
+       {0x2201, 1, &mqc_states[49], &mqc_states[43]},\r
+       {0x1c01, 0, &mqc_states[50], &mqc_states[44]},\r
+       {0x1c01, 1, &mqc_states[51], &mqc_states[45]},\r
+       {0x1801, 0, &mqc_states[52], &mqc_states[46]},\r
+       {0x1801, 1, &mqc_states[53], &mqc_states[47]},\r
+       {0x1601, 0, &mqc_states[54], &mqc_states[48]},\r
+       {0x1601, 1, &mqc_states[55], &mqc_states[49]},\r
+       {0x1401, 0, &mqc_states[56], &mqc_states[50]},\r
+       {0x1401, 1, &mqc_states[57], &mqc_states[51]},\r
+       {0x1201, 0, &mqc_states[58], &mqc_states[52]},\r
+       {0x1201, 1, &mqc_states[59], &mqc_states[53]},\r
+       {0x1101, 0, &mqc_states[60], &mqc_states[54]},\r
+       {0x1101, 1, &mqc_states[61], &mqc_states[55]},\r
+       {0x0ac1, 0, &mqc_states[62], &mqc_states[56]},\r
+       {0x0ac1, 1, &mqc_states[63], &mqc_states[57]},\r
+       {0x09c1, 0, &mqc_states[64], &mqc_states[58]},\r
+       {0x09c1, 1, &mqc_states[65], &mqc_states[59]},\r
+       {0x08a1, 0, &mqc_states[66], &mqc_states[60]},\r
+       {0x08a1, 1, &mqc_states[67], &mqc_states[61]},\r
+       {0x0521, 0, &mqc_states[68], &mqc_states[62]},\r
+       {0x0521, 1, &mqc_states[69], &mqc_states[63]},\r
+       {0x0441, 0, &mqc_states[70], &mqc_states[64]},\r
+       {0x0441, 1, &mqc_states[71], &mqc_states[65]},\r
+       {0x02a1, 0, &mqc_states[72], &mqc_states[66]},\r
+       {0x02a1, 1, &mqc_states[73], &mqc_states[67]},\r
+       {0x0221, 0, &mqc_states[74], &mqc_states[68]},\r
+       {0x0221, 1, &mqc_states[75], &mqc_states[69]},\r
+       {0x0141, 0, &mqc_states[76], &mqc_states[70]},\r
+       {0x0141, 1, &mqc_states[77], &mqc_states[71]},\r
+       {0x0111, 0, &mqc_states[78], &mqc_states[72]},\r
+       {0x0111, 1, &mqc_states[79], &mqc_states[73]},\r
+       {0x0085, 0, &mqc_states[80], &mqc_states[74]},\r
+       {0x0085, 1, &mqc_states[81], &mqc_states[75]},\r
+       {0x0049, 0, &mqc_states[82], &mqc_states[76]},\r
+       {0x0049, 1, &mqc_states[83], &mqc_states[77]},\r
+       {0x0025, 0, &mqc_states[84], &mqc_states[78]},\r
+       {0x0025, 1, &mqc_states[85], &mqc_states[79]},\r
+       {0x0015, 0, &mqc_states[86], &mqc_states[80]},\r
+       {0x0015, 1, &mqc_states[87], &mqc_states[81]},\r
+       {0x0009, 0, &mqc_states[88], &mqc_states[82]},\r
+       {0x0009, 1, &mqc_states[89], &mqc_states[83]},\r
+       {0x0005, 0, &mqc_states[90], &mqc_states[84]},\r
+       {0x0005, 1, &mqc_states[91], &mqc_states[85]},\r
+       {0x0001, 0, &mqc_states[90], &mqc_states[86]},\r
+       {0x0001, 1, &mqc_states[91], &mqc_states[87]},\r
+       {0x5601, 0, &mqc_states[92], &mqc_states[92]},\r
+       {0x5601, 1, &mqc_states[93], &mqc_states[93]},\r
+};\r
+\r
+/* \r
+==========================================================\r
+   local functions\r
+==========================================================\r
+*/\r
+\r
+static void mqc_byteout(opj_mqc_t *mqc) {\r
+       if (*mqc->bp == 0xff) {\r
+               mqc->bp++;\r
+               *mqc->bp = mqc->c >> 20;\r
+               mqc->c &= 0xfffff;\r
+               mqc->ct = 7;\r
+       } else {\r
+               if ((mqc->c & 0x8000000) == 0) {        /* ((mqc->c&0x8000000)==0) CHANGE */\r
+                       mqc->bp++;\r
+                       *mqc->bp = mqc->c >> 19;\r
+                       mqc->c &= 0x7ffff;\r
+                       mqc->ct = 8;\r
+               } else {\r
+                       (*mqc->bp)++;\r
+                       if (*mqc->bp == 0xff) {\r
+                               mqc->c &= 0x7ffffff;\r
+                               mqc->bp++;\r
+                               *mqc->bp = mqc->c >> 20;\r
+                               mqc->c &= 0xfffff;\r
+                               mqc->ct = 7;\r
+                       } else {\r
+                               mqc->bp++;\r
+                               *mqc->bp = mqc->c >> 19;\r
+                               mqc->c &= 0x7ffff;\r
+                               mqc->ct = 8;\r
+                       }\r
+               }\r
+       }\r
+}\r
+\r
+static void mqc_renorme(opj_mqc_t *mqc) {\r
+       do {\r
+               mqc->a <<= 1;\r
+               mqc->c <<= 1;\r
+               mqc->ct--;\r
+               if (mqc->ct == 0) {\r
+                       mqc_byteout(mqc);\r
+               }\r
+       } while ((mqc->a & 0x8000) == 0);\r
+}\r
+\r
+static void mqc_codemps(opj_mqc_t *mqc) {\r
+       mqc->a -= (*mqc->curctx)->qeval;\r
+       if ((mqc->a & 0x8000) == 0) {\r
+               if (mqc->a < (*mqc->curctx)->qeval) {\r
+                       mqc->a = (*mqc->curctx)->qeval;\r
+               } else {\r
+                       mqc->c += (*mqc->curctx)->qeval;\r
+               }\r
+               *mqc->curctx = (*mqc->curctx)->nmps;\r
+               mqc_renorme(mqc);\r
+       } else {\r
+               mqc->c += (*mqc->curctx)->qeval;\r
+       }\r
+}\r
+\r
+static void mqc_codelps(opj_mqc_t *mqc) {\r
+       mqc->a -= (*mqc->curctx)->qeval;\r
+       if (mqc->a < (*mqc->curctx)->qeval) {\r
+               mqc->c += (*mqc->curctx)->qeval;\r
+       } else {\r
+               mqc->a = (*mqc->curctx)->qeval;\r
+       }\r
+       *mqc->curctx = (*mqc->curctx)->nlps;\r
+       mqc_renorme(mqc);\r
+}\r
+\r
+static void mqc_setbits(opj_mqc_t *mqc) {\r
+       unsigned int tempc = mqc->c + mqc->a;\r
+       mqc->c |= 0xffff;\r
+       if (mqc->c >= tempc) {\r
+               mqc->c -= 0x8000;\r
+       }\r
+}\r
+\r
+static int mqc_mpsexchange(opj_mqc_t *mqc) {\r
+       int d;\r
+       if (mqc->a < (*mqc->curctx)->qeval) {\r
+               d = 1 - (*mqc->curctx)->mps;\r
+               *mqc->curctx = (*mqc->curctx)->nlps;\r
+       } else {\r
+               d = (*mqc->curctx)->mps;\r
+               *mqc->curctx = (*mqc->curctx)->nmps;\r
+       }\r
+       \r
+       return d;\r
+}\r
+\r
+static int mqc_lpsexchange(opj_mqc_t *mqc) {\r
+       int d;\r
+       if (mqc->a < (*mqc->curctx)->qeval) {\r
+               mqc->a = (*mqc->curctx)->qeval;\r
+               d = (*mqc->curctx)->mps;\r
+               *mqc->curctx = (*mqc->curctx)->nmps;\r
+       } else {\r
+               mqc->a = (*mqc->curctx)->qeval;\r
+               d = 1 - (*mqc->curctx)->mps;\r
+               *mqc->curctx = (*mqc->curctx)->nlps;\r
+       }\r
+       \r
+       return d;\r
+}\r
+\r
+static void mqc_bytein(opj_mqc_t *mqc) {\r
+       if (mqc->bp != mqc->end) {\r
+               unsigned int c;\r
+               if (mqc->bp + 1 != mqc->end) {\r
+                       c = *(mqc->bp + 1);\r
+               } else {\r
+                       c = 0xff;\r
+               }\r
+               if (*mqc->bp == 0xff) {\r
+                       if (c > 0x8f) {\r
+                               mqc->c += 0xff00;\r
+                               mqc->ct = 8;\r
+                       } else {\r
+                               mqc->bp++;\r
+                               mqc->c += c << 9;\r
+                               mqc->ct = 7;\r
+                       }\r
+               } else {\r
+                       mqc->bp++;\r
+                       mqc->c += c << 8;\r
+                       mqc->ct = 8;\r
+               }\r
+       } else {\r
+               mqc->c += 0xff00;\r
+               mqc->ct = 8;\r
+       }\r
+}\r
+\r
+static void mqc_renormd(opj_mqc_t *mqc) {\r
+       do {\r
+               if (mqc->ct == 0) {\r
+                       mqc_bytein(mqc);\r
+               }\r
+               mqc->a <<= 1;\r
+               mqc->c <<= 1;\r
+               mqc->ct--;\r
+       } while (mqc->a < 0x8000);\r
+}\r
+\r
+/* \r
+==========================================================\r
+   MQ-Coder interface\r
+==========================================================\r
+*/\r
+\r
+opj_mqc_t* mqc_create() {\r
+       opj_mqc_t *mqc = (opj_mqc_t*)opj_malloc(sizeof(opj_mqc_t));\r
+       return mqc;\r
+}\r
+\r
+void mqc_destroy(opj_mqc_t *mqc) {\r
+       if(mqc) {\r
+               opj_free(mqc);\r
+       }\r
+}\r
+\r
+int mqc_numbytes(opj_mqc_t *mqc) {\r
+       return mqc->bp - mqc->start;\r
+}\r
+\r
+void mqc_init_enc(opj_mqc_t *mqc, unsigned char *bp) {\r
+       mqc_setcurctx(mqc, 0);\r
+       mqc->a = 0x8000;\r
+       mqc->c = 0;\r
+       mqc->bp = bp - 1;\r
+       mqc->ct = 12;\r
+       if (*mqc->bp == 0xff) {\r
+               mqc->ct = 13;\r
+       }\r
+       mqc->start = bp;\r
+}\r
+\r
+void mqc_setcurctx(opj_mqc_t *mqc, int ctxno) {\r
+       mqc->curctx = &mqc->ctxs[ctxno];\r
+}\r
+\r
+void mqc_encode(opj_mqc_t *mqc, int d) {\r
+       if ((*mqc->curctx)->mps == d) {\r
+               mqc_codemps(mqc);\r
+       } else {\r
+               mqc_codelps(mqc);\r
+       }\r
+}\r
+\r
+void mqc_flush(opj_mqc_t *mqc) {\r
+       mqc_setbits(mqc);\r
+       mqc->c <<= mqc->ct;\r
+       mqc_byteout(mqc);\r
+       mqc->c <<= mqc->ct;\r
+       mqc_byteout(mqc);\r
+       \r
+       if (*mqc->bp != 0xff) {\r
+               mqc->bp++;\r
+       }\r
+}\r
+\r
+void mqc_bypass_init_enc(opj_mqc_t *mqc) {\r
+       mqc->c = 0;\r
+       mqc->ct = 8;\r
+       /*if (*mqc->bp == 0xff) {\r
+       mqc->ct = 7;\r
+     } */\r
+}\r
+\r
+void mqc_bypass_enc(opj_mqc_t *mqc, int d) {\r
+       mqc->ct--;\r
+       mqc->c = mqc->c + (d << mqc->ct);\r
+       if (mqc->ct == 0) {\r
+               mqc->bp++;\r
+               *mqc->bp = mqc->c;\r
+               mqc->ct = 8;\r
+               if (*mqc->bp == 0xff) {\r
+                       mqc->ct = 7;\r
+               }\r
+               mqc->c = 0;\r
+       }\r
+}\r
+\r
+int mqc_bypass_flush_enc(opj_mqc_t *mqc) {\r
+       unsigned char bit_padding;\r
+       \r
+       bit_padding = 0;\r
+       \r
+       if (mqc->ct != 0) {\r
+               while (mqc->ct > 0) {\r
+                       mqc->ct--;\r
+                       mqc->c += bit_padding << mqc->ct;\r
+                       bit_padding = (bit_padding + 1) & 0x01;\r
+               }\r
+               mqc->bp++;\r
+               *mqc->bp = mqc->c;\r
+               mqc->ct = 8;\r
+               mqc->c = 0;\r
+       }\r
+       \r
+       return 1;\r
+}\r
+\r
+void mqc_reset_enc(opj_mqc_t *mqc) {\r
+       mqc_resetstates(mqc);\r
+       mqc_setstate(mqc, 18, 0, 46);\r
+       mqc_setstate(mqc, 0, 0, 3);\r
+       mqc_setstate(mqc, 1, 0, 4);\r
+}\r
+\r
+void mqc_reset_enc_3(opj_mqc_t *mqc) {\r
+       mqc_resetstates(mqc);\r
+       mqc_setstate(mqc, T1_3D_CTXNO_UNI, 0, 46);\r
+       mqc_setstate(mqc, T1_3D_CTXNO_AGG, 0, 3);\r
+       mqc_setstate(mqc, T1_3D_CTXNO_ZC, 0, 4);\r
+}\r
+\r
+int mqc_restart_enc(opj_mqc_t *mqc) {\r
+       int correction = 1;\r
+       \r
+       /* <flush part> */\r
+       int n = 27 - 15 - mqc->ct;\r
+       mqc->c <<= mqc->ct;\r
+       while (n > 0) {\r
+               mqc_byteout(mqc);\r
+               n -= mqc->ct;\r
+               mqc->c <<= mqc->ct;\r
+       }\r
+       mqc_byteout(mqc);\r
+       \r
+       return correction;\r
+}\r
+\r
+void mqc_restart_init_enc(opj_mqc_t *mqc) {\r
+       /* <Re-init part> */\r
+       mqc_setcurctx(mqc, 0);\r
+       mqc->a = 0x8000;\r
+       mqc->c = 0;\r
+       mqc->ct = 12;\r
+       mqc->bp--;\r
+       if (*mqc->bp == 0xff) {\r
+               mqc->ct = 13;\r
+       }\r
+}\r
+\r
+void mqc_erterm_enc(opj_mqc_t *mqc) {\r
+       int k = 11 - mqc->ct + 1;\r
+       \r
+       while (k > 0) {\r
+               mqc->c <<= mqc->ct;\r
+               mqc->ct = 0;\r
+               mqc_byteout(mqc);\r
+               k -= mqc->ct;\r
+       }\r
+       \r
+       if (*mqc->bp != 0xff) {\r
+               mqc_byteout(mqc);\r
+       }\r
+}\r
+\r
+void mqc_segmark_enc(opj_mqc_t *mqc) {\r
+       int i;\r
+       mqc_setcurctx(mqc, 18);\r
+       \r
+       for (i = 1; i < 5; i++) {\r
+               mqc_encode(mqc, i % 2);\r
+       }\r
+}\r
+\r
+void mqc_init_dec(opj_mqc_t *mqc, unsigned char *bp, int len) {\r
+       mqc_setcurctx(mqc, 0);\r
+       mqc->start = bp;\r
+       mqc->end = bp + len;\r
+       mqc->bp = bp;\r
+       if (len==0) mqc->c = 0xff << 16;\r
+       else mqc->c = *mqc->bp << 16;\r
+       mqc_bytein(mqc);\r
+       mqc->c <<= 7;\r
+       mqc->ct -= 7;\r
+       mqc->a = 0x8000;\r
+}\r
+\r
+int mqc_decode(opj_mqc_t *mqc) {\r
+       int d;\r
+       mqc->a -= (*mqc->curctx)->qeval;\r
+       if ((mqc->c >> 16) < (*mqc->curctx)->qeval) {\r
+               d = mqc_lpsexchange(mqc);\r
+               mqc_renormd(mqc);\r
+       } else {\r
+               mqc->c -= (*mqc->curctx)->qeval << 16;\r
+               if ((mqc->a & 0x8000) == 0) {\r
+                       d = mqc_mpsexchange(mqc);\r
+                       mqc_renormd(mqc);\r
+               } else {\r
+                       d = (*mqc->curctx)->mps;\r
+               }\r
+       }\r
+\r
+       return d;\r
+}\r
+\r
+void mqc_resetstates(opj_mqc_t *mqc) {\r
+       int i;\r
+       for (i = 0; i < MQC_NUMCTXS; i++) {\r
+               mqc->ctxs[i] = mqc_states;\r
+       }\r
+}\r
+\r
+void mqc_setstate(opj_mqc_t *mqc, int ctxno, int msb, int prob) {\r
+       mqc->ctxs[ctxno] = &mqc_states[msb + (prob << 1)];\r
+}\r
+\r
+\r
diff --git a/src/lib/openjp3d/mqc.h b/src/lib/openjp3d/mqc.h
new file mode 100755 (executable)
index 0000000..9025335
--- /dev/null
@@ -0,0 +1,201 @@
+/*\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
+ * 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 __MQC_H\r
+#define __MQC_H\r
+/**\r
+@file mqc.h\r
+@brief Implementation of an MQ-Coder (MQC)\r
+\r
+The functions in MQC.C have for goal to realize the MQ-coder operations. The functions\r
+in MQC.C are used by some function in T1.C.\r
+*/\r
+\r
+/** @defgroup MQC MQC - Implementation of an MQ-Coder */\r
+/*@{*/\r
+\r
+/**\r
+This struct defines the state of a context.\r
+*/\r
+typedef struct opj_mqc_state {\r
+       /** the probability of the Least Probable Symbol (0.75->0x8000, 1.5->0xffff) */\r
+       unsigned int qeval;\r
+       /** the Most Probable Symbol (0 or 1) */\r
+       int mps;\r
+       /** next state if the next encoded symbol is the MPS */\r
+       struct opj_mqc_state *nmps;\r
+       /** next state if the next encoded symbol is the LPS */\r
+       struct opj_mqc_state *nlps;\r
+} opj_mqc_state_t;\r
+\r
+#define MQC_NUMCTXS 32\r
+\r
+/**\r
+MQ coder\r
+*/\r
+typedef struct opj_mqc {\r
+       unsigned int c;\r
+       unsigned int a;\r
+       unsigned int ct;\r
+       unsigned char *bp;\r
+       unsigned char *start;\r
+       unsigned char *end;\r
+       opj_mqc_state_t *ctxs[MQC_NUMCTXS];\r
+       opj_mqc_state_t **curctx;\r
+} opj_mqc_t;\r
+\r
+/** @name Exported functions */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Create a new MQC handle \r
+@return Returns a new MQC handle if successful, returns NULL otherwise\r
+*/\r
+opj_mqc_t* mqc_create();\r
+/**\r
+Destroy a previously created MQC handle\r
+@param mqc MQC handle to destroy\r
+*/\r
+void mqc_destroy(opj_mqc_t *mqc);\r
+/**\r
+Return the number of bytes written/read since initialisation\r
+@param mqc MQC handle\r
+@return Returns the number of bytes already encoded\r
+*/\r
+int mqc_numbytes(opj_mqc_t *mqc);\r
+/**\r
+Reset the states of all the context of the coder/decoder \r
+(each context is set to a state where 0 and 1 are more or less equiprobable)\r
+@param mqc MQC handle\r
+*/\r
+void mqc_resetstates(opj_mqc_t *mqc);\r
+/**\r
+Set the state of a particular context\r
+@param mqc MQC handle\r
+@param ctxno Number that identifies the context\r
+@param msb The MSB of the new state of the context\r
+@param prob Number that identifies the probability of the symbols for the new state of the context\r
+*/\r
+void mqc_setstate(opj_mqc_t *mqc, int ctxno, int msb, int prob);\r
+/**\r
+Initialize the encoder\r
+@param mqc MQC handle\r
+@param bp Pointer to the start of the buffer where the bytes will be written\r
+*/\r
+void mqc_init_enc(opj_mqc_t *mqc, unsigned char *bp);\r
+/**\r
+Set the current context used for coding/decoding\r
+@param mqc MQC handle\r
+@param ctxno Number that identifies the context\r
+*/\r
+void mqc_setcurctx(opj_mqc_t *mqc, int ctxno);\r
+/**\r
+Encode a symbol using the MQ-coder\r
+@param mqc MQC handle\r
+@param d The symbol to be encoded (0 or 1)\r
+*/\r
+void mqc_encode(opj_mqc_t *mqc, int d);\r
+/**\r
+Flush the encoder, so that all remaining data is written\r
+@param mqc MQC handle\r
+*/\r
+void mqc_flush(opj_mqc_t *mqc);\r
+/**\r
+BYPASS mode switch, initialization operation. \r
+JPEG 2000 p 505. \r
+<h2>Not fully implemented and tested !!</h2>\r
+@param mqc MQC handle\r
+*/\r
+void mqc_bypass_init_enc(opj_mqc_t *mqc);\r
+/**\r
+BYPASS mode switch, coding operation. \r
+JPEG 2000 p 505. \r
+<h2>Not fully implemented and tested !!</h2>\r
+@param mqc MQC handle\r
+@param d The symbol to be encoded (0 or 1)\r
+*/\r
+void mqc_bypass_enc(opj_mqc_t *mqc, int d);\r
+/**\r
+BYPASS mode switch, flush operation\r
+<h2>Not fully implemented and tested !!</h2>\r
+@param mqc MQC handle\r
+@return Returns 1 (always)\r
+*/\r
+int mqc_bypass_flush_enc(opj_mqc_t *mqc);\r
+/**\r
+RESET mode switch\r
+@param mqc MQC handle\r
+*/\r
+void mqc_reset_enc(opj_mqc_t *mqc);\r
+/**\r
+RESET mode switch\r
+@param mqc MQC handle\r
+*/\r
+void mqc_reset_enc_3(opj_mqc_t *mqc);\r
+/**\r
+RESTART mode switch (TERMALL)\r
+@param mqc MQC handle\r
+@return Returns 1 (always)\r
+*/\r
+int mqc_restart_enc(opj_mqc_t *mqc);\r
+/**\r
+RESTART mode switch (TERMALL) reinitialisation\r
+@param mqc MQC handle\r
+*/\r
+void mqc_restart_init_enc(opj_mqc_t *mqc);\r
+/**\r
+ERTERM mode switch (PTERM)\r
+@param mqc MQC handle\r
+*/\r
+void mqc_erterm_enc(opj_mqc_t *mqc);\r
+/**\r
+SEGMARK mode switch (SEGSYM)\r
+@param mqc MQC handle\r
+*/\r
+void mqc_segmark_enc(opj_mqc_t *mqc);\r
+/**\r
+Initialize the decoder\r
+@param mqc MQC handle\r
+@param bp Pointer to the start of the buffer from which the bytes will be read\r
+@param len Length of the input buffer\r
+*/\r
+void mqc_init_dec(opj_mqc_t *mqc, unsigned char *bp, int len);\r
+/**\r
+Decode a symbol\r
+@param mqc MQC handle\r
+@return Returns the decoded symbol (0 or 1)\r
+*/\r
+int mqc_decode(opj_mqc_t *mqc);\r
+/* ----------------------------------------------------------------------- */\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* __MQC_H */\r
diff --git a/src/lib/openjp3d/openjp3d.c b/src/lib/openjp3d/openjp3d.c
new file mode 100755 (executable)
index 0000000..ab2744e
--- /dev/null
@@ -0,0 +1,207 @@
+/*\r
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team\r
+ * Copyright (c) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain\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
+\r
+#include "opj_includes.h"\r
+#define JP3D_VERSION "1.3.0"\r
+/* ---------------------------------------------------------------------- */\r
+#ifdef _WIN32\r
+#ifndef OPJ_STATIC\r
+BOOL APIENTRY\r
+DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {\r
+       switch (ul_reason_for_call) {\r
+               case DLL_PROCESS_ATTACH :\r
+                       break;\r
+               case DLL_PROCESS_DETACH :\r
+                       break;\r
+               case DLL_THREAD_ATTACH :\r
+               case DLL_THREAD_DETACH :\r
+                       break;\r
+    }\r
+\r
+    return TRUE;\r
+}\r
+#endif /* OPJ_STATIC */\r
+#endif /* _WIN32 */\r
+\r
+/* ---------------------------------------------------------------------- */\r
+\r
+const char* OPJ_CALLCONV opj_version() {\r
+    return JP3D_VERSION;\r
+}\r
+opj_dinfo_t* OPJ_CALLCONV opj_create_decompress(OPJ_CODEC_FORMAT format) {\r
+       opj_dinfo_t *dinfo = (opj_dinfo_t*)opj_malloc(sizeof(opj_dinfo_t));\r
+       if(!dinfo) return NULL;\r
+       dinfo->is_decompressor = true;\r
+       switch(format) {\r
+               case CODEC_J3D:\r
+               case CODEC_J2K:\r
+                       /* get a J3D decoder handle */\r
+                       dinfo->j3d_handle = (void*)j3d_create_decompress((opj_common_ptr)dinfo);\r
+                       if(!dinfo->j3d_handle) {\r
+                               opj_free(dinfo);\r
+                               return NULL;\r
+                       }\r
+                       break;\r
+               default:\r
+                       opj_free(dinfo);\r
+                       return NULL;\r
+       }\r
+\r
+       dinfo->codec_format = format;\r
+\r
+       return dinfo;\r
+}\r
+\r
+void OPJ_CALLCONV opj_destroy_decompress(opj_dinfo_t *dinfo) {\r
+       if(dinfo) {\r
+               /* destroy the codec */\r
+               if(dinfo->codec_format != CODEC_UNKNOWN) {\r
+                       j3d_destroy_decompress((opj_j3d_t*)dinfo->j3d_handle);\r
+               }\r
+               /* destroy the decompressor */\r
+               opj_free(dinfo);\r
+       }\r
+}\r
+\r
+void OPJ_CALLCONV opj_set_default_decoder_parameters(opj_dparameters_t *parameters) {\r
+       if(parameters) {\r
+               memset(parameters, 0, sizeof(opj_dparameters_t));\r
+               /* default decoding parameters */\r
+               parameters->cp_layer = 0;\r
+               parameters->cp_reduce[0] = 0;\r
+               parameters->cp_reduce[1] = 0;\r
+               parameters->cp_reduce[2] = 0;\r
+               parameters->bigendian = 0;\r
+\r
+               parameters->decod_format = -1;\r
+               parameters->cod_format = -1;\r
+       }\r
+}\r
+\r
+void OPJ_CALLCONV opj_setup_decoder(opj_dinfo_t *dinfo, opj_dparameters_t *parameters) {\r
+       if(dinfo && parameters) {\r
+               if (dinfo->codec_format != CODEC_UNKNOWN) {\r
+                       j3d_setup_decoder((opj_j3d_t*)dinfo->j3d_handle, parameters);\r
+               }\r
+       }\r
+}\r
+\r
+opj_volume_t* OPJ_CALLCONV opj_decode(opj_dinfo_t *dinfo, opj_cio_t *cio) {\r
+       if(dinfo && cio) {\r
+               if (dinfo->codec_format != CODEC_UNKNOWN) {\r
+                       return j3d_decode((opj_j3d_t*)dinfo->j3d_handle, cio);\r
+               }\r
+       }\r
+\r
+       return NULL;\r
+}\r
+\r
+opj_cinfo_t* OPJ_CALLCONV opj_create_compress(OPJ_CODEC_FORMAT format) {\r
+       opj_cinfo_t *cinfo = (opj_cinfo_t*)opj_malloc(sizeof(opj_cinfo_t));\r
+       if(!cinfo) return NULL;\r
+       cinfo->is_decompressor = false;\r
+       switch(format) {\r
+               case CODEC_J3D:\r
+               case CODEC_J2K:\r
+                       /* get a J3D coder handle */\r
+                       cinfo->j3d_handle = (void*)j3d_create_compress((opj_common_ptr)cinfo);\r
+                       if(!cinfo->j3d_handle) {\r
+                               opj_free(cinfo);\r
+                               return NULL;\r
+                       }\r
+                       break;\r
+               default:\r
+                       opj_free(cinfo);\r
+                       return NULL;\r
+       }\r
+\r
+       cinfo->codec_format = format;\r
+\r
+       return cinfo;\r
+}\r
+\r
+void OPJ_CALLCONV opj_destroy_compress(opj_cinfo_t *cinfo) {\r
+       if(cinfo) {\r
+               /* destroy the codec */\r
+               if (cinfo->codec_format != CODEC_UNKNOWN) {\r
+                               j3d_destroy_compress((opj_j3d_t*)cinfo->j3d_handle);\r
+               }\r
+               /* destroy the decompressor */\r
+               opj_free(cinfo);\r
+       }\r
+}\r
+\r
+void OPJ_CALLCONV opj_set_default_encoder_parameters(opj_cparameters_t *parameters) {\r
+       if(parameters) {\r
+               memset(parameters, 0, sizeof(opj_cparameters_t));\r
+               /* default coding parameters */\r
+               parameters->numresolution[0] = 3;\r
+               parameters->numresolution[1] = 3;\r
+               parameters->numresolution[2] = 1;\r
+               parameters->cblock_init[0] = 64;\r
+               parameters->cblock_init[1] = 64;\r
+               parameters->cblock_init[2] = 64;\r
+               parameters->prog_order = LRCP;\r
+               parameters->roi_compno = -1;            /* no ROI */\r
+               parameters->atk_wt[0] = 1;                              /* 5-3 WT */\r
+               parameters->atk_wt[1] = 1;                              /* 5-3 WT */\r
+               parameters->atk_wt[2] = 1;                              /* 5-3 WT */\r
+               parameters->irreversible = 0;\r
+               parameters->subsampling_dx = 1;\r
+               parameters->subsampling_dy = 1;\r
+               parameters->subsampling_dz = 1;\r
+\r
+               parameters->decod_format = -1;\r
+               parameters->cod_format = -1;\r
+               parameters->encoding_format = ENCOD_2EB;\r
+               parameters->transform_format = TRF_2D_DWT;\r
+       }\r
+}\r
+\r
+void OPJ_CALLCONV opj_setup_encoder(opj_cinfo_t *cinfo, opj_cparameters_t *parameters, opj_volume_t *volume) {\r
+       if(cinfo && parameters && volume) {\r
+               if (cinfo->codec_format != CODEC_UNKNOWN) {\r
+                       j3d_setup_encoder((opj_j3d_t*)cinfo->j3d_handle, parameters, volume);\r
+               }\r
+       }\r
+}\r
+\r
+bool OPJ_CALLCONV opj_encode(opj_cinfo_t *cinfo, opj_cio_t *cio, opj_volume_t *volume, char *index) {\r
+       if(cinfo && cio && volume) {\r
+               if (cinfo->codec_format != CODEC_UNKNOWN) {\r
+                       return j3d_encode((opj_j3d_t*)cinfo->j3d_handle, cio, volume, index);\r
+               }\r
+       }\r
+\r
+       return false;\r
+}\r
+\r
+\r
diff --git a/src/lib/openjp3d/openjp3d.h b/src/lib/openjp3d/openjp3d.h
new file mode 100755 (executable)
index 0000000..e6829d9
--- /dev/null
@@ -0,0 +1,713 @@
+/*\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) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain\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
+#ifndef OPENJPEG_H\r
+#define OPENJPEG_H\r
+\r
+/* \r
+==========================================================\r
+   Compiler directives\r
+==========================================================\r
+*/\r
+\r
+#if defined(OPJ_STATIC) || !defined(_WIN32)\r
+#define OPJ_API\r
+#define OPJ_CALLCONV\r
+#else\r
+#define OPJ_CALLCONV __stdcall\r
+/*\r
+The following ifdef block is the standard way of creating macros which make exporting \r
+from a DLL simpler. All files within this DLL are compiled with the OPJ_EXPORTS\r
+symbol defined on the command line. this symbol should not be defined on any project\r
+that uses this DLL. This way any other project whose source files include this file see \r
+OPJ_API functions as being imported from a DLL, wheras this DLL sees symbols\r
+defined with this macro as being exported.\r
+*/\r
+#if defined(OPJ_EXPORTS) || defined(DLL_EXPORT)\r
+#define OPJ_API __declspec(dllexport)\r
+#else\r
+#define OPJ_API __declspec(dllimport)\r
+#endif /* OPJ_EXPORTS */\r
+#endif /* !OPJ_STATIC || !WIN32 */\r
+\r
+#ifndef __cplusplus\r
+#if defined(HAVE_STDBOOL_H)\r
+/*\r
+The C language implementation does correctly provide the standard header\r
+file "stdbool.h".\r
+ */\r
+#include <stdbool.h>\r
+#else\r
+/*\r
+The C language implementation does not provide the standard header file\r
+"stdbool.h" as required by ISO/IEC 9899:1999.  Try to compensate for this\r
+braindamage below.\r
+*/\r
+#if !defined(bool)\r
+#define        bool    int\r
+#endif\r
+#if !defined(true)\r
+#define true   1\r
+#endif\r
+#if !defined(false)\r
+#define        false   0\r
+#endif\r
+#endif\r
+#endif /* __cplusplus */\r
+\r
+/* \r
+==========================================================\r
+   Useful constant definitions\r
+==========================================================\r
+*/\r
+#ifndef MAX_SLICES\r
+#define MAX_SLICES 300 /**< Maximum allowed size for slices */\r
+#endif /* MAX_PATH */\r
+\r
+#ifndef MAX_PATH\r
+#define MAX_PATH 260   /**< Maximum allowed size for filenames */\r
+#endif /* MAX_PATH */\r
+\r
+#define J3D_MAXRLVLS 32                                        /**< Number of maximum resolution level authorized */\r
+#define J3D_MAXBANDS (7*J3D_MAXRLVLS + 1)      /**< Number of maximum sub-band linked to number of resolution level */\r
+\r
+#define TINY 1.0E-20\r
+/* \r
+==========================================================\r
+   enum definitions\r
+==========================================================\r
+*/\r
+\r
+#define J2K_CFMT 0\r
+#define J3D_CFMT 1\r
+#define LSE_CFMT 2\r
+\r
+#define BIN_DFMT 0\r
+#define PGX_DFMT 1\r
+#define IMG_DFMT 2\r
+/* ----------------------------------------------------------------------- */\r
+\r
+/** Progression order */\r
+typedef enum PROG_ORDER {\r
+/**< place-holder */   \r
+       PROG_UNKNOWN = -1,      \r
+/**< layer-resolution-component-precinct order */      \r
+       LRCP = 0,               \r
+/**< resolution-layer-component-precinct order */      \r
+       RLCP = 1,               \r
+/**< resolution-precinct-component-layer order */      \r
+       RPCL = 2,               \r
+/**< precinct-component-resolution-layer order */      \r
+       PCRL = 3,               \r
+/**< component-precinct-resolution-layer order */      \r
+       CPRL = 4                \r
+} OPJ_PROG_ORDER;\r
+\r
+/**\r
+Supported volume color spaces\r
+*/\r
+typedef enum COLOR_SPACE {\r
+/**< place-holder */   \r
+       CLRSPC_UNKNOWN = -1,    \r
+/**< sRGB */   \r
+       CLRSPC_SRGB = 1,                \r
+/**< grayscale */      \r
+       CLRSPC_GRAY = 2,                \r
+/**< YUV */    \r
+       CLRSPC_SYCC = 3                 \r
+} OPJ_COLOR_SPACE;\r
+\r
+/**\r
+Supported codec\r
+*/\r
+typedef enum CODEC_FORMAT {\r
+       /**< place-holder */\r
+       CODEC_UNKNOWN = -1,\r
+/**< JPEG-2000 codestream : read/write */\r
+       CODEC_J2K = 0,          \r
+/**< JPEG-2000 Part 10 file format : read/write */\r
+       CODEC_J3D = 1           \r
+} OPJ_CODEC_FORMAT;\r
+\r
+/**\r
+Supported entropy coding algorithms\r
+*/\r
+typedef enum ENTROPY_CODING {\r
+/**< place-holder */\r
+       ENCOD_UNKNOWN = -1,\r
+/**< 2D EBCOT encoding */\r
+       ENCOD_2EB = 0,          \r
+/**< 3D EBCOT encoding */\r
+       ENCOD_3EB = 1,          \r
+/**< Golomb-Rice coding with 2D context */\r
+       ENCOD_2GR = 2,          \r
+/**< Golomb-Rice coding with 3D context  */\r
+       ENCOD_3GR = 3           \r
+} OPJ_ENTROPY_CODING;\r
+\r
+/**\r
+Supported transforms\r
+*/\r
+typedef enum TRANSFORM {\r
+/**< place-holder */\r
+       TRF_UNKNOWN = -1,       \r
+/**< 2D DWT, no transform in axial dim */\r
+       TRF_2D_DWT = 0,         \r
+/**< 3D DWT */\r
+       TRF_3D_DWT = 1,         \r
+/**< 3D prediction*/\r
+       TRF_3D_RLS = 2,         \r
+       TRF_3D_LSE = 3\r
+} OPJ_TRANSFORM;\r
+/* \r
+==========================================================\r
+   event manager typedef definitions\r
+==========================================================\r
+*/\r
+\r
+/**\r
+Callback function prototype for events\r
+@param msg Event message\r
+@param client_data \r
+*/\r
+typedef void (*opj_msg_callback) (const char *msg, void *client_data);\r
+\r
+/**\r
+Message handler object\r
+used for \r
+<ul>\r
+<li>Error messages\r
+<li>Warning messages\r
+<li>Debugging messages\r
+</ul>\r
+*/\r
+typedef struct opj_event_mgr {\r
+       /** Error message callback if available, NULL otherwise */\r
+       opj_msg_callback error_handler;\r
+       /** Warning message callback if available, NULL otherwise */\r
+       opj_msg_callback warning_handler;\r
+       /** Debug message callback if available, NULL otherwise */\r
+       opj_msg_callback info_handler;\r
+} opj_event_mgr_t;\r
+\r
+\r
+/* \r
+==========================================================\r
+   codec typedef definitions\r
+==========================================================\r
+*/\r
+\r
+/**\r
+Progression order changes\r
+*/\r
+typedef struct opj_poc {\r
+  int resno0, compno0;\r
+  int layno1, resno1, compno1;\r
+  OPJ_PROG_ORDER prg;\r
+  int tile;\r
+  char progorder[4];\r
+} opj_poc_t;\r
+\r
+\r
+/**\r
+Compression parameters\r
+*/\r
+typedef struct opj_cparameters {\r
+/** size of tile: tile_size_on = false (not in argument) or = true (in argument) */\r
+       bool tile_size_on;      \r
+/** XTOsiz */\r
+       int cp_tx0;\r
+/** YTOsiz */\r
+       int cp_ty0;     \r
+/** ZTOsiz */\r
+       int cp_tz0;             \r
+\r
+/** XTsiz */\r
+       int cp_tdx;     \r
+/** YTsiz */\r
+       int cp_tdy;     \r
+/** ZTsiz */\r
+       int cp_tdz;             \r
+                                                       \r
+/** allocation by rate/distortion */\r
+       int cp_disto_alloc;             \r
+/** allocation by fixed layer */               \r
+       int cp_fixed_alloc;             \r
+/** add fixed_quality */       \r
+       int cp_fixed_quality;   \r
+/** fixed layer */\r
+       int *cp_matrice;\r
+/** number of layers */\r
+       int tcp_numlayers;\r
+/** rates for successive layers */\r
+       float tcp_rates[100];\r
+/** psnr's for successive layers */\r
+       float tcp_distoratio[100];      \r
+/** comment for coding */\r
+       char *cp_comment;\r
+/** csty : coding style */\r
+       int csty;                                       \r
+/** DC offset (DCO) */\r
+       int dcoffset;\r
+/** progression order (default LRCP) */\r
+       OPJ_PROG_ORDER prog_order;      \r
+/** progression order changes */\r
+       opj_poc_t POC[J3D_MAXRLVLS-1];  \r
+/** number of progression order changes (POC), default to 0 */\r
+       int numpocs;                            \r
+\r
+/** number of resolutions */\r
+       int numresolution[3];           \r
+/** initial code block width, height and depth, default to 64 */\r
+       int cblock_init[3];                     \r
+/** mode switch (1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL) 8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)) */\r
+       int mode;                                       \r
+\r
+/** 1 : use the irreversible DWT 9-7, 0 : use lossless compression (default) */\r
+       int irreversible;                       \r
+/** WT from ATK, default to 0 (false), no of atk used */\r
+       int atk_wt[3];\r
+/** region of interest: affected component in [0..3], -1 means no ROI */\r
+       int roi_compno;                         \r
+/** region of interest: upshift value */\r
+       int roi_shift;                          \r
+\r
+/* number of precinct size specifications */\r
+       int res_spec;                           \r
+/** initial precinct width */\r
+       int prct_init[3][J3D_MAXRLVLS]; \r
+\r
+/** transform format 0: 0: 2DWT, 1: 2D1P, 2: 3DWT, 3: 3RLS */\r
+       OPJ_TRANSFORM transform_format; \r
+/** output file format 0: 2EB, 1: 3EB, 2: 2GR, 3: 3GR, 4: GRI */\r
+       OPJ_ENTROPY_CODING encoding_format;     \r
+\r
+       /**@name command line encoder parameters (not used inside the library) */\r
+       /*@{*/\r
+       char infile[MAX_PATH];          /** input file name */\r
+       char outfile[MAX_PATH];         /** output file name */\r
+       char imgfile[MAX_PATH];         /** IMG file name for BIN volumes*/\r
+       int index_on;                           /** creation of an index file, default to 0 (false) */\r
+       char index[MAX_PATH];           /** index file name */\r
+       \r
+       int volume_offset_x0;           /** subvolume encoding: origin volume offset in x, y and z direction */\r
+       int volume_offset_y0;\r
+       int volume_offset_z0;\r
+       \r
+       int subsampling_dx;                     /** subsampling value for dx */\r
+       int subsampling_dy;\r
+       int subsampling_dz;\r
+       \r
+       int decod_format;                       /** input file format 0: BIN, 1: PGX */\r
+       int cod_format;                         /** output file format 0: JP3D */\r
+       /*@}*/\r
+} opj_cparameters_t;\r
+\r
+/**\r
+Decompression parameters\r
+*/\r
+typedef struct opj_dparameters {\r
+/** Set the number of highest resolution levels to be discarded. if != 0, then original dimension divided by 2^(reduce); if == 0 or not used, volume is decoded to the full resolution */\r
+       int cp_reduce[3];               \r
+/** Set the maximum number of quality layers to decode. if != 0, then only the first "layer" layers are decoded; if == 0 or not used, all the quality layers are decoded       */\r
+       int cp_layer;   \r
+       int bigendian;\r
+       \r
+       /**@name command line encoder parameters (not used inside the library) */\r
+       /*@{*/\r
+/** input file name */\r
+       char infile[MAX_PATH];  \r
+/** output file name */\r
+       char outfile[MAX_PATH]; \r
+/** IMG file name for BIN volumes*/\r
+       char imgfile[MAX_PATH];\r
+/** Original file name for PSNR measures*/\r
+       char original[MAX_PATH];\r
+/** input file format 0: J2K, 1: JP3D */\r
+       int decod_format;               \r
+/** input file format 0: BIN, 1: PGM */\r
+       int cod_format;\r
+/** original file format 0: BIN, 1: PGM */\r
+       int orig_format;        \r
+       /*@}*/\r
+} opj_dparameters_t;\r
+\r
+/** Common fields between JPEG-2000 compression and decompression master structs. */\r
+#define opj_common_fields \\r
+       opj_event_mgr_t *event_mgr;     /**< pointer to the event manager */\\r
+       void * client_data;                     /**< Available for use by application */\\r
+       bool is_decompressor;           /**< So common code can tell which is which */\\r
+       OPJ_CODEC_FORMAT codec_format;          /**< selected codec */\\r
+       OPJ_ENTROPY_CODING encoding_format;     /**< selected entropy coding */\\r
+       OPJ_TRANSFORM transform_format;         /**< selected transform */\\r
+       void *j3d_handle                        /**< pointer to the J3D codec */\r
+       \r
+/* Routines that are to be used by both halves of the library are declared\r
+ * to receive a pointer to this structure.  There are no actual instances of\r
+ * opj_common_struct_t, only of opj_cinfo_t and opj_dinfo_t.\r
+ */\r
+typedef struct opj_common_struct {\r
+  opj_common_fields;           /* Fields common to both master struct types */\r
+  /* Additional fields follow in an actual opj_cinfo_t or\r
+   * opj_dinfo_t.  All three structs must agree on these\r
+   * initial fields!  (This would be a lot cleaner in C++.)\r
+   */\r
+} opj_common_struct_t;\r
+\r
+typedef opj_common_struct_t * opj_common_ptr;\r
+\r
+/**\r
+Compression context info\r
+*/\r
+typedef struct opj_cinfo {\r
+       /** Fields shared with opj_dinfo_t */\r
+       opj_common_fields;      \r
+       /* other specific fields go here */\r
+} opj_cinfo_t;\r
+\r
+/**\r
+Decompression context info\r
+*/\r
+typedef struct opj_dinfo {\r
+       /** Fields shared with opj_cinfo_t */\r
+       opj_common_fields;      \r
+       /* other specific fields go here */\r
+} opj_dinfo_t;\r
+\r
+/* \r
+==========================================================\r
+   I/O stream typedef definitions\r
+==========================================================\r
+*/\r
+\r
+/*\r
+ * Stream open flags.\r
+ */\r
+/** The stream was opened for reading. */\r
+#define OPJ_STREAM_READ        0x0001\r
+/** The stream was opened for writing. */\r
+#define OPJ_STREAM_WRITE 0x0002\r
+\r
+/**\r
+Byte input-output stream (CIO)\r
+*/\r
+typedef struct opj_cio {\r
+/** codec context */\r
+       opj_common_ptr cinfo;   \r
+/** open mode (read/write) either OPJ_STREAM_READ or OPJ_STREAM_WRITE */\r
+       int openmode;                   \r
+/** pointer to the start of the buffer */\r
+       unsigned char *buffer;  \r
+/** buffer size in bytes */\r
+       int length;                             \r
+/** pointer to the start of the stream */\r
+       unsigned char *start;           \r
+/** pointer to the end of the stream */\r
+       unsigned char *end;                     \r
+/** pointer to the current position */\r
+       unsigned char *bp;                      \r
+} opj_cio_t;\r
+\r
+/* \r
+==========================================================\r
+   volume typedef definitions\r
+==========================================================\r
+*/\r
+\r
+/**\r
+Defines a single volume component\r
+*/\r
+typedef struct opj_volume_comp {\r
+/** XRsiz: horizontal separation of a sample of ith component with respect to the reference grid */\r
+       int dx; \r
+/** YRsiz: vertical separation of a sample of ith component with respect to the reference grid */\r
+       int dy; \r
+/** ZRsiz: vertical separation of a sample of ith component with respect to the reference grid */\r
+       int dz;\r
+/** data width */\r
+       int w;  \r
+       /** data height */\r
+       int h;  \r
+       /** data length : no of slices */\r
+       int l;  \r
+       /** x component offset compared to the whole volume */\r
+       int x0; \r
+       /** y component offset compared to the whole volume */\r
+       int y0; \r
+       /** z component offset compared to the whole volume */\r
+       int z0; \r
+       /** precision */\r
+       int prec;       \r
+       /** volume depth in bits */\r
+       int bpp;        \r
+       /** DC offset (15444-2) */\r
+       int dcoffset;\r
+       /** signed (1) / unsigned (0) */\r
+       int sgnd;               \r
+       /** BE byte order (1) / LE byte order  (0) */\r
+       int bigendian;\r
+       /** number of decoded resolution */\r
+       int resno_decoded[3];   \r
+       /** number of division by 2 of the out volume compared to the original size of volume */\r
+       int factor[3];  \r
+       /** volume component data */\r
+       int *data;                              \r
+} opj_volume_comp_t;\r
+\r
+/** \r
+Defines volume data and characteristics\r
+*/\r
+typedef struct opj_volume {\r
+/** XOsiz: horizontal offset from the origin of the reference grid to the left side of the volume area */\r
+       int x0; \r
+/** YOsiz: vertical offset from the origin of the reference grid to the top side of the volume area */\r
+       int y0; \r
+/** ZOsiz: vertical offset from the origin of the reference grid to the top side of the volume area */\r
+       int z0; \r
+/** Xsiz: width of the reference grid */\r
+       int x1; \r
+/** Ysiz: height of the reference grid */\r
+       int y1; \r
+/** Zsiz: length of the reference grid */\r
+       int z1; \r
+/** number of components in the volume */\r
+       int numcomps;   \r
+/** number of slices in the volume */\r
+       int numslices;  \r
+/** color space: sRGB, Greyscale or YUV */\r
+       OPJ_COLOR_SPACE color_space;\r
+/** volume components */\r
+       opj_volume_comp_t *comps;       \r
+} opj_volume_t;\r
+\r
+/**\r
+Component parameters structure used by the opj_volume_create function\r
+*/\r
+typedef struct opj_volume_comptparm {\r
+       /** XRsiz: horizontal separation of a sample of ith component with respect to the reference grid */\r
+       int dx; \r
+       /** YRsiz: vertical separation of a sample of ith component with respect to the reference grid */\r
+       int dy; \r
+       /** ZRsiz: axial separation of a sample of ith component with respect to the reference grid */\r
+       int dz; \r
+       /** data width */\r
+       int w;  \r
+       /** data height */\r
+       int h;  \r
+       /** data length */\r
+       int l;  \r
+       /** x component offset compared to the whole volume */\r
+       int x0; \r
+       /** y component offset compared to the whole volume */\r
+       int y0;\r
+       /** z component offset compared to the whole volume */\r
+       int z0; \r
+       /** precision */\r
+       int prec;\r
+       /** volume depth in bits */\r
+       int bpp;        \r
+       /** signed (1) / unsigned (0) */\r
+       int sgnd;\r
+       /** DC offset*/\r
+       int dcoffset;\r
+       /** BE byte order (1) / LE byte order  (0) */\r
+       int bigendian;\r
+} opj_volume_cmptparm_t;\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+\r
+/* \r
+==========================================================\r
+   openjpeg version\r
+==========================================================\r
+*/\r
+\r
+OPJ_API const char * OPJ_CALLCONV opj_version();\r
+\r
+/* \r
+==========================================================\r
+   volume functions definitions\r
+==========================================================\r
+*/\r
+\r
+/**\r
+Create an volume\r
+@param numcmpts number of components\r
+@param cmptparms components parameters\r
+@param clrspc volume color space\r
+@return returns a new volume structure if successful, returns NULL otherwise\r
+*/\r
+OPJ_API opj_volume_t* OPJ_CALLCONV opj_volume_create(int numcmpts, opj_volume_cmptparm_t *cmptparms, OPJ_COLOR_SPACE clrspc);\r
+\r
+/**\r
+Deallocate any resources associated with an volume\r
+@param volume volume to be destroyed\r
+*/\r
+OPJ_API void OPJ_CALLCONV opj_volume_destroy(opj_volume_t *volume);\r
+\r
+/* \r
+==========================================================\r
+   stream functions definitions\r
+==========================================================\r
+*/\r
+\r
+/**\r
+Open and allocate a memory stream for read / write. \r
+On reading, the user must provide a buffer containing encoded data. The buffer will be \r
+wrapped by the returned CIO handle. \r
+On writing, buffer parameters must be set to 0: a buffer will be allocated by the library \r
+to contain encoded data. \r
+@param cinfo Codec context info\r
+@param buffer Reading: buffer address. Writing: NULL\r
+@param length Reading: buffer length. Writing: 0\r
+@return Returns a CIO handle if successful, returns NULL otherwise\r
+*/\r
+OPJ_API opj_cio_t* OPJ_CALLCONV opj_cio_open(opj_common_ptr cinfo, unsigned char *buffer, int length);\r
+\r
+/**\r
+Close and free a CIO handle\r
+@param cio CIO handle to free\r
+*/\r
+OPJ_API void OPJ_CALLCONV opj_cio_close(opj_cio_t *cio);\r
+\r
+/**\r
+Get position in byte stream\r
+@param cio CIO handle\r
+@return Returns the position in bytes\r
+*/\r
+OPJ_API int OPJ_CALLCONV cio_tell(opj_cio_t *cio);\r
+/**\r
+Set position in byte stream\r
+@param cio CIO handle\r
+@param pos Position, in number of bytes, from the beginning of the stream\r
+*/\r
+OPJ_API void OPJ_CALLCONV cio_seek(opj_cio_t *cio, int pos);\r
+\r
+/* \r
+==========================================================\r
+   event manager functions definitions\r
+==========================================================\r
+*/\r
+\r
+OPJ_API opj_event_mgr_t* OPJ_CALLCONV opj_set_event_mgr(opj_common_ptr cinfo, opj_event_mgr_t *event_mgr, void *context);\r
+\r
+/* \r
+==========================================================\r
+   codec functions definitions\r
+==========================================================\r
+*/\r
+/**\r
+Creates a J3D decompression structure\r
+@param format Decoder to select\r
+@return Returns a handle to a decompressor if successful, returns NULL otherwise\r
+*/\r
+OPJ_API opj_dinfo_t* OPJ_CALLCONV opj_create_decompress(OPJ_CODEC_FORMAT format);\r
+/**\r
+Destroy a decompressor handle\r
+@param dinfo decompressor handle to destroy\r
+*/\r
+OPJ_API void OPJ_CALLCONV opj_destroy_decompress(opj_dinfo_t *dinfo);\r
+/**\r
+Set decoding parameters to default values\r
+@param parameters Decompression parameters\r
+*/\r
+OPJ_API void OPJ_CALLCONV opj_set_default_decoder_parameters(opj_dparameters_t *parameters);\r
+/**\r
+Setup the decoder decoding parameters using user parameters.\r
+Decoding parameters are returned in j3d->cp. \r
+@param dinfo decompressor handle\r
+@param parameters decompression parameters\r
+*/\r
+OPJ_API void OPJ_CALLCONV opj_setup_decoder(opj_dinfo_t *dinfo, opj_dparameters_t *parameters);\r
+/**\r
+Decode an volume from a JPEG-2000 codestream\r
+@param dinfo decompressor handle\r
+@param cio Input buffer stream\r
+@return Returns a decoded volume if successful, returns NULL otherwise\r
+*/\r
+OPJ_API opj_volume_t* OPJ_CALLCONV opj_decode(opj_dinfo_t *dinfo, opj_cio_t *cio);\r
+/**\r
+Creates a J3D/JP2 compression structure\r
+@param format Coder to select\r
+@return Returns a handle to a compressor if successful, returns NULL otherwise\r
+*/\r
+OPJ_API opj_cinfo_t* OPJ_CALLCONV opj_create_compress(OPJ_CODEC_FORMAT format);\r
+/**\r
+Destroy a compressor handle\r
+@param cinfo compressor handle to destroy\r
+*/\r
+OPJ_API void OPJ_CALLCONV opj_destroy_compress(opj_cinfo_t *cinfo);\r
+/**\r
+Set encoding parameters to default values, that means : \r
+<ul>\r
+<li>Lossless\r
+<li>1 tile\r
+<li>Size of precinct : 2^15 x 2^15 (means 1 precinct)\r
+<li>Size of code-block : 64 x 64\r
+<li>Number of resolutions: 6\r
+<li>No SOP marker in the codestream\r
+<li>No EPH marker in the codestream\r
+<li>No sub-sampling in x or y direction\r
+<li>No mode switch activated\r
+<li>Progression order: LRCP\r
+<li>No index file\r
+<li>No ROI upshifted\r
+<li>No offset of the origin of the volume\r
+<li>No offset of the origin of the tiles\r
+<li>Reversible DWT 5-3\r
+</ul>\r
+@param parameters Compression parameters\r
+*/\r
+OPJ_API void OPJ_CALLCONV opj_set_default_encoder_parameters(opj_cparameters_t *parameters);\r
+/**\r
+Setup the encoder parameters using the current volume and using user parameters. \r
+@param cinfo compressor handle\r
+@param parameters compression parameters\r
+@param volume input filled volume\r
+*/\r
+OPJ_API void OPJ_CALLCONV opj_setup_encoder(opj_cinfo_t *cinfo, opj_cparameters_t *parameters, opj_volume_t *volume);\r
+/**\r
+Encode an volume into a JPEG-2000 codestream\r
+@param cinfo compressor handle\r
+@param cio Output buffer stream\r
+@param volume Volume to encode\r
+@param index Name of the index file if required, NULL otherwise\r
+@return Returns true if successful, returns false otherwise\r
+*/\r
+OPJ_API bool OPJ_CALLCONV opj_encode(opj_cinfo_t *cinfo, opj_cio_t *cio, opj_volume_t *volume, char *index);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif /* OPENJPEG_H */\r
diff --git a/src/lib/openjp3d/opj_includes.h b/src/lib/openjp3d/opj_includes.h
new file mode 100755 (executable)
index 0000000..40fecfc
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * 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_INCLUDES_H
+#define OPJ_INCLUDES_H
+
+/*
+ ==========================================================
+   Standard includes used by the library
+ ==========================================================
+*/
+#include <memory.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <float.h>
+#include <time.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <assert.h>
+/*
+ ==========================================================
+   OpenJPEG interface
+ ==========================================================
+ */
+#include "openjp3d.h"
+
+/*
+ ==========================================================
+   OpenJPEG modules
+ ==========================================================
+*/
+
+#include "jp3d_lib.h"
+#include "event.h"
+#include "cio.h"
+
+#include "volume.h"
+#include "jp3d.h"
+
+#include "mqc.h"
+#include "raw.h"
+#include "bio.h"
+#include "tgt.h"
+#include "tcd.h"
+#include "t1.h"
+#include "t1_3d.h"
+#include "dwt.h"
+#include "pi.h"
+#include "t2.h"
+#include "mct.h"
+#include "int.h"
+#include "fix.h"
+
+//#include "pred.h"
+//#include "golomb.h"
+
+#endif /* OPJ_INCLUDES_H */
diff --git a/src/lib/openjp3d/pi.c b/src/lib/openjp3d/pi.c
new file mode 100755 (executable)
index 0000000..f9b8a96
--- /dev/null
@@ -0,0 +1,630 @@
+/*\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) 2006, Mónica Díez, LPI-UVA, Spain\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 "opj_includes.h"\r
+\r
+/** @defgroup PI PI - Implementation of a packet iterator */\r
+/*@{*/\r
+\r
+/** @name Funciones locales */\r
+/*@{*/\r
+\r
+/**\r
+Get next packet in layer-resolution-component-precinct order.\r
+@param pi packet iterator to modify\r
+@return returns false if pi pointed to the last packet or else returns true \r
+*/\r
+static bool pi_next_lrcp(opj_pi_iterator_t * pi);\r
+/**\r
+Get next packet in resolution-layer-component-precinct order.\r
+@param pi packet iterator to modify\r
+@return returns false if pi pointed to the last packet or else returns true \r
+*/\r
+static bool pi_next_rlcp(opj_pi_iterator_t * pi);\r
+/**\r
+Get next packet in resolution-precinct-component-layer order.\r
+@param pi packet iterator to modify\r
+@return returns false if pi pointed to the last packet or else returns true \r
+*/\r
+static bool pi_next_rpcl(opj_pi_iterator_t * pi);\r
+/**\r
+Get next packet in precinct-component-resolution-layer order.\r
+@param pi packet iterator to modify\r
+@return returns false if pi pointed to the last packet or else returns true \r
+*/\r
+static bool pi_next_pcrl(opj_pi_iterator_t * pi);\r
+/**\r
+Get next packet in component-precinct-resolution-layer order.\r
+@param pi packet iterator to modify\r
+@return returns false if pi pointed to the last packet or else returns true \r
+*/\r
+static bool pi_next_cprl(opj_pi_iterator_t * pi);\r
+\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+/* \r
+==========================================================\r
+   local functions\r
+==========================================================\r
+*/\r
+\r
+static bool pi_next_lrcp(opj_pi_iterator_t * pi) {\r
+       opj_pi_comp_t *comp = NULL;\r
+       opj_pi_resolution_t *res = NULL;\r
+       long index = 0;\r
+\r
+       if (!pi->first) {\r
+               comp = &pi->comps[pi->compno];\r
+               res = &comp->resolutions[pi->resno];\r
+               goto LABEL_SKIP;\r
+       } else {\r
+               pi->first = 0;\r
+       }\r
+\r
+       for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {\r
+               for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {\r
+                       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {\r
+                               comp = &pi->comps[pi->compno];\r
+                               if (pi->resno >= comp->numresolution[0]) {\r
+                                       continue;\r
+                               }\r
+                               res = &comp->resolutions[pi->resno];\r
+                               //for (pi->precno = 0; pi->precno < (res->prctno[0] * res->prctno[1]); pi->precno++) {\r
+                               for (pi->precno = 0; pi->precno < (res->prctno[0] * res->prctno[1] * res->prctno[2]); pi->precno++) {\r
+                                       index = pi->layno * pi->step_l \r
+                                               + pi->resno * pi->step_r \r
+                                               + pi->compno * pi->step_c \r
+                                               + pi->precno * pi->step_p;\r
+                                       if (!pi->include[index]) {\r
+                                               pi->include[index] = 1;\r
+                                               return true;\r
+                                       }\r
+LABEL_SKIP:;\r
+\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+       \r
+       return false;\r
+}\r
+\r
+static bool pi_next_rlcp(opj_pi_iterator_t * pi) {\r
+       opj_pi_comp_t *comp = NULL;\r
+       opj_pi_resolution_t *res = NULL;\r
+       long index = 0;\r
+\r
+       if (!pi->first) {\r
+               comp = &pi->comps[pi->compno];\r
+               res = &comp->resolutions[pi->resno];\r
+               goto LABEL_SKIP;\r
+       } else {\r
+               pi->first = 0;\r
+       }\r
+\r
+       for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {\r
+               for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {\r
+                       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {\r
+                               comp = &pi->comps[pi->compno];\r
+                               if (pi->resno >= comp->numresolution[0]) {\r
+                                       continue;\r
+                               }\r
+                               res = &comp->resolutions[pi->resno];\r
+                               //for (pi->precno = 0; pi->precno < (res->prctno[0] * res->prctno[1]); pi->precno++) {\r
+                               for (pi->precno = 0; pi->precno < (res->prctno[0] * res->prctno[1] * res->prctno[2]); pi->precno++) {\r
+                                       index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p;\r
+                                       if (!pi->include[index]) {\r
+                                               pi->include[index] = 1;\r
+                                               return true;\r
+                                       }\r
+LABEL_SKIP:;\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+       \r
+       return false;\r
+}\r
+\r
+static bool pi_next_rpcl(opj_pi_iterator_t * pi) {\r
+       opj_pi_comp_t *comp = NULL;\r
+       opj_pi_resolution_t *res = NULL;\r
+       long index = 0;\r
+\r
+       if (!pi->first) {\r
+               goto LABEL_SKIP;\r
+       } else {\r
+               int compno, resno;\r
+               pi->first = 0;\r
+               pi->dx = 0;\r
+               pi->dy = 0;\r
+               for (compno = 0; compno < pi->numcomps; compno++) {\r
+                       comp = &pi->comps[compno];\r
+                       for (resno = 0; resno < comp->numresolution[0]; resno++) {\r
+                               int dx, dy,dz;\r
+                               res = &comp->resolutions[resno];\r
+                               dx = comp->dx * (1 << (res->pdx + comp->numresolution[0] - 1 - resno));\r
+                               dy = comp->dy * (1 << (res->pdy + comp->numresolution[1] - 1 - resno));\r
+                               dz = comp->dz * (1 << (res->pdz + comp->numresolution[2] - 1 - resno));\r
+                               pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);\r
+                               pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);\r
+                               pi->dz = !pi->dz ? dz : int_min(pi->dz, dz);\r
+                       }\r
+               }\r
+       }\r
+\r
+       for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {\r
+               for (pi->z = pi->tz0; pi->z < pi->tz1; pi->z += pi->dz - (pi->z % pi->dz)) {\r
+                       for (pi->y = pi->ty0; pi->y < pi->ty1; pi->y += pi->dy - (pi->y % pi->dy)) {\r
+                               for (pi->x = pi->tx0; pi->x < pi->tx1; pi->x += pi->dx - (pi->x % pi->dx)) {\r
+                                       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {\r
+                                               int levelnox, levelnoy, levelnoz;\r
+                                               int trx0, try0, trz0;\r
+                                               int trx1, try1, trz1;\r
+                                               int rpx, rpy, rpz;\r
+                                               int prci, prcj, prck;\r
+                                               comp = &pi->comps[pi->compno];\r
+                                               if (pi->resno >= comp->numresolution[0]) {\r
+                                                       continue;\r
+                                               }\r
+                                               res = &comp->resolutions[pi->resno];\r
+                                               levelnox = comp->numresolution[0] - 1 - pi->resno;\r
+                                               levelnoy = comp->numresolution[1] - 1 - pi->resno;\r
+                                               levelnoz = comp->numresolution[2] - 1 - pi->resno;\r
+                                               trx0 = int_ceildiv(pi->tx0, comp->dx << levelnox);\r
+                                               try0 = int_ceildiv(pi->ty0, comp->dy << levelnoy);\r
+                                               trz0 = int_ceildiv(pi->tz0, comp->dz << levelnoz);\r
+                                               trx1 = int_ceildiv(pi->tx1, comp->dx << levelnox);\r
+                                               try1 = int_ceildiv(pi->ty1, comp->dy << levelnoy);\r
+                                               trz1 = int_ceildiv(pi->tz1, comp->dz << levelnoz);\r
+                                               rpx = res->pdx + levelnox;\r
+                                               rpy = res->pdy + levelnoy;\r
+                                               rpz = res->pdz + levelnoz;\r
+                                               if ((!(pi->x % (comp->dx << rpx) == 0) || (pi->x == pi->tx0 && (trx0 << levelnox) % (1 << rpx)))) {\r
+                                                       continue;\r
+                                               }\r
+                                               if ((!(pi->y % (comp->dy << rpy) == 0) || (pi->y == pi->ty0 && (try0 << levelnoy) % (1 << rpx)))) {\r
+                                                       continue;\r
+                                               }\r
+                                               if ((!(pi->z % (comp->dz << rpz) == 0) || (pi->z == pi->tz0 && (trz0 << levelnoz) % (1 << rpx)))) {\r
+                                                       continue;\r
+                                               }\r
+                                               if ((res->prctno[0]==0)||(res->prctno[1]==0)||(res->prctno[2]==0)) continue;\r
+                                               \r
+                                               if ((trx0==trx1)||(try0==try1)||(trz0==trz1)) continue;\r
+                                               \r
+                                               prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelnox), res->pdx) \r
+                                                       - int_floordivpow2(trx0, res->pdx);\r
+                                               prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelnoy), res->pdy) \r
+                                                       - int_floordivpow2(try0, res->pdy);\r
+                                               prck = int_floordivpow2(int_ceildiv(pi->z, comp->dz << levelnoz), res->pdz) \r
+                                                       - int_floordivpow2(trz0, res->pdz);\r
+                                               pi->precno = prci + prcj * res->prctno[0] + prck * res->prctno[0] * res->prctno[1];\r
+                                               for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {\r
+                                                       index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p;\r
+                                                       if (!pi->include[index]) {\r
+                                                               pi->include[index] = 1;\r
+                                                               return true;\r
+                                                       }\r
+       LABEL_SKIP:;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+       \r
+       return false;\r
+}\r
+\r
+static bool pi_next_pcrl(opj_pi_iterator_t * pi) {\r
+       opj_pi_comp_t *comp = NULL;\r
+       opj_pi_resolution_t *res = NULL;\r
+       long index = 0;\r
+\r
+       if (!pi->first) {\r
+               comp = &pi->comps[pi->compno];\r
+               goto LABEL_SKIP;\r
+       } else {\r
+               int compno, resno;\r
+               pi->first = 0;\r
+               pi->dx = 0;\r
+               pi->dy = 0;\r
+               pi->dz = 0;\r
+               for (compno = 0; compno < pi->numcomps; compno++) {\r
+                       comp = &pi->comps[compno];\r
+                       for (resno = 0; resno < comp->numresolution[0]; resno++) {\r
+                               int dx, dy, dz;\r
+                               res = &comp->resolutions[resno];\r
+                               dx = comp->dx * (1 << (res->pdx + comp->numresolution[0] - 1 - resno));\r
+                               dy = comp->dy * (1 << (res->pdy + comp->numresolution[1] - 1 - resno));\r
+                               dz = comp->dz * (1 << (res->pdy + comp->numresolution[2] - 1 - resno));\r
+                               pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);\r
+                               pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);\r
+                               pi->dz = !pi->dz ? dz : int_min(pi->dz, dz);\r
+                       }\r
+               }\r
+       }\r
+\r
+for (pi->z = pi->tz0; pi->z < pi->tz1; pi->z += pi->dz - (pi->z % pi->dz)) {\r
+       for (pi->y = pi->ty0; pi->y < pi->ty1; pi->y += pi->dy - (pi->y % pi->dy)) {\r
+               for (pi->x = pi->tx0; pi->x < pi->tx1; pi->x += pi->dx - (pi->x % pi->dx)) {\r
+                       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {\r
+                               comp = &pi->comps[pi->compno];\r
+                               for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolution[0]); pi->resno++) {\r
+                                               int levelnox, levelnoy, levelnoz;\r
+                                               int trx0, try0, trz0;\r
+                                               int trx1, try1, trz1;\r
+                                               int rpx, rpy, rpz;\r
+                                               int prci, prcj, prck;\r
+                                               comp = &pi->comps[pi->compno];\r
+                                               if (pi->resno >= comp->numresolution[0]) {\r
+                                                       continue;\r
+                                               }\r
+                                               res = &comp->resolutions[pi->resno];\r
+                                               levelnox = comp->numresolution[0] - 1 - pi->resno;\r
+                                               levelnoy = comp->numresolution[1] - 1 - pi->resno;\r
+                                               levelnoz = comp->numresolution[2] - 1 - pi->resno;\r
+                                               trx0 = int_ceildiv(pi->tx0, comp->dx << levelnox);\r
+                                               try0 = int_ceildiv(pi->ty0, comp->dy << levelnoy);\r
+                                               trz0 = int_ceildiv(pi->tz0, comp->dz << levelnoz);\r
+                                               trx1 = int_ceildiv(pi->tx1, comp->dx << levelnox);\r
+                                               try1 = int_ceildiv(pi->ty1, comp->dy << levelnoy);\r
+                                               trz1 = int_ceildiv(pi->tz1, comp->dz << levelnoz);\r
+                                               rpx = res->pdx + levelnox;\r
+                                               rpy = res->pdy + levelnoy;\r
+                                               rpz = res->pdz + levelnoz;\r
+                                               if ((!(pi->x % (comp->dx << rpx) == 0) || (pi->x == pi->tx0 && (trx0 << levelnox) % (1 << rpx)))) {\r
+                                                       continue;\r
+                                               }\r
+                                               if ((!(pi->y % (comp->dy << rpy) == 0) || (pi->y == pi->ty0 && (try0 << levelnoy) % (1 << rpx)))) {\r
+                                                       continue;\r
+                                               }\r
+                                               if ((!(pi->z % (comp->dz << rpz) == 0) || (pi->z == pi->tz0 && (trz0 << levelnoz) % (1 << rpx)))) {\r
+                                                       continue;\r
+                                               }\r
+                                               if ((res->prctno[0]==0)||(res->prctno[1]==0)||(res->prctno[2]==0)) continue;\r
+                                               \r
+                                               if ((trx0==trx1)||(try0==try1)||(trz0==trz1)) continue;\r
+                                               \r
+                                               prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelnox), res->pdx) \r
+                                                       - int_floordivpow2(trx0, res->pdx);\r
+                                               prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelnoy), res->pdy) \r
+                                                       - int_floordivpow2(try0, res->pdy);\r
+                                               prck = int_floordivpow2(int_ceildiv(pi->z, comp->dz << levelnoz), res->pdz) \r
+                                                       - int_floordivpow2(trz0, res->pdz);\r
+                                               pi->precno = prci + prcj * res->prctno[0] + prck * res->prctno[0] * res->prctno[1];\r
+                                               for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {\r
+                                                       index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p;\r
+                                                       if (!pi->include[index]) {\r
+                                                               pi->include[index] = 1;\r
+                                                               return true;\r
+                                                       }       \r
+LABEL_SKIP:;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+}\r
+       \r
+       return false;\r
+}\r
+\r
+static bool pi_next_cprl(opj_pi_iterator_t * pi) {\r
+       opj_pi_comp_t *comp = NULL;\r
+       opj_pi_resolution_t *res = NULL;\r
+       long index = 0;\r
+\r
+       if (!pi->first) {\r
+               comp = &pi->comps[pi->compno];\r
+               goto LABEL_SKIP;\r
+       } else {\r
+               pi->first = 0;\r
+       }\r
+\r
+       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {\r
+               int resno;\r
+               comp = &pi->comps[pi->compno];\r
+               pi->dx = 0;\r
+               pi->dy = 0;\r
+               for (resno = 0; resno < comp->numresolution[0]; resno++) {\r
+                       int dx, dy;\r
+                       res = &comp->resolutions[resno];\r
+                       dx = comp->dx * (1 << (res->pdx + comp->numresolution[0] - 1 - resno));\r
+                       dy = comp->dy * (1 << (res->pdy + comp->numresolution[0] - 1 - resno));\r
+                       pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);\r
+                       pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);\r
+               }\r
+       for (pi->z = pi->tz0; pi->z < pi->tz1; pi->z += pi->dz - (pi->z % pi->dz)) {\r
+               for (pi->y = pi->ty0; pi->y < pi->ty1; pi->y += pi->dy - (pi->y % pi->dy)) {\r
+                       for (pi->x = pi->tx0; pi->x < pi->tx1; pi->x += pi->dx - (pi->x % pi->dx)) {\r
+                               for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolution[0]); pi->resno++) {\r
+                                               int levelnox, levelnoy, levelnoz;\r
+                                               int trx0, try0, trz0;\r
+                                               int trx1, try1, trz1;\r
+                                               int rpx, rpy, rpz;\r
+                                               int prci, prcj, prck;\r
+                                               comp = &pi->comps[pi->compno];\r
+                                               if (pi->resno >= comp->numresolution[0]) {\r
+                                                       continue;\r
+                                               }\r
+                                               res = &comp->resolutions[pi->resno];\r
+                                               levelnox = comp->numresolution[0] - 1 - pi->resno;\r
+                                               levelnoy = comp->numresolution[1] - 1 - pi->resno;\r
+                                               levelnoz = comp->numresolution[2] - 1 - pi->resno;\r
+                                               trx0 = int_ceildiv(pi->tx0, comp->dx << levelnox);\r
+                                               try0 = int_ceildiv(pi->ty0, comp->dy << levelnoy);\r
+                                               trz0 = int_ceildiv(pi->tz0, comp->dz << levelnoz);\r
+                                               trx1 = int_ceildiv(pi->tx1, comp->dx << levelnox);\r
+                                               try1 = int_ceildiv(pi->ty1, comp->dy << levelnoy);\r
+                                               trz1 = int_ceildiv(pi->tz1, comp->dz << levelnoz);\r
+                                               rpx = res->pdx + levelnox;\r
+                                               rpy = res->pdy + levelnoy;\r
+                                               rpz = res->pdz + levelnoz;\r
+                                               if ((!(pi->x % (comp->dx << rpx) == 0) || (pi->x == pi->tx0 && (trx0 << levelnox) % (1 << rpx)))) {\r
+                                                       continue;\r
+                                               }\r
+                                               if ((!(pi->y % (comp->dy << rpy) == 0) || (pi->y == pi->ty0 && (try0 << levelnoy) % (1 << rpx)))) {\r
+                                                       continue;\r
+                                               }\r
+                                               if ((!(pi->z % (comp->dz << rpz) == 0) || (pi->z == pi->tz0 && (trz0 << levelnoz) % (1 << rpx)))) {\r
+                                                       continue;\r
+                                               }\r
+                                               if ((res->prctno[0]==0)||(res->prctno[1]==0)||(res->prctno[2]==0)) continue;\r
+                                               \r
+                                               if ((trx0==trx1)||(try0==try1)||(trz0==trz1)) continue;\r
+                                               \r
+                                               prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelnox), res->pdx) \r
+                                                       - int_floordivpow2(trx0, res->pdx);\r
+                                               prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelnoy), res->pdy) \r
+                                                       - int_floordivpow2(try0, res->pdy);\r
+                                               prck = int_floordivpow2(int_ceildiv(pi->z, comp->dz << levelnoz), res->pdz) \r
+                                                       - int_floordivpow2(trz0, res->pdz);\r
+                                               pi->precno = prci + prcj * res->prctno[0] + prck * res->prctno[0] * res->prctno[1];\r
+                                               for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {\r
+                                                       index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p;\r
+                                                       if (!pi->include[index]) {\r
+                                                               pi->include[index] = 1;\r
+                                                               return true;\r
+                                                       }\r
+       LABEL_SKIP:;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+       \r
+       return false;\r
+}\r
+\r
+/* \r
+==========================================================\r
+   Packet iterator interface\r
+==========================================================\r
+*/\r
+\r
+opj_pi_iterator_t *pi_create(opj_volume_t *volume, opj_cp_t *cp, int tileno) {\r
+       int p, q, r;\r
+       int compno, resno, pino;\r
+       opj_pi_iterator_t *pi = NULL;\r
+       opj_tcp_t *tcp = NULL;\r
+       opj_tccp_t *tccp = NULL;\r
+       size_t array_size;\r
+       \r
+       tcp = &cp->tcps[tileno];\r
+\r
+       array_size = (tcp->numpocs + 1) * sizeof(opj_pi_iterator_t);\r
+       pi = (opj_pi_iterator_t *) opj_malloc(array_size);\r
+       if(!pi) {\r
+               fprintf(stdout,"[ERROR] Malloc of opj_pi_iterator failed \n");\r
+               return NULL;\r
+       }\r
+       \r
+       for (pino = 0; pino < tcp->numpocs + 1; pino++) {       /* change */\r
+               int maxres = 0;\r
+               int maxprec = 0;\r
+               p = tileno % cp->tw;\r
+               q = tileno / cp->tw;\r
+               r = tileno / (cp->tw * cp->th);\r
+\r
+               pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, volume->x0);\r
+               pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, volume->y0);\r
+               pi[pino].tz0 = int_max(cp->tz0 + r * cp->tdz, volume->z0);\r
+               pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, volume->x1);\r
+               pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, volume->y1);\r
+               pi[pino].tz1 = int_min(cp->tz0 + (r + 1) * cp->tdz, volume->z1);\r
+               pi[pino].numcomps = volume->numcomps;\r
+\r
+               array_size = volume->numcomps * sizeof(opj_pi_comp_t);\r
+               pi[pino].comps = (opj_pi_comp_t *) opj_malloc(array_size);\r
+               if(!pi[pino].comps) {\r
+                       fprintf(stdout,"[ERROR] Malloc of opj_pi_comp failed \n");\r
+                       pi_destroy(pi, cp, tileno);\r
+                       return NULL;\r
+               }\r
+               memset(pi[pino].comps, 0, array_size);\r
+               \r
+               for (compno = 0; compno < pi->numcomps; compno++) {\r
+                       int tcx0, tcx1, tcy0, tcy1, tcz0, tcz1;\r
+                       int i;\r
+                       opj_pi_comp_t *comp = &pi[pino].comps[compno];\r
+                       tccp = &tcp->tccps[compno];\r
+                       \r
+                       comp->dx = volume->comps[compno].dx;\r
+                       comp->dy = volume->comps[compno].dy;\r
+                       comp->dz = volume->comps[compno].dz;\r
+                       for (i = 0; i < 3; i++) {\r
+                               comp->numresolution[i] = tccp->numresolution[i];\r
+                               if (comp->numresolution[i] > maxres) {\r
+                                       maxres = comp->numresolution[i];\r
+                               }\r
+                       }\r
+                       array_size = comp->numresolution[0] * sizeof(opj_pi_resolution_t);\r
+                       comp->resolutions =     (opj_pi_resolution_t *) opj_malloc(array_size);\r
+                       if(!comp->resolutions) {\r
+                               fprintf(stdout,"[ERROR] Malloc of opj_pi_resolution failed \n");\r
+                               pi_destroy(pi, cp, tileno);\r
+                               return NULL;\r
+                       }\r
+\r
+                       tcx0 = int_ceildiv(pi->tx0, comp->dx);\r
+                       tcy0 = int_ceildiv(pi->ty0, comp->dy);\r
+                       tcz0 = int_ceildiv(pi->tz0, comp->dz);\r
+                       tcx1 = int_ceildiv(pi->tx1, comp->dx);\r
+                       tcy1 = int_ceildiv(pi->ty1, comp->dy);\r
+                       tcz1 = int_ceildiv(pi->tz1, comp->dz);\r
+                       \r
+                       for (resno = 0; resno < comp->numresolution[0]; resno++) {\r
+                               int levelnox, levelnoy, levelnoz, diff;\r
+                               int rx0, ry0, rz0, rx1, ry1, rz1;\r
+                               int px0, py0, pz0, px1, py1, pz1;\r
+                               opj_pi_resolution_t *res = &comp->resolutions[resno];\r
+                               if (tccp->csty & J3D_CCP_CSTY_PRT) {\r
+                                       res->pdx = tccp->prctsiz[0][resno];\r
+                                       res->pdy = tccp->prctsiz[1][resno];\r
+                                       res->pdz = tccp->prctsiz[2][resno];\r
+                               } else {\r
+                                       res->pdx = 15;\r
+                                       res->pdy = 15;\r
+                                       res->pdz = 15;\r
+                               }\r
+                               levelnox = comp->numresolution[0] - 1 - resno;\r
+                               levelnoy = comp->numresolution[1] - 1 - resno;\r
+                levelnoz = comp->numresolution[2] - 1 - resno;\r
+                               if (levelnoz < 0) levelnoz = 0; \r
+                               diff = comp->numresolution[0] - comp->numresolution[2];\r
+\r
+                               rx0 = int_ceildivpow2(tcx0, levelnox);\r
+                               ry0 = int_ceildivpow2(tcy0, levelnoy);\r
+                               rz0 = int_ceildivpow2(tcz0, levelnoz);\r
+                               rx1 = int_ceildivpow2(tcx1, levelnox);\r
+                               ry1 = int_ceildivpow2(tcy1, levelnoy);\r
+                               rz1 = int_ceildivpow2(tcz1, levelnoz);\r
+                               px0 = int_floordivpow2(rx0, res->pdx) << res->pdx;\r
+                               py0 = int_floordivpow2(ry0, res->pdy) << res->pdy;\r
+                               pz0 = int_floordivpow2(rz0, res->pdz) << res->pdz;\r
+                               px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx;\r
+                               py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy;\r
+                               pz1 = int_ceildivpow2(rz1, res->pdz) << res->pdz;\r
+                               res->prctno[0] = (rx0==rx1)? 0 : ((px1 - px0) >> res->pdx);\r
+                               res->prctno[1] = (ry0==ry1)? 0 : ((py1 - py0) >> res->pdy);\r
+                               res->prctno[2] = (rz0==rz1)? 0 : ((pz1 - pz0) >> res->pdz);\r
+\r
+                               if (res->prctno[0]*res->prctno[1]*res->prctno[2] > maxprec) {\r
+                                       maxprec = res->prctno[0]*res->prctno[1]*res->prctno[2];\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               tccp = &tcp->tccps[0];\r
+               pi[pino].step_p = 1;\r
+               pi[pino].step_c = maxprec * pi[pino].step_p;\r
+               pi[pino].step_r = volume->numcomps * pi[pino].step_c;\r
+               pi[pino].step_l = maxres * pi[pino].step_r;\r
+               \r
+               if (pino == 0) {\r
+                       array_size = volume->numcomps * maxres * tcp->numlayers * maxprec * sizeof(short int);\r
+                       pi[pino].include = (short int *) opj_malloc(array_size);\r
+                       if(!pi[pino].include) {\r
+                               fprintf(stdout,"[ERROR] Malloc of pi[pino].include failed \n");\r
+                               pi_destroy(pi, cp, tileno);\r
+                               return NULL;\r
+                       }\r
+               }\r
+               else {\r
+                       pi[pino].include = pi[pino - 1].include;\r
+               }\r
+               \r
+               if (tcp->POC == 0) {\r
+                       pi[pino].first = 1;\r
+                       pi[pino].poc.resno0 = 0;\r
+                       pi[pino].poc.compno0 = 0;\r
+                       pi[pino].poc.layno1 = tcp->numlayers;\r
+                       pi[pino].poc.resno1 = maxres;\r
+                       pi[pino].poc.compno1 = volume->numcomps;\r
+                       pi[pino].poc.prg = tcp->prg;\r
+               } else {\r
+                       pi[pino].first = 1;\r
+                       pi[pino].poc.resno0 = tcp->pocs[pino].resno0;\r
+                       pi[pino].poc.compno0 = tcp->pocs[pino].compno0;\r
+                       pi[pino].poc.layno1 = tcp->pocs[pino].layno1;\r
+                       pi[pino].poc.resno1 = tcp->pocs[pino].resno1;\r
+                       pi[pino].poc.compno1 = tcp->pocs[pino].compno1;\r
+                       pi[pino].poc.prg = tcp->pocs[pino].prg;\r
+               }\r
+       }\r
+       \r
+       return pi;\r
+}\r
+\r
+void pi_destroy(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno) {\r
+       int compno, pino;\r
+       opj_tcp_t *tcp = &cp->tcps[tileno];\r
+       if(pi) {\r
+               for (pino = 0; pino < tcp->numpocs + 1; pino++) {       \r
+                       if(pi[pino].comps) {\r
+                               for (compno = 0; compno < pi->numcomps; compno++) {\r
+                                       opj_pi_comp_t *comp = &pi[pino].comps[compno];\r
+                                       if(comp->resolutions) {\r
+                                               opj_free(comp->resolutions);\r
+                                       }\r
+                               }\r
+                               opj_free(pi[pino].comps);\r
+                       }\r
+               }\r
+               if(pi->include) {\r
+                       opj_free(pi->include);\r
+               }\r
+               opj_free(pi);\r
+       }\r
+}\r
+\r
+bool pi_next(opj_pi_iterator_t * pi) {\r
+       switch (pi->poc.prg) {\r
+               case LRCP:\r
+                       return pi_next_lrcp(pi);\r
+               case RLCP:\r
+                       return pi_next_rlcp(pi);\r
+               case RPCL:\r
+                       return pi_next_rpcl(pi);\r
+               case PCRL:\r
+                       return pi_next_pcrl(pi);\r
+               case CPRL:\r
+                       return pi_next_cprl(pi);\r
+       }\r
+       \r
+       return false;\r
+}\r
+\r
diff --git a/src/lib/openjp3d/pi.h b/src/lib/openjp3d/pi.h
new file mode 100755 (executable)
index 0000000..1edcc5f
--- /dev/null
@@ -0,0 +1,145 @@
+/*\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) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain\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 __PI_H\r
+#define __PI_H\r
+/**\r
+@file pi.h\r
+@brief Implementation of a packet iterator (PI)\r
+\r
+The functions in PI.C have for goal to realize a packet iterator that permits to get the next\r
+packet following the progression order and change of it. The functions in PI.C are used\r
+by some function in T2.C.\r
+*/\r
+\r
+/** @defgroup PI PI - Implementation of a packet iterator */\r
+/*@{*/\r
+\r
+/**\r
+Packet iterator : resolution level information \r
+*/\r
+typedef struct opj_pi_resolution {\r
+/** Size of precints in horizontal axis */\r
+       int pdx;\r
+/** Size of precints in vertical axis */\r
+       int pdy;\r
+/** Size of precints in axial axis */\r
+       int pdz;\r
+/** Number of precints in each axis */\r
+       int prctno[3];                          \r
+} opj_pi_resolution_t;\r
+\r
+/**\r
+Packet iterator : component information \r
+*/\r
+typedef struct opj_pi_comp {\r
+/** Size in horizontal axis */\r
+       int dx;\r
+/** Size in vertical axis */\r
+       int dy;\r
+/** Size in axial axis */\r
+       int dz;\r
+/** Number of resolution levels */\r
+       int numresolution[3];                   \r
+/** Packet iterator : resolution level information */\r
+       opj_pi_resolution_t *resolutions;\r
+} opj_pi_comp_t;\r
+\r
+/** \r
+Packet iterator \r
+*/\r
+typedef struct opj_pi_iterator {\r
+/** precise if the packet has been already used (usefull for progression order change) */\r
+       short int *include;             \r
+/** layer step used to localize the packet in the include vector */\r
+       int step_l;             \r
+/** resolution step used to localize the packet in the include vector */\r
+       int step_r;     \r
+/** component step used to localize the packet in the include vector */\r
+       int step_c;                             \r
+/** precinct step used to localize the packet in the include vector */\r
+       int step_p;                             \r
+/** component that identify the packet */\r
+       int compno;                             \r
+/** resolution that identify the packet */\r
+       int resno;                              \r
+/** precinct that identify the packet */\r
+       int precno;                             \r
+/** layer that identify the packet */\r
+       int layno;                              \r
+/** 0 if the first packet */\r
+       int first;                              \r
+/** progression order change information */\r
+       opj_poc_t poc;                  \r
+/**    Packet iterator : component information */\r
+opj_pi_comp_t *comps;\r
+       \r
+       int numcomps;\r
+       int tx0, ty0, tz0;\r
+       int tx1, ty1, tz1;\r
+       int x, y, z;\r
+       int dx, dy, dz;\r
+} opj_pi_iterator_t;\r
+\r
+/** @name Funciones generales */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Create a packet iterator\r
+@param volume Raw volume for which the packets will be listed\r
+@param cp Coding parameters\r
+@param tileno Number that identifies the tile for which to list the packets\r
+@return Returns a packet iterator that points to the first packet of the tile\r
+@see pi_destroy\r
+*/\r
+opj_pi_iterator_t *pi_create(opj_volume_t * volume, opj_cp_t * cp, int tileno);\r
+\r
+/**\r
+Destroy a packet iterator\r
+@param pi Previously created packet iterator\r
+@param cp Coding parameters\r
+@param tileno Number that identifies the tile for which the packets were listed\r
+@see pi_create\r
+*/\r
+void pi_destroy(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno);\r
+\r
+/**\r
+Modify the packet iterator to point to the next packet\r
+@param pi Packet iterator to modify\r
+@return Returns false if pi pointed to the last packet or else returns true \r
+*/\r
+bool pi_next(opj_pi_iterator_t * pi);\r
+/* ----------------------------------------------------------------------- */\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* __PI_H */\r
diff --git a/src/lib/openjp3d/raw.c b/src/lib/openjp3d/raw.c
new file mode 100755 (executable)
index 0000000..b6a5810
--- /dev/null
@@ -0,0 +1,86 @@
+/*\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
+ * 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 "opj_includes.h"\r
+\r
+/* \r
+==========================================================\r
+   local functions\r
+==========================================================\r
+*/\r
+\r
+\r
+/* \r
+==========================================================\r
+   RAW encoding interface\r
+==========================================================\r
+*/\r
+\r
+opj_raw_t* raw_create() {\r
+       opj_raw_t *raw = (opj_raw_t*)opj_malloc(sizeof(opj_raw_t));\r
+       return raw;\r
+}\r
+\r
+void raw_destroy(opj_raw_t *raw) {\r
+       if(raw) {\r
+               opj_free(raw);\r
+       }\r
+}\r
+\r
+int raw_numbytes(opj_raw_t *raw) {\r
+       return raw->bp - raw->start;\r
+}\r
+\r
+void raw_init_dec(opj_raw_t *raw, unsigned char *bp, int len) {\r
+       raw->start = bp;\r
+       raw->lenmax = len;\r
+       raw->len = 0;\r
+       raw->c = 0;\r
+       raw->ct = 0;\r
+}\r
+\r
+int raw_decode(opj_raw_t *raw) {\r
+       int d;\r
+       if (raw->ct == 0) {\r
+               raw->ct = 8;\r
+               if (raw->len == raw->lenmax) {\r
+                       raw->c = 0xff;\r
+               } else {\r
+                       if (raw->c == 0xff) {\r
+                               raw->ct = 7;\r
+                       }\r
+                       raw->c = *(raw->start + raw->len);\r
+                       raw->len++;\r
+               }\r
+       }\r
+       raw->ct--;\r
+       d = (raw->c >> raw->ct) & 0x01;\r
+       \r
+       return d;\r
+}\r
+\r
diff --git a/src/lib/openjp3d/raw.h b/src/lib/openjp3d/raw.h
new file mode 100755 (executable)
index 0000000..c26546a
--- /dev/null
@@ -0,0 +1,99 @@
+/*\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
+ * 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 __RAW_H\r
+#define __RAW_H\r
+/**\r
+@file raw.h\r
+@brief Implementation of operations for raw encoding (RAW)\r
+\r
+The functions in RAW.C have for goal to realize the operation of raw encoding linked\r
+with the corresponding mode switch.\r
+*/\r
+\r
+/** @defgroup RAW RAW - Implementation of operations for raw encoding */\r
+/*@{*/\r
+\r
+/**\r
+RAW encoding operations\r
+*/\r
+typedef struct opj_raw {\r
+/** Temporary buffer where bits are coded or decoded */\r
+       unsigned char c;                \r
+/** Number of bits already read or free to write */\r
+       unsigned int ct;                \r
+/** Maximum length to decode */\r
+       unsigned int lenmax;    \r
+/** Length decoded */\r
+       unsigned int len;               \r
+/** Pointer to the current position in the buffer */\r
+       unsigned char *bp;              \r
+/** Pointer to the start of the buffer */\r
+       unsigned char *start;   \r
+/** Pointer to the end of the buffer */\r
+       unsigned char *end;             \r
+} opj_raw_t;\r
+\r
+/** @name Funciones generales */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Create a new RAW handle \r
+@return Returns a new RAW handle if successful, returns NULL otherwise\r
+*/\r
+opj_raw_t* raw_create();\r
+/**\r
+Destroy a previously created RAW handle\r
+@param raw RAW handle to destroy\r
+*/\r
+void raw_destroy(opj_raw_t *raw);\r
+/**\r
+Return the number of bytes written/read since initialisation\r
+@param raw RAW handle to destroy\r
+@return Returns the number of bytes already encoded\r
+*/\r
+int raw_numbytes(opj_raw_t *raw);\r
+/**\r
+Initialize the decoder\r
+@param raw RAW handle\r
+@param bp Pointer to the start of the buffer from which the bytes will be read\r
+@param len Length of the input buffer\r
+*/\r
+void raw_init_dec(opj_raw_t *raw, unsigned char *bp, int len);\r
+/**\r
+Decode a symbol using raw-decoder. Cfr p.506 TAUBMAN\r
+@param raw RAW handle\r
+@return Returns the decoded symbol (0 or 1)\r
+*/\r
+int raw_decode(opj_raw_t *raw);\r
+/* ----------------------------------------------------------------------- */\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* __RAW_H */\r
diff --git a/src/lib/openjp3d/t1.c b/src/lib/openjp3d/t1.c
new file mode 100755 (executable)
index 0000000..db1d260
--- /dev/null
@@ -0,0 +1,1181 @@
+/*\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
+ * 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 "opj_includes.h"\r
+\r
+/** @defgroup T1 T1 - Implementation of the tier-1 coding */\r
+/*@{*/\r
+\r
+/** @name Local static functions */\r
+/*@{*/\r
+\r
+static int t1_getctxno_zc(opj_t1_t *t1, int f, int orient);\r
+static int t1_getctxno_sc(opj_t1_t *t1, int f);\r
+static int t1_getctxno_mag(opj_t1_t *t1, int f);\r
+static int t1_getspb(opj_t1_t *t1, int f);\r
+static int t1_getnmsedec_sig(opj_t1_t *t1, int x, int bitpos);\r
+static int t1_getnmsedec_ref(opj_t1_t *t1, int x, int bitpos);\r
+static void t1_updateflags(int *fp, int s);\r
+/**\r
+Encode significant pass\r
+*/\r
+static void t1_enc_sigpass_step(opj_t1_t *t1, int *fp, int *dp, int orient, int bpno, int one, int *nmsedec, char type, int vsc);\r
+/**\r
+Decode significant pass\r
+*/\r
+static void t1_dec_sigpass_step(opj_t1_t *t1, int *fp, int *dp, int orient, int oneplushalf, char type, int vsc);\r
+/**\r
+Encode significant pass\r
+*/\r
+static void t1_enc_sigpass(opj_t1_t *t1, int w, int h, int l, int bpno, int orient, int *nmsedec, char type, int cblksty);\r
+/**\r
+Decode significant pass\r
+*/\r
+static void t1_dec_sigpass(opj_t1_t *t1, int w, int h, int l, int bpno, int orient, char type, int cblksty);\r
+/**\r
+Encode refinement pass\r
+*/\r
+static void t1_enc_refpass_step(opj_t1_t *t1, int *fp, int *dp, int bpno, int one, int *nmsedec, char type, int vsc);\r
+/**\r
+Decode refinement pass\r
+*/\r
+static void t1_dec_refpass_step(opj_t1_t *t1, int *fp, int *dp, int poshalf, int neghalf, char type, int vsc);\r
+/**\r
+Encode refinement pass\r
+*/\r
+static void t1_enc_refpass(opj_t1_t *t1, int w, int h, int l, int bpno, int *nmsedec, char type, int cblksty);\r
+/**\r
+Decode refinement pass\r
+*/\r
+static void t1_dec_refpass(opj_t1_t *t1, int w, int h, int l, int bpno, char type, int cblksty);\r
+/**\r
+Encode clean-up pass\r
+*/\r
+static void t1_enc_clnpass_step(opj_t1_t *t1, int *fp, int *dp, int orient, int bpno, int one, int *nmsedec, int partial, int vsc);\r
+/**\r
+Decode clean-up pass\r
+*/\r
+static void t1_dec_clnpass_step(opj_t1_t *t1, int *fp, int *dp, int orient, int oneplushalf, int partial, int vsc);\r
+/**\r
+Encode clean-up pass\r
+*/\r
+static void t1_enc_clnpass(opj_t1_t *t1, int w, int h, int l, int bpno, int orient, int *nmsedec, int cblksty);\r
+/**\r
+Decode clean-up pass\r
+*/\r
+static void t1_dec_clnpass(opj_t1_t *t1, int w, int h, int l, int bpno, int orient, int cblksty);\r
+/**\r
+Encode 1 code-block\r
+@param t1 T1 handle\r
+@param cblk Code-block coding parameters\r
+@param orient\r
+@param compno Component number\r
+@param level\r
+@param dwtid\r
+@param stepsize\r
+@param cblksty Code-block style\r
+@param numcomps\r
+@param tile\r
+*/\r
+static void t1_encode_cblk(opj_t1_t *t1, opj_tcd_cblk_t * cblk, int orient, int compno, int level[3], int dwtid[3], double stepsize, int cblksty, int numcomps, opj_tcd_tile_t * tile);\r
+/**\r
+Decode 1 code-block\r
+@param t1 T1 handle\r
+@param cblk Code-block coding parameters\r
+@param orient\r
+@param roishift Region of interest shifting value\r
+@param cblksty Code-block style\r
+*/\r
+static void t1_decode_cblk(opj_t1_t *t1, opj_tcd_cblk_t * cblk, int orient, int roishift, int cblksty);\r
+\r
+static int t1_init_ctxno_zc(int f, int orient);\r
+static int t1_init_ctxno_sc(int f);\r
+static int t1_init_ctxno_mag(int f);\r
+static int t1_init_spb(int f);\r
+/**\r
+Initialize the look-up tables of the Tier-1 coder/decoder\r
+@param t1 T1 handle\r
+*/\r
+static void t1_init_luts(opj_t1_t *t1);\r
+\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+static int t1_getctxno_zc(opj_t1_t *t1, int f, int orient) {\r
+       return t1->lut_ctxno_zc[(orient << 8) | (f & T1_SIG_OTH)];\r
+}\r
+\r
+static int t1_getctxno_sc(opj_t1_t *t1, int f) {\r
+       return t1->lut_ctxno_sc[(f & (T1_SIG_PRIM | T1_SGN)) >> 4];\r
+}\r
+\r
+static int t1_getctxno_mag(opj_t1_t *t1, int f) {\r
+       return t1->lut_ctxno_mag[(f & T1_SIG_OTH) | (((f & T1_REFINE) != 0) << 11)];\r
+}\r
+\r
+static int t1_getspb(opj_t1_t *t1, int f) {\r
+       return t1->lut_spb[(f & (T1_SIG_PRIM | T1_SGN)) >> 4];\r
+}\r
+\r
+static int t1_getnmsedec_sig(opj_t1_t *t1, int x, int bitpos) {\r
+       if (bitpos > T1_NMSEDEC_FRACBITS) {\r
+               return t1->lut_nmsedec_sig[(x >> (bitpos - T1_NMSEDEC_FRACBITS)) & ((1 << T1_NMSEDEC_BITS) - 1)];\r
+       }\r
+       \r
+       return t1->lut_nmsedec_sig0[x & ((1 << T1_NMSEDEC_BITS) - 1)];\r
+}\r
+\r
+static int t1_getnmsedec_ref(opj_t1_t *t1, int x, int bitpos) {\r
+       if (bitpos > T1_NMSEDEC_FRACBITS) {\r
+               return t1->lut_nmsedec_ref[(x >> (bitpos - T1_NMSEDEC_FRACBITS)) & ((1 << T1_NMSEDEC_BITS) - 1)];\r
+       }\r
+\r
+    return t1->lut_nmsedec_ref0[x & ((1 << T1_NMSEDEC_BITS) - 1)];\r
+}\r
+\r
+static void t1_updateflags(int *fp, int s) {\r
+       int *np = fp - (T1_MAXCBLKW + 2);\r
+       int *sp = fp + (T1_MAXCBLKW + 2);\r
+       np[-1] |= T1_SIG_SE;\r
+       np[1] |= T1_SIG_SW;\r
+       sp[-1] |= T1_SIG_NE;\r
+       sp[1] |= T1_SIG_NW;\r
+       *np |= T1_SIG_S;\r
+       *sp |= T1_SIG_N;\r
+       fp[-1] |= T1_SIG_E;\r
+       fp[1] |= T1_SIG_W;\r
+       if (s) {\r
+               *np |= T1_SGN_S;\r
+               *sp |= T1_SGN_N;\r
+               fp[-1] |= T1_SGN_E;\r
+               fp[1] |= T1_SGN_W;\r
+       }\r
+}\r
+\r
+static void t1_enc_sigpass_step(opj_t1_t *t1, int *fp, int *dp, int orient, int bpno, int one, int *nmsedec, char type, int vsc) {\r
+       int v, flag;\r
+       \r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       flag = vsc ? ((*fp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*fp);\r
+       if ((flag & T1_SIG_OTH) && !(flag & (T1_SIG | T1_VISIT))) {\r
+               v = int_abs(*dp) & one ? 1 : 0;\r
+               if (type == T1_TYPE_RAW) {      /* BYPASS/LAZY MODE */\r
+                       mqc_setcurctx(mqc, t1_getctxno_zc(t1, flag, orient));   /* ESSAI */\r
+                       mqc_bypass_enc(mqc, v);\r
+               } else {\r
+                       mqc_setcurctx(mqc, t1_getctxno_zc(t1, flag, orient));\r
+                       mqc_encode(mqc, v);\r
+               }\r
+               if (v) {\r
+                       v = *dp < 0 ? 1 : 0;\r
+                       *nmsedec +=     t1_getnmsedec_sig(t1, int_abs(*dp), bpno + T1_NMSEDEC_FRACBITS);\r
+                       if (type == T1_TYPE_RAW) {      /* BYPASS/LAZY MODE */\r
+                               mqc_setcurctx(mqc, t1_getctxno_sc(t1, flag));   /* ESSAI */\r
+                               mqc_bypass_enc(mqc, v);\r
+                       } else {\r
+                               mqc_setcurctx(mqc, t1_getctxno_sc(t1, flag));\r
+                               mqc_encode(mqc, v ^ t1_getspb(t1, flag));\r
+                       }\r
+                       t1_updateflags(fp, v);\r
+                       *fp |= T1_SIG;\r
+               }\r
+               *fp |= T1_VISIT;\r
+       }\r
+}\r
+\r
+static void t1_dec_sigpass_step(opj_t1_t *t1, int *fp, int *dp, int orient, int oneplushalf, char type, int vsc) {\r
+       int v, flag;\r
+       \r
+       opj_raw_t *raw = t1->raw;       /* RAW component */\r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       flag = vsc ? ((*fp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*fp);\r
+       if ((flag & T1_SIG_OTH) && !(flag & (T1_SIG | T1_VISIT))) {\r
+               if (type == T1_TYPE_RAW) {\r
+                       if (raw_decode(raw)) {\r
+                               v = raw_decode(raw);    /* ESSAI */\r
+                               *dp = v ? -oneplushalf : oneplushalf;\r
+                               t1_updateflags(fp, v);\r
+                               *fp |= T1_SIG;\r
+                       }\r
+               } else {\r
+                       mqc_setcurctx(mqc, t1_getctxno_zc(t1, flag, orient));\r
+                       if (mqc_decode(mqc)) {\r
+                               mqc_setcurctx(mqc, t1_getctxno_sc(t1, flag));\r
+                               v = mqc_decode(mqc) ^ t1_getspb(t1, flag);\r
+                               *dp = v ? -oneplushalf : oneplushalf;\r
+                               t1_updateflags(fp, v);\r
+                               *fp |= T1_SIG;\r
+                       }\r
+               }\r
+               *fp |= T1_VISIT;\r
+       }\r
+}                              /* VSC and  BYPASS by Antonin */\r
+\r
+static void t1_enc_sigpass(opj_t1_t *t1, int w, int h, int l, int bpno, int orient, int *nmsedec, char type, int cblksty) {\r
+       int i, j, k, m, one, vsc;\r
+       *nmsedec = 0;\r
+       one = 1 << (bpno + T1_NMSEDEC_FRACBITS);\r
+       for (m = 0; m < l; m++) {\r
+       for (k = 0; k < h; k += 4) {\r
+               for (i = 0; i < w; i++) {\r
+                       for (j = k; j < k + 4 && j < h; j++) {\r
+                               vsc = ((cblksty & J3D_CCP_CBLKSTY_VSC) && (j == k + 3 || j == h - 1)) ? 1 : 0;\r
+                               t1_enc_sigpass_step(t1, &t1->flags[1 + m][1 + j][1 + i], &t1->data[m][j][i], orient, bpno, one, nmsedec, type, vsc);\r
+                       }\r
+               }\r
+       }\r
+       }\r
+}\r
+\r
+static void t1_dec_sigpass(opj_t1_t *t1, int w, int h, int l, int bpno, int orient, char type, int cblksty) {\r
+       int i, j, k, m, one, half, oneplushalf, vsc;\r
+       one = 1 << bpno;\r
+       half = one >> 1;\r
+       oneplushalf = one | half;\r
+       for (m = 0; m < l; m++) {\r
+       for (k = 0; k < h; k += 4) {\r
+               for (i = 0; i < w; i++) {\r
+                       for (j = k; j < k + 4 && j < h; j++) {\r
+                               vsc = ((cblksty & J3D_CCP_CBLKSTY_VSC) && (j == k + 3 || j == h - 1)) ? 1 : 0;\r
+                               t1_dec_sigpass_step(t1, &t1->flags[1 + m][1 + j][1 + i], &t1->data[m][j][i], orient, oneplushalf, type, vsc);\r
+                       }\r
+               }\r
+       }\r
+       }\r
+}                              /* VSC and  BYPASS by Antonin */\r
+\r
+static void t1_enc_refpass_step(opj_t1_t *t1, int *fp, int *dp, int bpno, int one, int *nmsedec, char type, int vsc) {\r
+       int v, flag;\r
+       \r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       flag = vsc ? ((*fp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*fp);\r
+       if ((flag & (T1_SIG | T1_VISIT)) == T1_SIG) {\r
+               *nmsedec += t1_getnmsedec_ref(t1, int_abs(*dp), bpno + T1_NMSEDEC_FRACBITS);\r
+               v = int_abs(*dp) & one ? 1 : 0;\r
+               if (type == T1_TYPE_RAW) {      /* BYPASS/LAZY MODE */\r
+                       mqc_setcurctx(mqc, t1_getctxno_mag(t1, flag));  /* ESSAI */\r
+                       mqc_bypass_enc(mqc, v);\r
+               } else {\r
+                       mqc_setcurctx(mqc, t1_getctxno_mag(t1, flag));\r
+                       mqc_encode(mqc, v);\r
+               }\r
+               *fp |= T1_REFINE;\r
+       }\r
+}\r
+\r
+static void t1_dec_refpass_step(opj_t1_t *t1, int *fp, int *dp, int poshalf, int neghalf, char type, int vsc) {\r
+       int v, t, flag;\r
+       \r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       opj_raw_t *raw = t1->raw;       /* RAW component */\r
+       \r
+       flag = vsc ? ((*fp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*fp);\r
+       if ((flag & (T1_SIG | T1_VISIT)) == T1_SIG) {\r
+               if (type == T1_TYPE_RAW) {\r
+                       mqc_setcurctx(mqc, t1_getctxno_mag(t1, flag));  /* ESSAI */\r
+                       v = raw_decode(raw);\r
+               } else {\r
+                       mqc_setcurctx(mqc, t1_getctxno_mag(t1, flag));\r
+                       v = mqc_decode(mqc);\r
+               }\r
+               t = v ? poshalf : neghalf;\r
+               *dp += *dp < 0 ? -t : t;\r
+               *fp |= T1_REFINE;\r
+       }\r
+}                              /* VSC and  BYPASS by Antonin  */\r
+\r
+static void t1_enc_refpass(opj_t1_t *t1, int w, int h, int l, int bpno, int *nmsedec, char type, int cblksty) {\r
+       int i, j, k, m, one, vsc;\r
+       *nmsedec = 0;\r
+       one = 1 << (bpno + T1_NMSEDEC_FRACBITS);\r
+       for (m = 0; m < l; m++) {\r
+               for (k = 0; k < h; k += 4) {\r
+               for (i = 0; i < w; i++) {\r
+                       for (j = k; j < k + 4 && j < h; j++) {\r
+                               vsc = ((cblksty & J3D_CCP_CBLKSTY_VSC) && (j == k + 3 || j == h - 1)) ? 1 : 0;\r
+                               t1_enc_refpass_step(t1, &t1->flags[1 + m][1 + j][1 + i], &t1->data[m][j][i], bpno, one, nmsedec, type, vsc);\r
+                       }\r
+               }\r
+       }\r
+       }\r
+}\r
+\r
+static void t1_dec_refpass(opj_t1_t *t1, int w, int h, int l, int bpno, char type, int cblksty) {\r
+       int i, j, k, m, one, poshalf, neghalf;\r
+       int vsc;\r
+       one = 1 << bpno;\r
+       poshalf = one >> 1;\r
+       neghalf = bpno > 0 ? -poshalf : -1;\r
+       for (m = 0; m < l; m++) {\r
+               for (k = 0; k < h; k += 4) {\r
+               for (i = 0; i < w; i++) {\r
+                       for (j = k; j < k + 4 && j < h; j++) {\r
+                               vsc = ((cblksty & J3D_CCP_CBLKSTY_VSC) && (j == k + 3 || j == h - 1)) ? 1 : 0;\r
+                               t1_dec_refpass_step(t1, &t1->flags[1 + m][1 + j][1 + i], &t1->data[m][j][i], poshalf, neghalf, type, vsc);\r
+                       }\r
+               }\r
+       }\r
+       }\r
+}                              /* VSC and  BYPASS by Antonin */\r
+\r
+static void t1_enc_clnpass_step(opj_t1_t *t1, int *fp, int *dp, int orient, int bpno, int one, int *nmsedec, int partial, int vsc) {\r
+       int v, flag;\r
+       \r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       flag = vsc ? ((*fp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*fp);\r
+       if (partial) {\r
+               goto LABEL_PARTIAL;\r
+       }\r
+       if (!(*fp & (T1_SIG | T1_VISIT))) {\r
+               mqc_setcurctx(mqc, t1_getctxno_zc(t1, flag, orient));\r
+               v = int_abs(*dp) & one ? 1 : 0;\r
+               mqc_encode(mqc, v);\r
+               if (v) {\r
+LABEL_PARTIAL:\r
+                       *nmsedec += t1_getnmsedec_sig(t1, int_abs(*dp), bpno + T1_NMSEDEC_FRACBITS);\r
+                       mqc_setcurctx(mqc, t1_getctxno_sc(t1, flag));\r
+                       v = *dp < 0 ? 1 : 0;\r
+                       mqc_encode(mqc, v ^ t1_getspb(t1, flag));\r
+                       t1_updateflags(fp, v);\r
+                       *fp |= T1_SIG;\r
+               }\r
+       }\r
+       *fp &= ~T1_VISIT;\r
+}\r
+\r
+static void t1_dec_clnpass_step(opj_t1_t *t1, int *fp, int *dp, int orient, int oneplushalf, int partial, int vsc) {\r
+       int v, flag;\r
+       \r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       flag = vsc ? ((*fp) & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) : (*fp);\r
+       if (partial) {\r
+               goto LABEL_PARTIAL;\r
+       }\r
+       if (!(flag & (T1_SIG | T1_VISIT))) {\r
+               mqc_setcurctx(mqc, t1_getctxno_zc(t1, flag, orient));\r
+               if (mqc_decode(mqc)) {\r
+LABEL_PARTIAL:\r
+                       mqc_setcurctx(mqc, t1_getctxno_sc(t1, flag));\r
+                       v = mqc_decode(mqc) ^ t1_getspb(t1, flag);\r
+                       *dp = v ? -oneplushalf : oneplushalf;\r
+                       t1_updateflags(fp, v);\r
+                       *fp |= T1_SIG;\r
+               }\r
+       }\r
+       *fp &= ~T1_VISIT;\r
+}                              /* VSC and  BYPASS by Antonin */\r
+\r
+static void t1_enc_clnpass(opj_t1_t *t1, int w, int h, int l, int bpno, int orient, int *nmsedec, int cblksty) {\r
+       int i, j, k, m, one, agg, runlen, vsc;\r
+       \r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       *nmsedec = 0;\r
+       one = 1 << (bpno + T1_NMSEDEC_FRACBITS);\r
+       for (m = 0; m < l; m++) {\r
+               for (k = 0; k < h; k += 4) {\r
+                       for (i = 0; i < w; i++) {\r
+                               if (k + 3 < h) {\r
+                                       if (cblksty & J3D_CCP_CBLKSTY_VSC) {\r
+                                               agg = !(t1->flags[1 + m][1 + k][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH)\r
+                                                       || t1->flags[1 + m][1 + k + 1][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH)\r
+                                                       || t1->flags[1 + m][1 + k + 2][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH)\r
+                                                       || (t1->flags[1 + m][1 + k + 3][1 + i] \r
+                                                       & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) & (T1_SIG | T1_VISIT | T1_SIG_OTH));\r
+                                       } else {\r
+                                               agg = !(t1->flags[1 + m][1 + k][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH)\r
+                                                       || t1->flags[1 + m][1 + k + 1][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH)\r
+                                                       || t1->flags[1 + m][1 + k + 2][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH)\r
+                                                       || t1->flags[1 + m][1 + k + 3][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH));\r
+                                       }\r
+                               } else {\r
+                                       agg = 0;\r
+                               }\r
+                               if (agg) {\r
+                                       for (runlen = 0; runlen < 4; runlen++) {\r
+                                               if (int_abs(t1->data[m][k + runlen][i]) & one)\r
+                                                       break;\r
+                                       }\r
+                                       mqc_setcurctx(mqc, T1_CTXNO_AGG);\r
+                                       mqc_encode(mqc, runlen != 4);\r
+                                       if (runlen == 4) {\r
+                                               continue;\r
+                                       }\r
+                                       mqc_setcurctx(mqc, T1_CTXNO_UNI);\r
+                                       mqc_encode(mqc, runlen >> 1);\r
+                                       mqc_encode(mqc, runlen & 1);\r
+                               } else {\r
+                                       runlen = 0;\r
+                               }\r
+                               for (j = k + runlen; j < k + 4 && j < h; j++) {\r
+                                       vsc = ((cblksty & J3D_CCP_CBLKSTY_VSC) && (j == k + 3 || j == h - 1)) ? 1 : 0;\r
+                                       t1_enc_clnpass_step(t1, &(t1->flags[1 + m][1 + j][1 + i]), &(t1->data[m][j][i]), orient, bpno, one, nmsedec, agg && (j == k + runlen), vsc);\r
+                               }\r
+                       }\r
+       }\r
+       }\r
+}\r
+\r
+static void t1_dec_clnpass(opj_t1_t *t1, int w, int h, int l, int bpno, int orient, int cblksty) {\r
+       int i, j, k, m, one, half, oneplushalf, agg, runlen, vsc;\r
+       int segsym = cblksty & J3D_CCP_CBLKSTY_SEGSYM;\r
+       \r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       one = 1 << bpno;\r
+       half = one >> 1;\r
+       oneplushalf = one | half;\r
+       for (m = 0; m < l; m++) {\r
+               for (k = 0; k < h; k += 4) {\r
+               for (i = 0; i < w; i++) {\r
+                       if (k + 3 < h) {\r
+                               if (cblksty & J3D_CCP_CBLKSTY_VSC) {\r
+                                       agg = !(t1->flags[1 + m][1 + k][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH)\r
+                                               || t1->flags[1 + m][1 + k + 1][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH)\r
+                                               || t1->flags[1 + m][1 + k + 2][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH)\r
+                                               || (t1->flags[1 + m][1 + k + 3][1 + i] \r
+                                               & (~(T1_SIG_S | T1_SIG_SE | T1_SIG_SW | T1_SGN_S))) & (T1_SIG | T1_VISIT | T1_SIG_OTH));\r
+                               } else {\r
+                                       agg = !(t1->flags[1 + m][1 + k][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH)\r
+                                               || t1->flags[1 + m][1 + k + 1][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH)\r
+                                               || t1->flags[1 + m][1 + k + 2][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH)\r
+                                               || t1->flags[1 + m][1 + k + 3][1 + i] & (T1_SIG | T1_VISIT | T1_SIG_OTH));\r
+                               }\r
+                       } else {\r
+                               agg = 0;\r
+                       }\r
+                       if (agg) {\r
+                               mqc_setcurctx(mqc, T1_CTXNO_AGG);\r
+                               if (!mqc_decode(mqc)) {\r
+                                       continue;\r
+                               }\r
+                               mqc_setcurctx(mqc, T1_CTXNO_UNI);\r
+                               runlen = mqc_decode(mqc);\r
+                               runlen = (runlen << 1) | mqc_decode(mqc);\r
+                       } else {\r
+                               runlen = 0;\r
+                       }\r
+                       for (j = k + runlen; j < k + 4 && j < h; j++) {\r
+                               vsc = ((cblksty & J3D_CCP_CBLKSTY_VSC) && (j == k + 3 || j == h - 1)) ? 1 : 0;\r
+                               t1_dec_clnpass_step(t1, &t1->flags[1 + m][1 + j][1 + i], &t1->data[m][j][i], orient, oneplushalf, agg && (j == k + runlen), vsc);\r
+                       }\r
+               }\r
+       }\r
+       }\r
+       if (segsym) {\r
+               int v = 0;\r
+               mqc_setcurctx(mqc, T1_CTXNO_UNI);\r
+               v = mqc_decode(mqc);\r
+               v = (v << 1) | mqc_decode(mqc);\r
+               v = (v << 1) | mqc_decode(mqc);\r
+               v = (v << 1) | mqc_decode(mqc);\r
+               /*\r
+               if (v!=0xa) {\r
+                       opj_event_msg(t1->cinfo, EVT_WARNING, "Bad segmentation symbol %x\n", v);\r
+               } \r
+               */\r
+       }\r
+}                              /* VSC and  BYPASS by Antonin */\r
+\r
+\r
+static void t1_encode_cblk(opj_t1_t *t1, opj_tcd_cblk_t * cblk, int orient, int compno, int level[3], int dwtid[3], double stepsize, int cblksty, int numcomps, opj_tcd_tile_t * tile) {\r
+       int i, j, k;\r
+       int w, h, l;\r
+       int passno;\r
+       int bpno, passtype;\r
+       int max;\r
+       int nmsedec = 0;\r
+       double cumwmsedec = 0;\r
+       char type = T1_TYPE_MQ;\r
+       \r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       w = cblk->x1 - cblk->x0;\r
+       h = cblk->y1 - cblk->y0;\r
+       l = cblk->z1 - cblk->z0;\r
+\r
+       max = 0;\r
+       for (k = 0; k < l; k++) {\r
+               for (j = 0; j < h; j++) {\r
+                       for (i = 0; i < w; i++) {\r
+                               max = int_max(max, int_abs(t1->data[k][j][i]));\r
+                       }\r
+               }\r
+       }\r
+       for (k = 0; k <= l; k++) {\r
+               for (j = 0; j <= h; j++) {\r
+                       for (i = 0; i <= w; i++) {\r
+                               t1->flags[k][j][i] = 0; \r
+                       }\r
+               }\r
+       }\r
+\r
+       cblk->numbps = max ? (int_floorlog2(max) + 1) - T1_NMSEDEC_FRACBITS : 0;\r
+       \r
+       bpno = cblk->numbps - 1;\r
+       passtype = 2;\r
+       \r
+       mqc_reset_enc(mqc);\r
+       mqc_init_enc(mqc, cblk->data);\r
+       \r
+       for (passno = 0; bpno >= 0; passno++) {\r
+               opj_tcd_pass_t *pass = &cblk->passes[passno];\r
+               int correction = 3;\r
+               double tmpwmsedec;\r
+               type = ((bpno < (cblk->numbps - 4)) && (passtype < 2) && (cblksty & J3D_CCP_CBLKSTY_LAZY)) ? T1_TYPE_RAW : T1_TYPE_MQ;\r
+               //fprintf(stdout,"passno %d passtype %d w %d h %d l %d bpno %d orient %d type %d cblksty %d\n",passno,passtype,w,h,l,bpno,orient,type,cblksty);\r
+\r
+               switch (passtype) {\r
+                       case 0:\r
+                               t1_enc_sigpass(t1, w, h, l, bpno, orient, &nmsedec, type, cblksty);\r
+                               break;\r
+                       case 1:\r
+                               t1_enc_refpass(t1, w, h, l, bpno, &nmsedec, type, cblksty);\r
+                               break;\r
+                       case 2:\r
+                               //fprintf(stdout,"w %d h %d l %d bpno %d orient %d \n",w,h,l,bpno,orient);\r
+                               t1_enc_clnpass(t1, w, h, l, bpno, orient, &nmsedec, cblksty);\r
+                               /* code switch SEGMARK (i.e. SEGSYM) */\r
+                               if (cblksty & J3D_CCP_CBLKSTY_SEGSYM)\r
+                                       mqc_segmark_enc(mqc);\r
+                               break;\r
+               }\r
+               \r
+               /* fixed_quality */\r
+               tmpwmsedec = t1_getwmsedec(nmsedec, compno, level, orient, bpno, stepsize, numcomps, dwtid);\r
+               cumwmsedec += tmpwmsedec;\r
+               tile->distotile += tmpwmsedec;\r
+               \r
+               /* Code switch "RESTART" (i.e. TERMALL) */\r
+               if ((cblksty & J3D_CCP_CBLKSTY_TERMALL) && !((passtype == 2) && (bpno - 1 < 0))) {\r
+                       if (type == T1_TYPE_RAW) {\r
+                               mqc_flush(mqc);\r
+                               correction = 1;\r
+                               /* correction = mqc_bypass_flush_enc(); */\r
+                       } else {                        /* correction = mqc_restart_enc(); */\r
+                               mqc_flush(mqc);\r
+                               correction = 1;\r
+                       }\r
+                       pass->term = 1;\r
+               } else {\r
+                       if (((bpno < (cblk->numbps - 4) && (passtype > 0)) \r
+                               || ((bpno == (cblk->numbps - 4)) && (passtype == 2))) && (cblksty & J3D_CCP_CBLKSTY_LAZY)) {\r
+                               if (type == T1_TYPE_RAW) {\r
+                                       mqc_flush(mqc);\r
+                                       correction = 1;\r
+                                       /* correction = mqc_bypass_flush_enc(); */\r
+                               } else {                /* correction = mqc_restart_enc(); */\r
+                                       mqc_flush(mqc);\r
+                                       correction = 1;\r
+                               }\r
+                               pass->term = 1;\r
+                       } else {\r
+                               pass->term = 0;\r
+                       }\r
+               }\r
+               \r
+               if (++passtype == 3) {\r
+                       passtype = 0;\r
+                       bpno--;\r
+               }\r
+               \r
+               if (pass->term && bpno > 0) {\r
+                       type = ((bpno < (cblk->numbps - 4)) && (passtype < 2) && (cblksty & J3D_CCP_CBLKSTY_LAZY)) ? T1_TYPE_RAW : T1_TYPE_MQ;\r
+                       if (type == T1_TYPE_RAW)\r
+                               mqc_bypass_init_enc(mqc);\r
+                       else\r
+                               mqc_restart_init_enc(mqc);\r
+               }\r
+               \r
+               pass->distortiondec = cumwmsedec;\r
+               pass->rate = mqc_numbytes(mqc) + correction;    /* FIXME */\r
+               pass->len = pass->rate - (passno == 0 ? 0 : cblk->passes[passno - 1].rate);\r
+               \r
+               /* Code-switch "RESET" */\r
+               if (cblksty & J3D_CCP_CBLKSTY_RESET)\r
+                       mqc_reset_enc(mqc);\r
+       }\r
+       \r
+       /* Code switch "ERTERM" (i.e. PTERM) */\r
+       if (cblksty & J3D_CCP_CBLKSTY_PTERM)\r
+               mqc_erterm_enc(mqc);\r
+       else /* Default coding */ if (!(cblksty & J3D_CCP_CBLKSTY_LAZY))\r
+               mqc_flush(mqc);\r
+       \r
+       cblk->totalpasses = passno;\r
+}\r
+\r
+static void t1_decode_cblk(opj_t1_t *t1, opj_tcd_cblk_t * cblk, int orient, int roishift, int cblksty) {\r
+       int i, j, k, w, h, l;\r
+       int bpno, passtype;\r
+       int segno, passno;\r
+       char type = T1_TYPE_MQ; /* BYPASS mode */\r
+       \r
+       opj_raw_t *raw = t1->raw;       /* RAW component */\r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       w = cblk->x1 - cblk->x0;\r
+       h = cblk->y1 - cblk->y0;\r
+       l = cblk->z1 - cblk->z0;\r
+\r
+    for (k = 0; k < l; k++) {\r
+               for (j = 0; j < h; j++) {\r
+                       for (i = 0; i < w; i++) {\r
+                               t1->data[k][j][i] = 0;\r
+                       }\r
+               }\r
+       }\r
+       \r
+       for (k = 0; k <= l; k++) {\r
+               for (j = 0; j <= h; j++) {\r
+                       for (i = 0; i <= w; i++) {\r
+                               t1->flags[k][j][i] = 0;\r
+                       }\r
+               }\r
+       }\r
+\r
+       bpno = roishift + cblk->numbps - 1;\r
+       passtype = 2;\r
+       \r
+       mqc_reset_enc(mqc);\r
+       \r
+       for (segno = 0; segno < cblk->numsegs; segno++) {\r
+               opj_tcd_seg_t *seg = &cblk->segs[segno];\r
+               \r
+               /* BYPASS mode */\r
+               type = ((bpno <= (cblk->numbps - 1) - 4) && (passtype < 2) && (cblksty & J3D_CCP_CBLKSTY_LAZY)) ? T1_TYPE_RAW : T1_TYPE_MQ;\r
+               if (type == T1_TYPE_RAW) {\r
+                       raw_init_dec(raw, seg->data, seg->len);\r
+               } else {\r
+                       mqc_init_dec(mqc, seg->data, seg->len);\r
+               }\r
+\r
+               for (passno = 0; passno < seg->numpasses; passno++) {\r
+                       switch (passtype) {\r
+                               case 0:\r
+                                       t1_dec_sigpass(t1, w, h, l, bpno+1, orient, type, cblksty);\r
+                                       break;\r
+                               case 1:\r
+                                       t1_dec_refpass(t1, w, h, l, bpno+1, type, cblksty);\r
+                                       break;\r
+                               case 2:\r
+                                       t1_dec_clnpass(t1, w, h, l, bpno+1, orient, cblksty);\r
+                                       break;\r
+                       }\r
+                       \r
+                       if ((cblksty & J3D_CCP_CBLKSTY_RESET) && type == T1_TYPE_MQ) {\r
+                               mqc_reset_enc(mqc);\r
+                       }\r
+                       if (++passtype == 3) {\r
+                               passtype = 0;\r
+                               bpno--;\r
+                       }\r
+               }\r
+       }\r
+}\r
+\r
+static int t1_init_ctxno_zc(int f, int orient) {\r
+       int h, v, d, n, t, hv;\r
+       n = 0;\r
+       h = ((f & T1_SIG_W) != 0) + ((f & T1_SIG_E) != 0);\r
+       v = ((f & T1_SIG_N) != 0) + ((f & T1_SIG_S) != 0);\r
+       d = ((f & T1_SIG_NW) != 0) + ((f & T1_SIG_NE) != 0) + ((f & T1_SIG_SE) != 0) + ((f & T1_SIG_SW) != 0);\r
+       \r
+       switch (orient) {\r
+               case 2:\r
+                       t = h;\r
+                       h = v;\r
+                       v = t;\r
+               case 0:\r
+               case 1:\r
+                       if (!h) {\r
+                               if (!v) {\r
+                                       if (!d)\r
+                                               n = 0;\r
+                                       else if (d == 1)\r
+                                               n = 1;\r
+                                       else\r
+                                               n = 2;\r
+                               } else if (v == 1) {\r
+                                       n = 3;\r
+                               } else {\r
+                                       n = 4;\r
+                               }\r
+                       } else if (h == 1) {\r
+                               if (!v) {\r
+                                       if (!d)\r
+                                               n = 5;\r
+                                       else\r
+                                               n = 6;\r
+                               } else {\r
+                                       n = 7;\r
+                               }\r
+                       } else\r
+                               n = 8;\r
+                       break;\r
+               case 3:\r
+                       hv = h + v;\r
+                       if (!d) {\r
+                               if (!hv) {\r
+                                       n = 0;\r
+                               } else if (hv == 1) {\r
+                                       n = 1;\r
+                               } else {\r
+                                       n = 2;\r
+                               }\r
+                       } else if (d == 1) {\r
+                               if (!hv) {\r
+                                       n = 3;\r
+                               } else if (hv == 1) {\r
+                                       n = 4;\r
+                               } else {\r
+                                       n = 5;\r
+                               }\r
+                       } else if (d == 2) {\r
+                               if (!hv) {\r
+                                       n = 6;\r
+                               } else {\r
+                                       n = 7;\r
+                               }\r
+                       } else {\r
+                               n = 8;\r
+                       }\r
+                       break;\r
+       }\r
+       \r
+       return (T1_CTXNO_ZC + n);\r
+}\r
+\r
+static int t1_init_ctxno_sc(int f) {\r
+       int hc, vc, n;\r
+       n = 0;\r
+\r
+       hc = int_min(((f & (T1_SIG_E | T1_SGN_E)) ==\r
+               T1_SIG_E) + ((f & (T1_SIG_W | T1_SGN_W)) == T1_SIG_W),\r
+              1) - int_min(((f & (T1_SIG_E | T1_SGN_E)) ==\r
+                  (T1_SIG_E | T1_SGN_E)) +\r
+                  ((f & (T1_SIG_W | T1_SGN_W)) ==\r
+                  (T1_SIG_W | T1_SGN_W)), 1);\r
+       \r
+       vc = int_min(((f & (T1_SIG_N | T1_SGN_N)) ==\r
+               T1_SIG_N) + ((f & (T1_SIG_S | T1_SGN_S)) == T1_SIG_S),\r
+              1) - int_min(((f & (T1_SIG_N | T1_SGN_N)) ==\r
+                  (T1_SIG_N | T1_SGN_N)) +\r
+                  ((f & (T1_SIG_S | T1_SGN_S)) ==\r
+                  (T1_SIG_S | T1_SGN_S)), 1);\r
+       \r
+       if (hc < 0) {\r
+               hc = -hc;\r
+               vc = -vc;\r
+       }\r
+       if (!hc) {\r
+               if (vc == -1)\r
+                       n = 1;\r
+               else if (!vc)\r
+                       n = 0;\r
+               else\r
+                       n = 1;\r
+       } else if (hc == 1) {\r
+               if (vc == -1)\r
+                       n = 2;\r
+               else if (!vc)\r
+                       n = 3;\r
+               else\r
+                       n = 4;\r
+       }\r
+       \r
+       return (T1_CTXNO_SC + n);\r
+}\r
+\r
+static int t1_init_ctxno_mag(int f) {\r
+       int n;\r
+       if (!(f & T1_REFINE))\r
+               n = (f & (T1_SIG_OTH)) ? 1 : 0;\r
+       else\r
+               n = 2;\r
+       \r
+       return (T1_CTXNO_MAG + n);\r
+}\r
+\r
+static int t1_init_spb(int f) {\r
+       int hc, vc, n;\r
+       \r
+       hc = int_min(((f & (T1_SIG_E | T1_SGN_E)) ==\r
+               T1_SIG_E) + ((f & (T1_SIG_W | T1_SGN_W)) == T1_SIG_W),\r
+              1) - int_min(((f & (T1_SIG_E | T1_SGN_E)) ==\r
+                  (T1_SIG_E | T1_SGN_E)) +\r
+                  ((f & (T1_SIG_W | T1_SGN_W)) ==\r
+                  (T1_SIG_W | T1_SGN_W)), 1);\r
+       \r
+       vc = int_min(((f & (T1_SIG_N | T1_SGN_N)) ==\r
+               T1_SIG_N) + ((f & (T1_SIG_S | T1_SGN_S)) == T1_SIG_S),\r
+              1) - int_min(((f & (T1_SIG_N | T1_SGN_N)) ==\r
+                  (T1_SIG_N | T1_SGN_N)) +\r
+                  ((f & (T1_SIG_S | T1_SGN_S)) ==\r
+                  (T1_SIG_S | T1_SGN_S)), 1);\r
+       \r
+       if (!hc && !vc)\r
+               n = 0;\r
+       else\r
+               n = (!(hc > 0 || (!hc && vc > 0)));\r
+       \r
+       return n;\r
+}\r
+\r
+static void t1_init_luts(opj_t1_t *t1) {\r
+       int i, j;\r
+       double u, v, t;\r
+       for (j = 0; j < 4; j++) {\r
+               for (i = 0; i < 256; ++i) {\r
+                       t1->lut_ctxno_zc[(j << 8) | i] = t1_init_ctxno_zc(i, j);\r
+               }\r
+       }\r
+       for (i = 0; i < 256; i++) {\r
+               t1->lut_ctxno_sc[i] = t1_init_ctxno_sc(i << 4);\r
+       }\r
+       for (j = 0; j < 2; j++) {\r
+               for (i = 0; i < 2048; ++i) {\r
+                       t1->lut_ctxno_mag[(j << 11) + i] = t1_init_ctxno_mag((j ? T1_REFINE : 0) | i);\r
+               }\r
+       }\r
+       for (i = 0; i < 256; ++i) {\r
+               t1->lut_spb[i] = t1_init_spb(i << 4);\r
+       }\r
+       /* FIXME FIXME FIXME */\r
+       /* fprintf(stdout,"nmsedec luts:\n"); */\r
+       for (i = 0; i < (1 << T1_NMSEDEC_BITS); i++) {\r
+               t = i / pow(2, T1_NMSEDEC_FRACBITS);\r
+               u = t;\r
+               v = t - 1.5;\r
+               t1->lut_nmsedec_sig[i] = \r
+                       int_max(0, \r
+                       (int) (floor((u * u - v * v) * pow(2, T1_NMSEDEC_FRACBITS) + 0.5) / pow(2, T1_NMSEDEC_FRACBITS) * 8192.0));\r
+               t1->lut_nmsedec_sig0[i] =\r
+                       int_max(0,\r
+                       (int) (floor((u * u) * pow(2, T1_NMSEDEC_FRACBITS) + 0.5) / pow(2, T1_NMSEDEC_FRACBITS) * 8192.0));\r
+               u = t - 1.0;\r
+               if (i & (1 << (T1_NMSEDEC_BITS - 1))) {\r
+                       v = t - 1.5;\r
+               } else {\r
+                       v = t - 0.5;\r
+               }\r
+               t1->lut_nmsedec_ref[i] =\r
+                       int_max(0,\r
+                       (int) (floor((u * u - v * v) * pow(2, T1_NMSEDEC_FRACBITS) + 0.5) / pow(2, T1_NMSEDEC_FRACBITS) * 8192.0));\r
+               t1->lut_nmsedec_ref0[i] =\r
+                       int_max(0,\r
+                       (int) (floor((u * u) * pow(2, T1_NMSEDEC_FRACBITS) + 0.5) / pow(2, T1_NMSEDEC_FRACBITS) * 8192.0));\r
+       }\r
+}\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+opj_t1_t* t1_create(opj_common_ptr cinfo) {\r
+       opj_t1_t *t1 = (opj_t1_t*)opj_malloc(sizeof(opj_t1_t));\r
+       if(t1) {\r
+               t1->cinfo = cinfo;\r
+               /* create MQC and RAW handles */\r
+               t1->mqc = mqc_create();\r
+               t1->raw = raw_create();\r
+               /* initialize the look-up tables of the Tier-1 coder/decoder */\r
+               t1_init_luts(t1);\r
+       }\r
+       return t1;\r
+}\r
+\r
+void t1_destroy(opj_t1_t *t1) {\r
+       if(t1) {\r
+               /* destroy MQC and RAW handles */\r
+               mqc_destroy(t1->mqc);\r
+               raw_destroy(t1->raw);\r
+               //opj_free(t1->data);\r
+               //opj_free(t1->flags);\r
+               opj_free(t1);\r
+       }\r
+}\r
+\r
+void t1_encode_cblks(opj_t1_t *t1, opj_tcd_tile_t *tile, opj_tcp_t *tcp) {\r
+       int compno, resno, bandno, precno, cblkno;\r
+       int x, y, z, i, j, k, orient;\r
+       int n=0;\r
+       int level[3];\r
+       FILE *fid = NULL;\r
+//     char filename[10];\r
+       tile->distotile = 0;            /* fixed_quality */\r
+       \r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+\r
+               for (resno = 0; resno < tilec->numresolution[0]; resno++) {\r
+                       opj_tcd_resolution_t *res = &tilec->resolutions[resno];\r
+                       \r
+                       /* Weighted first order entropy\r
+                       sprintf(filename,"res%d.txt",resno);\r
+                       if ((fid = fopen(filename,"w")) == 0){\r
+                               fprintf(stdout,"Error while opening %s\n", filename);\r
+                               exit(1);\r
+                       }\r
+                       */\r
+                       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                               opj_tcd_band_t *band = &res->bands[bandno];\r
+                               for (precno = 0; precno < res->prctno[0] * res->prctno[1] * res->prctno[2]; precno++) {\r
+                                       opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+\r
+                                       for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                                               opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+\r
+                                               //fprintf(stdout,"Precno %d Cblkno %d \n",precno,cblkno);\r
+                                               if (band->bandno == 0) {\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 1) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 2) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 3) {         \r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 4) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 5) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 6) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 7) {         \r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               }\r
+\r
+                                               if (tcp->tccps[compno].reversible == 1) {\r
+                                                       for (k = 0; k < cblk->z1 - cblk->z0; k++) {\r
+                                                               for (j = 0; j < cblk->y1 - cblk->y0; j++) {\r
+                                    for (i = 0; i < cblk->x1 - cblk->x0; i++) {\r
+                                        t1->data[k][j][i] = \r
+                                                                               tilec->data[(x + i) + (y + j) * (tilec->x1 - tilec->x0) + (z + k) * (tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0)] << T1_NMSEDEC_FRACBITS;\r
+//fprintf(fid," %d",t1->data[k][j][i]);\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               } else if (tcp->tccps[compno].reversible == 0) {\r
+                                                       for (k = 0; k < cblk->z1 - cblk->z0; k++) {\r
+                                                               for (j = 0; j < cblk->y1 - cblk->y0; j++) {\r
+                                    for (i = 0; i < cblk->x1 - cblk->x0; i++) {\r
+                                        t1->data[k][j][i] = fix_mul(\r
+                                                                               tilec->data[(x + i) + (y + j) * (tilec->x1 - tilec->x0) + (z + k) * (tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0)],\r
+                                                                               8192 * 8192 / ((int) floor(band->stepsize * 8192))) >> (13 - T1_NMSEDEC_FRACBITS);\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+\r
+                                               orient = band->bandno;  /* FIXME */\r
+                                               if (orient == 2) {\r
+                                                       orient = 1;\r
+                                               } else if (orient == 1) {\r
+                                                       orient = 2;\r
+                                               }\r
+                                               for (i = 0; i < 3; i++) \r
+                                                       level[i] = tilec->numresolution[i] - 1 - resno;\r
+                                               //fprintf(stdout,"t1_encode_cblk(t1, cblk, %d, %d, %d %d %d, %d, %f, %d, %d, tile);\n", orient, compno, level[0], level[1], level[2], tcp->tccps[compno].reversible, band->stepsize, tcp->tccps[compno].cblksty, tile->numcomps);\r
+                                               t1_encode_cblk(t1, cblk, orient, compno, level, tcp->tccps[compno].dwtid, band->stepsize, tcp->tccps[compno].cblksty, tile->numcomps, tile);\r
+                                                       \r
+                                       } /* cblkno */\r
+                               } /* precno */\r
+//fprintf(fid,"\n");\r
+                       } /* bandno */\r
+//fclose(fid);\r
+               } /* resno  */\r
+       } /* compno  */\r
+}\r
+\r
+void t1_decode_cblks(opj_t1_t *t1, opj_tcd_tile_t *tile, opj_tcp_t *tcp) {\r
+       int compno, resno, bandno, precno, cblkno;\r
+       \r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+\r
+               for (resno = 0; resno < tilec->numresolution[0]; resno++) {\r
+                       opj_tcd_resolution_t *res = &tilec->resolutions[resno];\r
+\r
+                       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                               opj_tcd_band_t *band = &res->bands[bandno];\r
+\r
+                               for (precno = 0; precno < res->prctno[0] * res->prctno[1] * res->prctno[2]; precno++) {\r
+                                       opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+\r
+                                       for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                                               int x, y, k, i, j, z, orient;\r
+                                               opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+\r
+                                               orient = band->bandno;  /* FIXME */\r
+                                               if (orient == 2) {\r
+                                                       orient = 1;\r
+                                               } else if (orient == 1) {\r
+                                                       orient = 2;\r
+                                               }\r
+\r
+                                               t1_decode_cblk(t1, cblk, orient, tcp->tccps[compno].roishift, tcp->tccps[compno].cblksty);\r
+\r
+                                               if (band->bandno == 0) {\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 1) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 2) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 3) {         \r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 4) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 5) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 6) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 7) {         \r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               }\r
+                                               \r
+                                               if (tcp->tccps[compno].roishift) {\r
+                                                       int thresh, val, mag;\r
+                                                       thresh = 1 << tcp->tccps[compno].roishift;\r
+                                                       for (k = 0; k < cblk->z1 - cblk->z0; k++) {\r
+                                                               for (j = 0; j < cblk->y1 - cblk->y0; j++) {\r
+                                                                       for (i = 0; i < cblk->x1 - cblk->x0; i++) {\r
+                                                                               val = t1->data[k][j][i];\r
+                                                                               mag = int_abs(val);\r
+                                                                               if (mag >= thresh) {\r
+                                                                                       mag >>= tcp->tccps[compno].roishift;\r
+                                                                                       t1->data[k][j][i] = val < 0 ? -mag : mag;\r
+                                                                               }\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                               \r
+                                               if (tcp->tccps[compno].reversible == 1) {\r
+                                                       for (k = 0; k < cblk->z1 - cblk->z0; k++) {\r
+                                                               for (j = 0; j < cblk->y1 - cblk->y0; j++) {\r
+                                                                       for (i = 0; i < cblk->x1 - cblk->x0; i++) {\r
+                                                                               int tmp = t1->data[k][j][i];\r
+                                                                               tilec->data[x + i + (y + j) * (tilec->x1 - tilec->x0) + (z + k) * (tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0)] = tmp/2;\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               } else {                /* if (tcp->tccps[compno].reversible == 0) */\r
+                                                       for (k = 0; k < cblk->z1 - cblk->z0; k++) {\r
+                                                               for (j = 0; j < cblk->y1 - cblk->y0; j++) {\r
+                                                                       for (i = 0; i < cblk->x1 - cblk->x0; i++) {\r
+                                                                               double tmp = (double)(t1->data[k][j][i] * band->stepsize * 4096.0);\r
+                                                                               if (t1->data[k][j][i] >> 1 == 0) {\r
+                                                                                       tilec->data[x + i + (y + j) * (tilec->x1 - tilec->x0) + (z + k) * (tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0)] = 0;\r
+                                                                               } else {\r
+                                                                                       int tmp2 = ((int) (floor(fabs(tmp)))) + ((int) floor(fabs(tmp*2))%2);\r
+                                                                                       tilec->data[x + i + (y + j) * (tilec->x1 - tilec->x0) + (z + k) * (tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0)] = ((tmp<0)?-tmp2:tmp2);\r
+                                                                               }\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                       } /* cblkno */\r
+                               } /* precno */\r
+                       } /* bandno */\r
+               } /* resno */\r
+       } /* compno */\r
+}\r
+\r
+\r
+/** mod fixed_quality */\r
+double t1_getwmsedec(int nmsedec, int compno, int level[3], int orient, int bpno, double stepsize, int numcomps, int dwtid[3]) {\r
+       double w1, w2, wmsedec;\r
+       \r
+       if (dwtid[0] == 1 || dwtid[1] == 1 || dwtid[2] == 1) {\r
+               w1 = (numcomps > 1) ? mct_getnorm_real(compno) : 1;\r
+       } else {                        \r
+               w1 = (numcomps > 1) ? mct_getnorm(compno) : 1;\r
+       }\r
+       w2 = dwt_getnorm(orient, level, dwtid);\r
+\r
+       //fprintf(stdout,"nmsedec %d level %d %d %d orient %d bpno %d stepsize %f \n",nmsedec ,level[0],level[1],level[2],orient,bpno,stepsize);\r
+       wmsedec = w1 * w2 * stepsize * (1 << bpno);\r
+       wmsedec *= wmsedec * nmsedec / 8192.0;\r
+       \r
+       return wmsedec;\r
+}\r
+/** mod fixed_quality */\r
diff --git a/src/lib/openjp3d/t1.h b/src/lib/openjp3d/t1.h
new file mode 100755 (executable)
index 0000000..7b4a18f
--- /dev/null
@@ -0,0 +1,173 @@
+/*\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
+ * 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
+#ifndef __T1_H\r
+#define __T1_H\r
+/**\r
+@file t1.h\r
+@brief Implementation of the tier-1 coding (coding of code-block coefficients) (T1)\r
+\r
+The functions in T1.C have for goal to realize the tier-1 coding operation. The functions\r
+in T1.C are used by some function in TCD.C.\r
+*/\r
+\r
+/** @defgroup T1 T1 - Implementation of the tier-1 coding */\r
+/*@{*/\r
+\r
+/* ----------------------------------------------------------------------- */\r
+#define T1_NMSEDEC_BITS 7\r
+\r
+#define T1_MAXCBLKW 256        /*< Maximum size of code-block (width) */\r
+#define T1_MAXCBLKH 256        /*< Maximum size of code-block (heigth) */\r
+#define T1_MAXCBLKD 256        /*< Maximum size of code-block (depth) */\r
+#define T1_MINCBLKW 4          /*< Minimum size of code-block (width) */\r
+#define T1_MINCBLKH 4          /*< Minimum size of code-block (heigth) */\r
+#define T1_MINCBLKD 4          /*< Minimum size of code-block (depth) */\r
+#define T1_MAXWHD 18   \r
+#define T1_CBLKW 256\r
+#define T1_CBLKH 256\r
+#define T1_CBLKD 256\r
+\r
+#define T1_SIG_NE 0x0001       /*< Context orientation : North-East direction */\r
+#define T1_SIG_SE 0x0002       /*< Context orientation : South-East direction */\r
+#define T1_SIG_SW 0x0004       /*< Context orientation : South-West direction */\r
+#define T1_SIG_NW 0x0008       /*< Context orientation : North-West direction */\r
+#define T1_SIG_N 0x0010                /*< Context orientation : North direction */\r
+#define T1_SIG_E 0x0020                /*< Context orientation : East direction */\r
+#define T1_SIG_S 0x0040                /*< Context orientation : South direction */\r
+#define T1_SIG_W 0x0080                /*< Context orientation : West direction */\r
+#define T1_SIG_OTH (T1_SIG_N|T1_SIG_NE|T1_SIG_E|T1_SIG_SE|T1_SIG_S|T1_SIG_SW|T1_SIG_W|T1_SIG_NW)\r
+#define T1_SIG_PRIM (T1_SIG_N|T1_SIG_E|T1_SIG_S|T1_SIG_W)\r
+\r
+#define T1_SGN_N 0x0100\r
+#define T1_SGN_E 0x0200\r
+#define T1_SGN_S 0x0400\r
+#define T1_SGN_W 0x0800\r
+#define T1_SGN (T1_SGN_N|T1_SGN_E|T1_SGN_S|T1_SGN_W)\r
+\r
+#define T1_SIG 0x1000\r
+#define T1_REFINE 0x2000\r
+#define T1_VISIT 0x4000\r
+\r
+#define T1_NUMCTXS_AGG 1\r
+#define T1_NUMCTXS_ZC 9\r
+#define T1_NUMCTXS_MAG 3\r
+#define T1_NUMCTXS_SC 5\r
+#define T1_NUMCTXS_UNI 1\r
+\r
+#define T1_CTXNO_AGG 0\r
+#define T1_CTXNO_ZC (T1_CTXNO_AGG+T1_NUMCTXS_AGG)\r
+#define T1_CTXNO_MAG (T1_CTXNO_ZC+T1_NUMCTXS_ZC)\r
+#define T1_CTXNO_SC (T1_CTXNO_MAG+T1_NUMCTXS_MAG)\r
+#define T1_CTXNO_UNI (T1_CTXNO_SC+T1_NUMCTXS_SC)\r
+#define T1_NUMCTXS (T1_CTXNO_UNI+T1_NUMCTXS_UNI)\r
+\r
+#define T1_NMSEDEC_FRACBITS (T1_NMSEDEC_BITS-1)\r
+\r
+#define T1_TYPE_MQ 0   /*< Normal coding using entropy coder */\r
+#define T1_TYPE_RAW 1  /*< No encoding the information is store under raw format in codestream (mode switch RAW)*/\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+/**\r
+Tier-1 coding (coding of code-block coefficients)\r
+*/\r
+typedef struct opj_t1 {\r
+       /** codec context */\r
+       opj_common_ptr cinfo;\r
+\r
+       /** MQC component */\r
+       opj_mqc_t *mqc;\r
+       /** RAW component */\r
+       opj_raw_t *raw;\r
+       /** LUTs for context-based coding */\r
+       int lut_ctxno_zc[1024];\r
+       int lut_ctxno_sc[256];\r
+       int lut_ctxno_mag[4096];\r
+       int lut_spb[256];\r
+       /** LUTs for decoding normalised MSE */\r
+       int lut_nmsedec_sig[1 << T1_NMSEDEC_BITS];\r
+       int lut_nmsedec_sig0[1 << T1_NMSEDEC_BITS];\r
+       int lut_nmsedec_ref[1 << T1_NMSEDEC_BITS];\r
+       int lut_nmsedec_ref0[1 << T1_NMSEDEC_BITS];\r
+       /** Codeblock data */\r
+       int data[T1_CBLKD][T1_CBLKH][T1_CBLKW];//int ***data;\r
+       /** Context information for each voxel in codeblock */\r
+       int flags[T1_CBLKD + 2][T1_CBLKH + 2][T1_CBLKH + 2];//int ***flags;\r
+} opj_t1_t;\r
+\r
+/** @name Exported functions */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Create a new T1 handle \r
+and initialize the look-up tables of the Tier-1 coder/decoder\r
+@return Returns a new T1 handle if successful, returns NULL otherwise\r
+@see t1_init_luts\r
+*/\r
+opj_t1_t* t1_create(opj_common_ptr cinfo);\r
+/**\r
+Destroy a previously created T1 handle\r
+@param t1 T1 handle to destroy\r
+*/\r
+void t1_destroy(opj_t1_t *t1);\r
+/**\r
+Encode the code-blocks of a tile\r
+@param t1 T1 handle\r
+@param tile The tile to encode\r
+@param tcp Tile coding parameters\r
+*/\r
+void t1_encode_cblks(opj_t1_t *t1, opj_tcd_tile_t *tile, opj_tcp_t *tcp);\r
+/**\r
+Decode the code-blocks of a tile\r
+@param t1 T1 handle\r
+@param tile The tile to decode\r
+@param tcp Tile coding parameters\r
+*/\r
+void t1_decode_cblks(opj_t1_t *t1, opj_tcd_tile_t *tile, opj_tcp_t *tcp);\r
+/**\r
+Get weigths of MSE decoding\r
+@param nmsedec The normalized MSE reduction\r
+@param compno \r
+@param level \r
+@param orient\r
+@param bpno\r
+@param stepsize\r
+@param numcomps\r
+@param dwtid\r
+returns MSE associated to decoding pass\r
+*/\r
+double t1_getwmsedec(int nmsedec, int compno, int level[3], int orient, int bpno, double stepsize, int numcomps, int dwtid[3]);\r
+\r
+/* ----------------------------------------------------------------------- */\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* __T1_H */\r
diff --git a/src/lib/openjp3d/t1_3d.c b/src/lib/openjp3d/t1_3d.c
new file mode 100755 (executable)
index 0000000..efdf2ef
--- /dev/null
@@ -0,0 +1,1230 @@
+/*\r
+ * Copyrigth (c) 2006, Mónica Díez, LPI-UVA, Spain\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 "opj_includes.h"\r
+\r
+/** @defgroup T1_3D T1_3D - Implementation of the tier-1 coding */\r
+/*@{*/\r
+\r
+/** @name Local static functions */\r
+/*@{*/\r
+\r
+static int t1_3d_getctxno_zc(unsigned int f, int orient);\r
+static int t1_3d_getctxno_sc(unsigned int f);\r
+static int t1_3d_getctxno_mag(unsigned int f, int fsvr);\r
+static int t1_3d_getspb(unsigned int f);\r
+static int t1_3d_getnmsedec_sig(opj_t1_3d_t *t1, int x, int bitpos);\r
+static int t1_3d_getnmsedec_ref(opj_t1_3d_t *t1, int x, int bitpos);\r
+static void t1_3d_updateflags(unsigned int *fp, int s);\r
+/**\r
+Encode significant pass\r
+*/\r
+static void t1_3d_enc_sigpass_step(opj_t1_3d_t *t1, unsigned int *fp, int *fsvr, int *dp, int orient, int bpno, int one, int *nmsedec, char type, int vsc);\r
+/**\r
+Decode significant pass\r
+*/\r
+static void t1_3d_dec_sigpass_step(opj_t1_3d_t *t1, unsigned int *fp, int *fsvr, int *dp, int orient, int oneplushalf, char type, int vsc);\r
+/**\r
+Encode significant pass\r
+*/\r
+static void t1_3d_enc_sigpass(opj_t1_3d_t *t1, int w, int h, int l, int bpno, int orient, int *nmsedec, char type, int cblksty);\r
+/**\r
+Decode significant pass\r
+*/\r
+static void t1_3d_dec_sigpass(opj_t1_3d_t *t1, int w, int h, int l, int bpno, int orient, char type, int cblksty);\r
+/**\r
+Encode refinement pass\r
+*/\r
+static void t1_3d_enc_refpass_step(opj_t1_3d_t *t1, unsigned int *fp, int *fsvr, int *dp, int bpno, int one, int *nmsedec, char type, int vsc);\r
+/**\r
+Decode refinement pass\r
+*/\r
+static void t1_3d_dec_refpass_step(opj_t1_3d_t *t1, unsigned int *fp, int *fsvr, int *dp, int poshalf, int neghalf, char type, int vsc);\r
+/**\r
+Encode refinement pass\r
+*/\r
+static void t1_3d_enc_refpass(opj_t1_3d_t *t1, int w, int h, int l, int bpno, int *nmsedec, char type, int cblksty);\r
+/**\r
+Decode refinement pass\r
+*/\r
+static void t1_3d_dec_refpass(opj_t1_3d_t *t1, int w, int h, int l, int bpno, char type, int cblksty);\r
+/**\r
+Encode clean-up pass\r
+*/\r
+static void t1_3d_enc_clnpass_step(opj_t1_3d_t *t1, unsigned int *fp, int *fsvr, int *dp, int orient, int bpno, int one, int *nmsedec, int partial, int vsc);\r
+/**\r
+Decode clean-up pass\r
+*/\r
+static void t1_3d_dec_clnpass_step(opj_t1_3d_t *t1, unsigned int *fp, int *fsvr, int *dp, int orient, int oneplushalf, int partial, int vsc);\r
+/**\r
+Encode clean-up pass\r
+*/\r
+static void t1_3d_enc_clnpass(opj_t1_3d_t *t1, int w, int h, int l, int bpno, int orient, int *nmsedec, int cblksty);\r
+/**\r
+Decode clean-up pass\r
+*/\r
+static void t1_3d_dec_clnpass(opj_t1_3d_t *t1, int w, int h, int l, int bpno, int orient, int cblksty);\r
+/**\r
+Encode 1 code-block\r
+@param t1 T1 handle\r
+@param cblk Code-block coding parameters\r
+@param orient\r
+@param compno Component number\r
+@param level[3]\r
+@param dwtid[3]\r
+@param stepsize\r
+@param cblksty Code-block style\r
+@param numcomps\r
+@param tile\r
+*/\r
+static void t1_3d_encode_cblk(opj_t1_3d_t *t1, opj_tcd_cblk_t * cblk, int orient, int compno,  int level[3], int dwtid[3], double stepsize, int cblksty, int numcomps, opj_tcd_tile_t * tile);\r
+/**\r
+Decode 1 code-block\r
+@param t1 T1 handle\r
+@param cblk Code-block coding parameters\r
+@param orient\r
+@param roishift Region of interest shifting value\r
+@param cblksty Code-block style\r
+*/\r
+static void t1_3d_decode_cblk(opj_t1_3d_t *t1, opj_tcd_cblk_t * cblk, int orient, int roishift, int cblksty);\r
+static int t1_3d_init_ctxno_zc(unsigned int f, int orient);\r
+static int t1_3d_init_ctxno_sc(unsigned int f);\r
+static int t1_3d_init_ctxno_mag(unsigned int f, int f2);\r
+static int t1_3d_init_spb(unsigned int f);\r
+/**\r
+Initialize the look-up tables of the Tier-1 coder/decoder\r
+@param t1 T1 handle\r
+*/\r
+static void t1_3d_init_luts(opj_t1_3d_t *t1);\r
+\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+static int t1_3d_getctxno_zc(unsigned int f, int orient) {\r
+       return t1_3d_init_ctxno_zc((f & T1_3D_SIG_OTH), orient);\r
+}\r
+\r
+static int t1_3d_getctxno_sc(unsigned int f) {\r
+       return t1_3d_init_ctxno_sc((f & T1_3D_SIG_PRIM) | ((f >> 16) & T1_3D_SGN));\r
+       //return t1->lut_ctxno_sc[((f & T1_3D_SIG_PRIM) | ((f >> 16) & T1_3D_SGN)) >> 4];\r
+}\r
+\r
+static int t1_3d_getctxno_mag(unsigned int f, int fsvr) {\r
+       return t1_3d_init_ctxno_mag((f & T1_3D_SIG_OTH), fsvr);\r
+}\r
+\r
+static int t1_3d_getspb(unsigned int f) {\r
+       return t1_3d_init_spb((f & T1_3D_SIG_PRIM) | ((f >> 16) & T1_3D_SGN));\r
+       //return t1->lut_spb[((f & T1_3D_SIG_PRIM) | ((f >> 16) & T1_3D_SGN)) >> 4];\r
+}\r
+\r
+static int t1_3d_getnmsedec_sig(opj_t1_3d_t *t1, int x, int bitpos) {\r
+       if (bitpos > T1_NMSEDEC_FRACBITS) {\r
+               return t1->lut_nmsedec_sig[(x >> (bitpos - T1_NMSEDEC_FRACBITS)) & ((1 << T1_NMSEDEC_BITS) - 1)];\r
+       }\r
+       \r
+       return t1->lut_nmsedec_sig0[x & ((1 << T1_NMSEDEC_BITS) - 1)];\r
+}\r
+\r
+static int t1_3d_getnmsedec_ref(opj_t1_3d_t *t1, int x, int bitpos) {\r
+       if (bitpos > T1_NMSEDEC_FRACBITS) {\r
+               return t1->lut_nmsedec_ref[(x >> (bitpos - T1_NMSEDEC_FRACBITS)) & ((1 << T1_NMSEDEC_BITS) - 1)];\r
+       }\r
+\r
+    return t1->lut_nmsedec_ref0[x & ((1 << T1_NMSEDEC_BITS) - 1)];\r
+}\r
+\r
+static void t1_3d_updateflags(unsigned int *fp, int s) {\r
+       unsigned int *np = fp - (T1_MAXCBLKW + 2);\r
+       unsigned int *sp = fp + (T1_MAXCBLKW + 2);\r
+\r
+       unsigned int *bwp = fp + ((T1_MAXCBLKW + 2)*(T1_MAXCBLKH +2));\r
+       unsigned int *bnp = bwp - (T1_MAXCBLKW + 2);\r
+       unsigned int *bsp = bwp + (T1_MAXCBLKW + 2);\r
+       \r
+       unsigned int *fwp = fp - ((T1_MAXCBLKW + 2)*(T1_MAXCBLKH +2));\r
+       unsigned int *fnp = fwp - (T1_MAXCBLKW + 2);\r
+       unsigned int *fsp = fwp + (T1_MAXCBLKW + 2);\r
+\r
+       np[-1] |= T1_3D_SIG_SE;\r
+       np[1] |= T1_3D_SIG_SW;\r
+       sp[-1] |= T1_3D_SIG_NE;\r
+       sp[1] |= T1_3D_SIG_NW;\r
+       *np |= T1_3D_SIG_S;\r
+       *sp |= T1_3D_SIG_N;\r
+       fp[-1] |= T1_3D_SIG_E;\r
+       fp[1] |= T1_3D_SIG_W;\r
+\r
+       *fwp |= T1_3D_SIG_FC;\r
+       *bwp |= T1_3D_SIG_BC;\r
+\r
+       fnp[-1] |= T1_3D_SIG_FSE;\r
+       fnp[1] |= T1_3D_SIG_FSW;\r
+       fsp[-1] |= T1_3D_SIG_FNE;\r
+       fsp[1] |= T1_3D_SIG_FNW;\r
+       *fnp |= T1_3D_SIG_FS;\r
+       *fsp |= T1_3D_SIG_FN;\r
+       fwp[-1] |= T1_3D_SIG_FE;\r
+       fwp[1] |= T1_3D_SIG_FW;\r
+\r
+       bnp[-1] |= T1_3D_SIG_BSE;\r
+       bnp[1] |= T1_3D_SIG_BSW;\r
+       bsp[-1] |= T1_3D_SIG_BNE;\r
+       bsp[1] |= T1_3D_SIG_BNW;\r
+       *bnp |= T1_3D_SIG_BS;\r
+       *bsp |= T1_3D_SIG_BN;\r
+       bwp[-1] |= T1_3D_SIG_BE;\r
+       bwp[1] |= T1_3D_SIG_BW;\r
+\r
+       if (s) {\r
+               *np |= (T1_3D_SGN_S << 16);\r
+               *sp |= (T1_3D_SGN_N << 16);\r
+               fp[-1] |= (T1_3D_SGN_E << 16);\r
+               fp[1] |= (T1_3D_SGN_W << 16);\r
+               *fwp |= (T1_3D_SGN_F << 16);\r
+               *bwp |= (T1_3D_SGN_B << 16);\r
+       }\r
+}\r
+\r
+static void t1_3d_enc_sigpass_step(opj_t1_3d_t *t1, unsigned int *fp, int *fsvr, int *dp, int orient, int bpno, int one, int *nmsedec, char type, int vsc) {\r
+       int v, flagsvr;\r
+       unsigned int flag;\r
+\r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       flag = vsc ? ((*fp) & (~(T1_3D_SIG_S | T1_3D_SIG_SE | T1_3D_SIG_SW | (T1_3D_SGN_S << 16)))) : (*fp);\r
+       flagsvr = (*fsvr);\r
+       if ((flag & T1_3D_SIG_OTH) && !(flagsvr & (T1_3D_SIG | T1_3D_VISIT))) {\r
+               v = int_abs(*dp) & one ? 1 : 0;\r
+               if (type == T1_TYPE_RAW) {      /* BYPASS/LAZY MODE */\r
+                       mqc_setcurctx(mqc, t1_3d_getctxno_zc(flag, orient));    /* ESSAI */\r
+                       mqc_bypass_enc(mqc, v);\r
+               } else {\r
+                       mqc_setcurctx(mqc, t1_3d_getctxno_zc(flag, orient));\r
+                       mqc_encode(mqc, v);\r
+               }\r
+               if (v) {\r
+                       v = *dp < 0 ? 1 : 0;\r
+                       *nmsedec +=     t1_3d_getnmsedec_sig(t1, int_abs(*dp), bpno + T1_NMSEDEC_FRACBITS);\r
+                       if (type == T1_TYPE_RAW) {      /* BYPASS/LAZY MODE */\r
+                               mqc_setcurctx(mqc, t1_3d_getctxno_sc(flag));    /* ESSAI */\r
+                               mqc_bypass_enc(mqc, v);\r
+                       } else {\r
+                               mqc_setcurctx(mqc, t1_3d_getctxno_sc(flag));\r
+                               mqc_encode(mqc, v ^ t1_3d_getspb(flag));\r
+                       }\r
+                       t1_3d_updateflags(fp, v);\r
+                       *fsvr |= T1_3D_SIG;\r
+               }\r
+               *fsvr |= T1_3D_VISIT;\r
+       }\r
+}\r
+\r
+static void t1_3d_dec_sigpass_step(opj_t1_3d_t *t1, unsigned int *fp, int *fsvr, int *dp, int orient, int oneplushalf, char type, int vsc) {\r
+       int v, flagsvr;\r
+       unsigned int flag;\r
+       \r
+       opj_raw_t *raw = t1->raw;       /* RAW component */\r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       flag = vsc ? ((*fp) & (~(T1_3D_SIG_S | T1_3D_SIG_SE | T1_3D_SIG_SW | (T1_3D_SGN_S << 16)))) : (*fp);\r
+       flagsvr = (*fsvr);\r
+       if ((flag & T1_3D_SIG_OTH) && !(flagsvr & (T1_3D_SIG | T1_3D_VISIT))) {\r
+               if (type == T1_TYPE_RAW) {\r
+                       if (raw_decode(raw)) {\r
+                               v = raw_decode(raw);    /* ESSAI */\r
+                               *dp = v ? -oneplushalf : oneplushalf;\r
+                               t1_3d_updateflags(fp, v);\r
+                               *fsvr |= T1_3D_SIG;\r
+                       }\r
+               } else {\r
+                       mqc_setcurctx(mqc, t1_3d_getctxno_zc(flag, orient));\r
+                       if (mqc_decode(mqc)) {\r
+                               mqc_setcurctx(mqc, t1_3d_getctxno_sc(flag));\r
+                               v = mqc_decode(mqc) ^ t1_3d_getspb(flag);\r
+                               *dp = v ? -oneplushalf : oneplushalf;\r
+                               t1_3d_updateflags(fp, v);\r
+                               *fsvr |= T1_3D_SIG;\r
+                       }\r
+               }\r
+               *fsvr |= T1_3D_VISIT;\r
+       }\r
+}                              /* VSC and  BYPASS by Antonin */\r
+\r
+static void t1_3d_enc_sigpass(opj_t1_3d_t *t1, int w, int h, int l, int bpno, int orient, int *nmsedec, char type, int cblksty) {\r
+       int i, j, k, m, one, vsc;\r
+       *nmsedec = 0;\r
+       one = 1 << (bpno + T1_NMSEDEC_FRACBITS);\r
+       for (m = 0; m < l; m++) {\r
+               for (k = 0; k < h; k += 4) {\r
+                       for (i = 0; i < w; i++) {\r
+                               for (j = k; j < k + 4 && j < h; j++) {\r
+                                       vsc = ((cblksty & J3D_CCP_CBLKSTY_VSC) && (j == k + 3 || j == h - 1)) ? 1 : 0;\r
+                                       t1_3d_enc_sigpass_step(t1, &t1->flags[1 + m][1 + j][1 + i], &t1->flagSVR[1 + m][1 + j][1 + i], &t1->data[m][j][i], orient, bpno, one, nmsedec, type, vsc);\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+}\r
+\r
+static void t1_3d_dec_sigpass(opj_t1_3d_t *t1, int w, int h, int l, int bpno, int orient, char type, int cblksty) {\r
+       int i, j, k, m, one, half, oneplushalf, vsc;\r
+       one = 1 << bpno;\r
+       half = one >> 1;\r
+       oneplushalf = one | half;\r
+       for (m = 0; m < l; m++) {\r
+               for (k = 0; k < h; k += 4) {\r
+                       for (i = 0; i < w; i++) {\r
+                               for (j = k; j < k + 4 && j < h; j++) {\r
+                                       vsc = ((cblksty & J3D_CCP_CBLKSTY_VSC) && (j == k + 3 || j == h - 1)) ? 1 : 0;\r
+                                       t1_3d_dec_sigpass_step(t1, &t1->flags[1 + m][1 + j][1 + i], &t1->flagSVR[1 + m][1 + j][1 + i], &t1->data[m][j][i], orient, oneplushalf, type, vsc);\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+}                              /* VSC and  BYPASS by Antonin */\r
+\r
+static void t1_3d_enc_refpass_step(opj_t1_3d_t *t1, unsigned int *fp, int *fsvr, int *dp, int bpno, int one, int *nmsedec, char type, int vsc) {\r
+       int v, flagsvr;\r
+       unsigned int flag;\r
+\r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       flag = vsc ? ((*fp) & (~(T1_3D_SIG_S | T1_3D_SIG_SE | T1_3D_SIG_SW | (T1_3D_SGN_S << 16)))) : (*fp);\r
+       flagsvr = (*fsvr);\r
+       if ((flagsvr & (T1_3D_SIG | T1_3D_VISIT)) == T1_3D_SIG) {\r
+               *nmsedec += t1_3d_getnmsedec_ref(t1, int_abs(*dp), bpno + T1_NMSEDEC_FRACBITS);\r
+               v = int_abs(*dp) & one ? 1 : 0;\r
+               if (type == T1_TYPE_RAW) {      /* BYPASS/LAZY MODE */\r
+                       mqc_setcurctx(mqc, t1_3d_getctxno_mag(flag, flagsvr));  /* ESSAI */\r
+                       mqc_bypass_enc(mqc, v);\r
+               } else {\r
+                       mqc_setcurctx(mqc, t1_3d_getctxno_mag(flag, flagsvr));\r
+                       mqc_encode(mqc, v);\r
+               }\r
+               *fsvr |= T1_3D_REFINE;\r
+       }\r
+}\r
+\r
+static void t1_3d_dec_refpass_step(opj_t1_3d_t *t1, unsigned int *fp, int *fsvr, int *dp, int poshalf, int neghalf, char type, int vsc) {\r
+       int v, t, flagsvr;\r
+       unsigned int flag;\r
+\r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       opj_raw_t *raw = t1->raw;       /* RAW component */\r
+       \r
+       flag = vsc ? ((*fp) & (~(T1_3D_SIG_S | T1_3D_SIG_SE | T1_3D_SIG_SW | (T1_3D_SGN_S << 16)))) : (*fp);\r
+       flagsvr = (*fsvr);\r
+       if ((flagsvr & (T1_3D_SIG | T1_3D_VISIT)) == T1_3D_SIG) {\r
+               if (type == T1_TYPE_RAW) {\r
+                       mqc_setcurctx(mqc, t1_3d_getctxno_mag(flag, flagsvr));  /* ESSAI */\r
+                       v = raw_decode(raw);\r
+               } else {\r
+                       mqc_setcurctx(mqc, t1_3d_getctxno_mag(flag, flagsvr));\r
+                       v = mqc_decode(mqc);\r
+               }\r
+               t = v ? poshalf : neghalf;\r
+               *dp += *dp < 0 ? -t : t;\r
+               *fsvr |= T1_3D_REFINE;\r
+       }\r
+}                              /* VSC and  BYPASS by Antonin  */\r
+\r
+static void t1_3d_enc_refpass(opj_t1_3d_t *t1, int w, int h, int l, int bpno, int *nmsedec, char type, int cblksty) {\r
+       int i, j, k, m, one, vsc;\r
+       *nmsedec = 0;\r
+       one = 1 << (bpno + T1_NMSEDEC_FRACBITS);\r
+       for (m = 0; m < l; m++){\r
+               for (k = 0; k < h; k += 4) {\r
+                       for (i = 0; i < w; i++) {\r
+                               for (j = k; j < k + 4 && j < h; j++) {\r
+                                       vsc = ((cblksty & J3D_CCP_CBLKSTY_VSC) && (j == k + 3 || j == h - 1)) ? 1 : 0;\r
+                                       t1_3d_enc_refpass_step(t1, &t1->flags[1 + m][1 + j][1 + i], &t1->flagSVR[1 + m][1 + j][1 + i], &t1->data[m][j][i], bpno, one, nmsedec, type, vsc);\r
+                               }\r
+                       }\r
+               }\r
+       }       \r
+}\r
+\r
+static void t1_3d_dec_refpass(opj_t1_3d_t *t1, int w, int h, int l, int bpno, char type, int cblksty) {\r
+       int i, j, k, m, one, poshalf, neghalf;\r
+       int vsc;\r
+       one = 1 << bpno;\r
+       poshalf = one >> 1;\r
+       neghalf = bpno > 0 ? -poshalf : -1;\r
+       for (m = 0; m < l; m++) {\r
+               for (k = 0; k < h; k += 4) {\r
+                       for (i = 0; i < w; i++) {\r
+                               for (j = k; j < k + 4 && j < h; j++) {\r
+                                       vsc = ((cblksty & J3D_CCP_CBLKSTY_VSC) && (j == k + 3 || j == h - 1)) ? 1 : 0;\r
+                                       t1_3d_dec_refpass_step(t1, &t1->flags[1 + m][1 + j][1 + i], &t1->flagSVR[1 + m][1 + j][1 + i], &t1->data[m][j][i], poshalf, neghalf, type, vsc);\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+}                              /* VSC and  BYPASS by Antonin */\r
+\r
+static void t1_3d_enc_clnpass_step(opj_t1_3d_t *t1, unsigned int *fp, int *fsvr, int *dp, int orient, int bpno, int one, int *nmsedec, int partial, int vsc) {\r
+       int v, flagsvr;\r
+       unsigned int flag;\r
+\r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       flag = vsc ? ((*fp) & (~(T1_3D_SIG_S | T1_3D_SIG_SE | T1_3D_SIG_SW | (T1_3D_SGN_S << 16)))) : (*fp);\r
+       flagsvr = (*fsvr);\r
+       if (partial) {\r
+               goto LABEL_PARTIAL;\r
+       }\r
+       if (!(*fsvr & (T1_3D_SIG | T1_3D_VISIT))) {\r
+               mqc_setcurctx(mqc, t1_3d_getctxno_zc(flag, orient));\r
+               v = int_abs(*dp) & one ? 1 : 0;\r
+               mqc_encode(mqc, v);\r
+               if (v) {\r
+LABEL_PARTIAL:\r
+                       *nmsedec += t1_3d_getnmsedec_sig(t1, int_abs(*dp), bpno + T1_NMSEDEC_FRACBITS);\r
+                       mqc_setcurctx(mqc, t1_3d_getctxno_sc(flag));\r
+                       v = *dp < 0 ? 1 : 0;\r
+                       mqc_encode(mqc, v ^ t1_3d_getspb(flag));\r
+                       t1_3d_updateflags(fp, v);\r
+                       *fsvr |= T1_3D_SIG;\r
+               }\r
+       }\r
+       *fsvr &= ~T1_3D_VISIT;\r
+}\r
+\r
+static void t1_3d_dec_clnpass_step(opj_t1_3d_t *t1, unsigned int *fp, int *fsvr, int *dp, int orient, int oneplushalf, int partial, int vsc) {\r
+       int v, flagsvr;\r
+       unsigned int flag;\r
+\r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       flag = vsc ? ((*fp) & (~(T1_3D_SIG_S | T1_3D_SIG_SE | T1_3D_SIG_SW | (T1_3D_SGN_S << 16)))) : (*fp);\r
+       flagsvr = (*fsvr);\r
+       if (partial) {\r
+               goto LABEL_PARTIAL;\r
+       }\r
+       if (!(flagsvr & (T1_3D_SIG | T1_3D_VISIT))) {\r
+               mqc_setcurctx(mqc, t1_3d_getctxno_zc(flag, orient));\r
+               if (mqc_decode(mqc)) {\r
+LABEL_PARTIAL:\r
+                       mqc_setcurctx(mqc, t1_3d_getctxno_sc(flag));\r
+                       v = mqc_decode(mqc) ^ t1_3d_getspb(flag);\r
+                       *dp = v ? -oneplushalf : oneplushalf;\r
+                       t1_3d_updateflags(fp, v);\r
+                       *fsvr |= T1_3D_SIG;\r
+               }\r
+       }\r
+       *fsvr &= ~T1_3D_VISIT;\r
+}                              /* VSC and  BYPASS by Antonin */\r
+\r
+static void t1_3d_enc_clnpass(opj_t1_3d_t *t1, int w, int h, int l, int bpno, int orient, int *nmsedec, int cblksty) {\r
+       int i, j, k, m, one, agg, runlen, vsc;\r
+       \r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       *nmsedec = 0;\r
+       one = 1 << (bpno + T1_NMSEDEC_FRACBITS);\r
+       for (m = 0; m < l; m++) {\r
+               for (k = 0; k < h; k += 4) {\r
+                       for (i = 0; i < w; i++) {\r
+                               if (k + 3 < h) {\r
+                                       if (cblksty & J3D_CCP_CBLKSTY_VSC) {\r
+                                               agg = !( ((t1->flagSVR[1 + m][1 + k][1 + i] | (T1_3D_SIG | T1_3D_VISIT)) & (t1->flags[1 + m][1 + k][1 + i] & T1_3D_SIG_OTH))\r
+                                                       ||   ((t1->flagSVR[1 + m][1 + k + 1][1 + i] | (T1_3D_SIG | T1_3D_VISIT)) & (t1->flags[1 + m][1 + k + 1][1 + i] & T1_3D_SIG_OTH))\r
+                                                       ||   ((t1->flagSVR[1 + m][1 + k + 2][1 + i] | (T1_3D_SIG | T1_3D_VISIT)) & (t1->flags[1 + m][1 + k + 2][1 + i] & T1_3D_SIG_OTH))\r
+                                                       ||   ((t1->flagSVR[1 + m][1 + k + 3][1 + i] | (T1_3D_SIG | T1_3D_VISIT)) & ((t1->flags[1 + m][1 + k + 3][1 + i] & (~(T1_3D_SIG_S | T1_3D_SIG_SE | T1_3D_SIG_SW | (T1_3D_SGN_S << 16)))) & (T1_3D_SIG_OTH)))\r
+                                                       );\r
+                                       } else {\r
+                                               agg = !(\r
+                                                       ((t1->flagSVR[1 + m][1 + k][1 + i] & (T1_3D_SIG | T1_3D_VISIT)) | (t1->flags[1 + m][1 + k][1 + i] & T1_3D_SIG_OTH))\r
+                                                       || ((t1->flagSVR[1 + m][1 + k + 1][1 + i] & (T1_3D_SIG | T1_3D_VISIT)) | (t1->flags[1 + m][1 + k + 1][1 + i] & T1_3D_SIG_OTH))\r
+                                                       || ((t1->flagSVR[1 + m][1 + k + 2][1 + i] & (T1_3D_SIG | T1_3D_VISIT)) | (t1->flags[1 + m][1 + k + 2][1 + i] & T1_3D_SIG_OTH))\r
+                                                       || ((t1->flagSVR[1 + m][1 + k + 3][1 + i] & (T1_3D_SIG | T1_3D_VISIT)) | (t1->flags[1 + m][1 + k + 3][1 + i] & T1_3D_SIG_OTH))\r
+                                                       );\r
+                                       }\r
+                               } else {\r
+                                       agg = 0;\r
+                               }\r
+                               if (agg) {\r
+                                       for (runlen = 0; runlen < 4; runlen++) {\r
+                                               if (int_abs(t1->data[m][k + runlen][i]) & one)\r
+                                                       break;\r
+                                       }\r
+                                       mqc_setcurctx(mqc, T1_CTXNO_AGG);\r
+                                       mqc_encode(mqc, runlen != 4);\r
+                                       if (runlen == 4) {\r
+                                               continue;\r
+                                       }\r
+                                       mqc_setcurctx(mqc, T1_CTXNO_UNI);\r
+                                       mqc_encode(mqc, runlen >> 1);\r
+                                       mqc_encode(mqc, runlen & 1);\r
+                               } else {\r
+                                       runlen = 0;\r
+                               }\r
+                               for (j = k + runlen; j < k + 4 && j < h; j++) {\r
+                                       vsc = ((cblksty & J3D_CCP_CBLKSTY_VSC) && (j == k + 3 || j == h - 1)) ? 1 : 0;\r
+                                       t1_3d_enc_clnpass_step(t1, &t1->flags[1 + m][1 + j][1 + i], &t1->flagSVR[1 + m][1 + j][1 + i], &t1->data[m][j][i], orient, bpno, one, nmsedec, agg && (j == k + runlen), vsc);\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+}\r
+\r
+static void t1_3d_dec_clnpass(opj_t1_3d_t *t1, int w, int h, int l, int bpno, int orient, int cblksty) {\r
+       int i, j, k, m, one, half, oneplushalf, agg, runlen, vsc;\r
+       int segsym = cblksty & J3D_CCP_CBLKSTY_SEGSYM;\r
+       \r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       one = 1 << bpno;\r
+       half = one >> 1;\r
+       oneplushalf = one | half;\r
+       for (m = 0; m < l; m++) {\r
+               for (k = 0; k < h; k += 4) {\r
+                       for (i = 0; i < w; i++) {\r
+                               if (k + 3 < h) {\r
+                                       if (cblksty & J3D_CCP_CBLKSTY_VSC) {\r
+                                               agg = !(\r
+                                                       ((t1->flagSVR[1 + m][1 + k][1 + i] & (T1_3D_SIG | T1_3D_VISIT)) | (t1->flags[1 + m][1 + k][1 + i] & T1_3D_SIG_OTH))\r
+                                                       || ((t1->flagSVR[1 + m][1 + k + 1][1 + i] & (T1_3D_SIG | T1_3D_VISIT)) | (t1->flags[1 + m][1 + k + 1][1 + i] & T1_3D_SIG_OTH))\r
+                                                       || ((t1->flagSVR[1 + m][1 + k + 2][1 + i] & (T1_3D_SIG | T1_3D_VISIT)) | (t1->flags[1 + m][1 + k + 2][1 + i] & T1_3D_SIG_OTH))\r
+                                                       || ((t1->flagSVR[1 + m][1 + k + 3][1 + i] & (T1_3D_SIG | T1_3D_VISIT)) | ((t1->flags[1 + m][1 + k + 3][1 + i] & (~(T1_3D_SIG_S | T1_3D_SIG_SE | T1_3D_SIG_SW | (T1_3D_SGN_S << 16)))) & (T1_3D_SIG_OTH)))\r
+                                                       );\r
+                                       } else {\r
+                                               agg = !(\r
+                                                       ((t1->flagSVR[1 + m][1 + k][1 + i] & (T1_3D_SIG | T1_3D_VISIT)) | (t1->flags[1 + m][1 + k][1 + i] & T1_3D_SIG_OTH))\r
+                                                       || ((t1->flagSVR[1 + m][1 + k + 1][1 + i] & (T1_3D_SIG | T1_3D_VISIT)) | (t1->flags[1 + m][1 + k + 1][1 + i] & T1_3D_SIG_OTH))\r
+                                                       || ((t1->flagSVR[1 + m][1 + k + 2][1 + i] & (T1_3D_SIG | T1_3D_VISIT)) | (t1->flags[1 + m][1 + k + 2][1 + i] & T1_3D_SIG_OTH))\r
+                                                       || ((t1->flagSVR[1 + m][1 + k + 3][1 + i] & (T1_3D_SIG | T1_3D_VISIT)) | (t1->flags[1 + m][1 + k + 3][1 + i] & T1_3D_SIG_OTH))\r
+                                                       );\r
+                                       }\r
+                               } else {\r
+                                       agg = 0;\r
+                               }\r
+                               if (agg) {\r
+                                       mqc_setcurctx(mqc, T1_CTXNO_AGG);\r
+                                       if (!mqc_decode(mqc)) {\r
+                                               continue;\r
+                                       }\r
+                                       mqc_setcurctx(mqc, T1_CTXNO_UNI);\r
+                                       runlen = mqc_decode(mqc);\r
+                                       runlen = (runlen << 1) | mqc_decode(mqc);\r
+                               } else {\r
+                                       runlen = 0;\r
+                               }\r
+                               for (j = k + runlen; j < k + 4 && j < h; j++) {\r
+                                       vsc = ((cblksty & J3D_CCP_CBLKSTY_VSC) && (j == k + 3 || j == h - 1)) ? 1 : 0;\r
+                                       t1_3d_dec_clnpass_step(t1, &t1->flags[1 + m][1 + j][1 + i], &t1->flagSVR[1 + m][1 + j][1 + i], &t1->data[m][j][i], orient, oneplushalf, agg && (j == k + runlen), vsc);\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+       if (segsym) {\r
+               int v = 0;\r
+               mqc_setcurctx(mqc, T1_CTXNO_UNI);\r
+               v = mqc_decode(mqc);\r
+               v = (v << 1) | mqc_decode(mqc);\r
+               v = (v << 1) | mqc_decode(mqc);\r
+               v = (v << 1) | mqc_decode(mqc);\r
+               /*\r
+               if (v!=0xa) {\r
+                       opj_event_msg(t1->cinfo, EVT_WARNING, "Bad segmentation symbol %x\n", v);\r
+               } \r
+               */\r
+       }\r
+}                              /* VSC and  BYPASS by Antonin */\r
+\r
+\r
+static void t1_3d_encode_cblk(opj_t1_3d_t *t1, opj_tcd_cblk_t * cblk, int orient, int compno, int level[3], int dwtid[3], double stepsize, int cblksty, int numcomps, opj_tcd_tile_t * tile) {\r
+       int i, j, k;\r
+       int w, h, l;\r
+       int passno;\r
+       int bpno, passtype;\r
+       int max;\r
+       int nmsedec = 0;\r
+       double cumwmsedec = 0;\r
+       char type = T1_TYPE_MQ;\r
+       \r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       w = cblk->x1 - cblk->x0;\r
+       h = cblk->y1 - cblk->y0;\r
+       l = cblk->z1 - cblk->z0;\r
+\r
+       max = 0;\r
+       for (k = 0; k < l; k++) {\r
+               for (j = 0; j < h; j++) {\r
+                       for (i = 0; i < w; i++) {\r
+                               max = int_max(max, int_abs(t1->data[k][j][i]));\r
+                       }\r
+               }\r
+       }\r
+       for (k = 0; k <= l; k++) {\r
+               for (j = 0; j <= h; j++) {\r
+                       for (i = 0; i <= w; i++) {\r
+                               t1->flags[k][j][i] = 0;\r
+                               t1->flagSVR[k][j][i] = 0;\r
+                       }\r
+               }\r
+       }\r
+       \r
+       cblk->numbps = max ? (int_floorlog2(max) + 1) - T1_NMSEDEC_FRACBITS : 0;\r
+       \r
+       bpno = cblk->numbps - 1;\r
+       passtype = 2;\r
+       \r
+       mqc_reset_enc(mqc);\r
+       mqc_init_enc(mqc, cblk->data);\r
+       \r
+       for (passno = 0; bpno >= 0; passno++) {\r
+               opj_tcd_pass_t *pass = &cblk->passes[passno];\r
+               int correction = 3;\r
+               double tmpwmsedec;\r
+               type = ((bpno < (cblk->numbps - 4)) && (passtype < 2) && (cblksty & J3D_CCP_CBLKSTY_LAZY)) ? T1_TYPE_RAW : T1_TYPE_MQ;\r
+               \r
+               switch (passtype) {\r
+                       case 0:\r
+                               t1_3d_enc_sigpass(t1, w, h, l, bpno, orient, &nmsedec, type, cblksty);\r
+                               break;\r
+                       case 1:\r
+                               t1_3d_enc_refpass(t1, w, h, l, bpno, &nmsedec, type, cblksty);\r
+                               break;\r
+                       case 2:\r
+                               t1_3d_enc_clnpass(t1, w, h, l, bpno, orient, &nmsedec, cblksty);\r
+                               /* code switch SEGMARK (i.e. SEGSYM) */\r
+                               if (cblksty & J3D_CCP_CBLKSTY_SEGSYM)\r
+                                       mqc_segmark_enc(mqc);\r
+                               break;\r
+               }\r
+               \r
+               /* fixed_quality */\r
+               tmpwmsedec = t1_getwmsedec(nmsedec, compno, level, orient, bpno, stepsize, numcomps, dwtid);\r
+               cumwmsedec += tmpwmsedec;\r
+               tile->distotile += tmpwmsedec;\r
+               \r
+               /* Code switch "RESTART" (i.e. TERMALL) */\r
+               if ((cblksty & J3D_CCP_CBLKSTY_TERMALL) && !((passtype == 2) && (bpno - 1 < 0))) {\r
+                       if (type == T1_TYPE_RAW) {\r
+                               mqc_flush(mqc);\r
+                               correction = 1;\r
+                               /* correction = mqc_bypass_flush_enc(); */\r
+                       } else {                        /* correction = mqc_restart_enc(); */\r
+                               mqc_flush(mqc);\r
+                               correction = 1;\r
+                       }\r
+                       pass->term = 1;\r
+               } else {\r
+                       if (((bpno < (cblk->numbps - 4) && (passtype > 0)) \r
+                               || ((bpno == (cblk->numbps - 4)) && (passtype == 2))) && (cblksty & J3D_CCP_CBLKSTY_LAZY)) {\r
+                               if (type == T1_TYPE_RAW) {\r
+                                       mqc_flush(mqc);\r
+                                       correction = 1;\r
+                               } else {        \r
+                                       mqc_flush(mqc);\r
+                                       correction = 1;\r
+                               }\r
+                               pass->term = 1;\r
+                       } else {\r
+                               pass->term = 0;\r
+                       }\r
+               }\r
+               \r
+               if (++passtype == 3) {\r
+                       passtype = 0;\r
+                       bpno--;\r
+               }\r
+               \r
+               if (pass->term && bpno > 0) {\r
+                       type = ((bpno < (cblk->numbps - 4)) && (passtype < 2) && (cblksty & J3D_CCP_CBLKSTY_LAZY)) ? T1_TYPE_RAW : T1_TYPE_MQ;\r
+                       if (type == T1_TYPE_RAW)\r
+                               mqc_bypass_init_enc(mqc);\r
+                       else\r
+                               mqc_restart_init_enc(mqc);\r
+               }\r
+               \r
+               pass->distortiondec = cumwmsedec;\r
+               pass->rate = mqc_numbytes(mqc) + correction;    /* FIXME */\r
+               pass->len = pass->rate - (passno == 0 ? 0 : cblk->passes[passno - 1].rate);\r
+\r
+               /* Code-switch "RESET" */\r
+               if (cblksty & J3D_CCP_CBLKSTY_RESET)\r
+                       mqc_reset_enc(mqc);\r
+       }\r
+       \r
+       /* Code switch "ERTERM" (i.e. PTERM) */\r
+       if (cblksty & J3D_CCP_CBLKSTY_PTERM)\r
+               mqc_erterm_enc(mqc);\r
+       else /* Default coding */ if (!(cblksty & J3D_CCP_CBLKSTY_LAZY))\r
+               mqc_flush(mqc);\r
+       \r
+       cblk->totalpasses = passno;\r
+}\r
+\r
+static void t1_3d_decode_cblk(opj_t1_3d_t *t1, opj_tcd_cblk_t * cblk, int orient, int roishift, int cblksty) {\r
+       int i, j, k;\r
+       int w, h, l;\r
+       int bpno, passtype;\r
+       int segno, passno;\r
+       char type = T1_TYPE_MQ; /* BYPASS mode */\r
+       opj_raw_t *raw = t1->raw;       /* RAW component */\r
+       opj_mqc_t *mqc = t1->mqc;       /* MQC component */\r
+       \r
+       w = cblk->x1 - cblk->x0;\r
+       h = cblk->y1 - cblk->y0;\r
+       l = cblk->z1 - cblk->z0;\r
+\r
+    for (k = 0; k < l; k++) {\r
+               for (j = 0; j < h; j++) {\r
+                       for (i = 0; i < w; i++) {\r
+                               t1->data[k][j][i] = 0;\r
+                       }\r
+               }\r
+       }\r
+       \r
+       for (k = 0; k <= l; k++) {\r
+               for (j = 0; j <= h; j++) {\r
+                       for (i = 0; i <= w; i++) {\r
+                               t1->flags[k][j][i] = 0;\r
+                               t1->flagSVR[k][j][i] = 0;\r
+                       }\r
+               }\r
+       }\r
+\r
+       \r
+       bpno = roishift + cblk->numbps - 1;\r
+       passtype = 2;\r
+       \r
+       mqc_reset_enc(mqc);\r
+       \r
+       for (segno = 0; segno < cblk->numsegs; segno++) {\r
+               opj_tcd_seg_t *seg = &cblk->segs[segno];\r
+               \r
+               /* BYPASS mode */\r
+               type = ((bpno <= (cblk->numbps - 1) - 4) && (passtype < 2) && (cblksty & J3D_CCP_CBLKSTY_LAZY)) ? T1_TYPE_RAW : T1_TYPE_MQ;\r
+               if (type == T1_TYPE_RAW) {\r
+                       raw_init_dec(raw, seg->data, seg->len);\r
+               } else {\r
+                       mqc_init_dec(mqc, seg->data, seg->len);\r
+               }\r
+               \r
+               for (passno = 0; passno < seg->numpasses; passno++) {\r
+                       switch (passtype) {\r
+                               case 0:\r
+                                       t1_3d_dec_sigpass(t1, w, h, l, bpno+1, orient, type, cblksty);\r
+                                       break;\r
+                               case 1:\r
+                                       t1_3d_dec_refpass(t1, w, h, l, bpno+1, type, cblksty);\r
+                                       break;\r
+                               case 2:\r
+                                       t1_3d_dec_clnpass(t1, w, h, l, bpno+1, orient, cblksty);\r
+                                       break;\r
+                       }\r
+                       \r
+                       if ((cblksty & J3D_CCP_CBLKSTY_RESET) && type == T1_TYPE_MQ) {\r
+                               mqc_reset_enc(mqc);\r
+                       }\r
+                       if (++passtype == 3) {\r
+                               passtype = 0;\r
+                               bpno--;\r
+                       }\r
+\r
+               }\r
+       }\r
+}\r
+\r
+static int t1_3d_init_ctxno_zc(unsigned int f, int orient) {\r
+       unsigned int h, v, c;\r
+       unsigned int d2xy, d2xz, d2yz, d3;\r
+       int n;\r
+       unsigned int hvc, hc, d2, d2xy2yz, d2xy2xz;\r
+       n = 0;\r
+       h = ((f & T1_3D_SIG_W) != 0) + ((f & T1_3D_SIG_E) != 0);\r
+       v = ((f & T1_3D_SIG_N) != 0) + ((f & T1_3D_SIG_S) != 0);\r
+       c = ((f & T1_3D_SIG_FC) != 0) + ((f & T1_3D_SIG_BC) != 0);\r
+       d2xy = ((f & T1_3D_SIG_NW) != 0) + ((f & T1_3D_SIG_NE) != 0) + ((f & T1_3D_SIG_SE) != 0) + ((f & T1_3D_SIG_SW) != 0);\r
+       d2xz = ((f & T1_3D_SIG_FW) != 0) + ((f & T1_3D_SIG_BW) != 0) + ((f & T1_3D_SIG_FE) != 0) + ((f & T1_3D_SIG_BE) != 0);\r
+       d2yz = ((f & T1_3D_SIG_FN) != 0) + ((f & T1_3D_SIG_FS) != 0) + ((f & T1_3D_SIG_BN) != 0) + ((f & T1_3D_SIG_BS) != 0);\r
+    d3 = ((f & T1_3D_SIG_FNW) != 0) + ((f & T1_3D_SIG_FNE) != 0) + ((f & T1_3D_SIG_FSE) != 0) + ((f & T1_3D_SIG_FSW) != 0) \r
+               + ((f & T1_3D_SIG_BNW) != 0) + ((f & T1_3D_SIG_BNE) != 0) + ((f & T1_3D_SIG_BSE) != 0) + ((f & T1_3D_SIG_BSW) != 0);\r
+       \r
+       switch (orient) {\r
+               case 0: //LLL\r
+               case 7: //HHH\r
+                       hvc = h + v + c;\r
+                       d2 = d2xy + d2xz + d2yz;\r
+                       if (!hvc) {\r
+                               if (!d2) {\r
+                    n = (!d3) ? 0 : 1;\r
+                               } else if (d2 == 1) {\r
+                                       n = (!d3) ? 2 : 3;\r
+                               } else {\r
+                                       n = (!d3) ? 4 : 5;\r
+                               }\r
+                       } else if (hvc == 1) {\r
+                               if (!d2) {\r
+                    n = (!d3) ? 6 : 7;\r
+                               } else if (d2 == 1) {\r
+                                       n = (!d3) ? 8 : 9;\r
+                               } else {\r
+                                       n = 10;\r
+                               }\r
+                       } else if (hvc == 2) {\r
+                               if (!d2) {\r
+                    n = (!d3) ? 11 : 12;\r
+                               } else {\r
+                                       n = 13;\r
+                               }\r
+                       } else if (hvc == 3) {\r
+                               n = 14;\r
+                       } else {\r
+                               n = 15;\r
+                       }\r
+                       break;\r
+               //LHL, HLL, LLH\r
+               case 1:\r
+               case 2:\r
+               case 4:\r
+                       hc = h + c;\r
+                       d2xy2yz = d2xy + d2yz;\r
+            if (!hc) {\r
+                               if (!v) {\r
+                                       if (!d2xy) {\r
+                                               n = (!d2xy2yz) ? ((!d3) ? 0 : 1) : ((!d3) ? 2 : 3);     \r
+                                       } else if (d2xy == 1) {\r
+                                               n = (!d2xy2yz) ? ((!d3) ? 4 : 5) : 6;   \r
+                                       } else { //>=2\r
+                        n = 7;\r
+                                       }\r
+                               } else {\r
+                                       n = (v == 1) ? 8 : 9; // =1 or =2\r
+                               } \r
+                       } else if (hc == 1) {\r
+                               n = (!v) ? ( (!d2xy) ? ( (!d2xy2yz) ? ( (!d3) ? 10 : 11) : (12) ) : (13) ) : (14);\r
+                       } else { //if (hc >= 2)\r
+                               n = 15;\r
+                       }\r
+                       break;\r
+               //HLH, HHL, LHH\r
+               case 3:\r
+               case 5:\r
+               case 6:\r
+                       hc = h + c;\r
+                       d2xy2xz = d2xy + d2xz;\r
+                       if (!v) {\r
+                               if (!d2xz) {\r
+                                       if (!hc && !d2xy2xz) {\r
+                                               n = (!d3) ? 0 : 1;\r
+                                       } else if (hc == 1) {\r
+                                               n = (!d2xy2xz) ?  2 : 3;\r
+                                       } else { //if >= 2\r
+                                               n = 4;\r
+                                       }\r
+                               } else if ( d2xz>=1 && !hc ) {\r
+                                       n = 5;\r
+                               } else if ( hc>=1 ) {\r
+                                       n = (d2xz==1) ? 6 : 7;\r
+                               } \r
+                       } else if (v == 1) {\r
+                               if (!d2xz) {\r
+                                       n = (!hc) ? 8 : 9;\r
+                               } else if (d2xz == 1) {\r
+                                       n = (!hc) ? 10 : 11;\r
+                               } else if (d2xz == 2) {\r
+                                       n = (!hc) ? 12 : 13;\r
+                               } else { // if (d2xz >= 3) {\r
+                                       n = 14;\r
+                               }\r
+                       } else if (v == 2) {\r
+                               n = 15;\r
+                       } \r
+                       break;\r
+       }\r
+       \r
+       return (T1_3D_CTXNO_ZC + n);\r
+}\r
+\r
+static int t1_3d_init_ctxno_sc(unsigned int f) {\r
+       int hc, vc, cc;\r
+       int n = 0;\r
+\r
+       hc = int_min( ( (f & (T1_3D_SIG_E | T1_3D_SGN_E)) == T1_3D_SIG_E ) \r
+                                       + ( (f & (T1_3D_SIG_W | T1_3D_SGN_W)) == T1_3D_SIG_W ) , 1) \r
+               - int_min( ( (f & (T1_3D_SIG_E | T1_3D_SGN_E)) == (T1_3D_SIG_E | T1_3D_SGN_E) ) \r
+                                       + ( (f & (T1_3D_SIG_W | T1_3D_SGN_W) ) == (T1_3D_SIG_W | T1_3D_SGN_W)), 1);\r
+       \r
+       vc = int_min(((f & (T1_3D_SIG_N | T1_3D_SGN_N)) == T1_3D_SIG_N) \r
+                                       + ((f & (T1_3D_SIG_S | T1_3D_SGN_S)) == T1_3D_SIG_S), 1) \r
+               - int_min(((f & (T1_3D_SIG_N | T1_3D_SGN_N)) == (T1_3D_SIG_N | T1_3D_SGN_N)) \r
+                                       + ((f & (T1_3D_SIG_S | T1_3D_SGN_S)) == (T1_3D_SIG_S | T1_3D_SGN_S)), 1);\r
+       \r
+       cc = int_min(((f & (T1_3D_SIG_FC | T1_3D_SGN_F)) == T1_3D_SIG_FC) \r
+                                       + ((f & (T1_3D_SIG_BC | T1_3D_SGN_B)) == T1_3D_SIG_BC), 1) \r
+               - int_min(((f & (T1_3D_SIG_FC | T1_3D_SGN_F)) == (T1_3D_SIG_FC | T1_3D_SGN_F)) \r
+                                       + ((f & (T1_3D_SIG_BC | T1_3D_SGN_B)) == (T1_3D_SIG_BC | T1_3D_SGN_B)), 1);\r
+       if (hc < 0) {\r
+               hc = -hc;\r
+               vc = -vc;\r
+               cc = -cc;\r
+       }\r
+\r
+       if (!hc) {\r
+               if (!vc) \r
+                       n = (!cc) ? 0 : 1;\r
+               else if (vc == -1)\r
+                       n = (!cc) ? 1 : ( (cc>0) ? 2 : 4);\r
+               else if (vc == 1)\r
+                       n = (!cc) ? 1 : ( (cc<0) ? 2 : 4);\r
+       } else if (hc == 1) {\r
+               if (!vc)\r
+                       n = (!cc) ? 1 : ( (cc<0) ? 2 : 4);\r
+               else if (vc == 1)\r
+                       n = (!cc) ? 4 : ( (cc>0) ? 5 : 3);\r
+               else if (vc == -1)\r
+                       n = (!cc) ? 2 : 3;\r
+       } else if (hc == -1) {\r
+               if (!vc)\r
+                       n = (!cc) ? 1 : ( (cc>0) ? 2 : 4);\r
+               else if (vc == 1)\r
+                       n = (!cc) ? 2 : 3;\r
+               else if (vc == -1)\r
+                       n = (!cc) ? 4 : ( (cc<0) ? 5 : 3);\r
+       }\r
+       \r
+       return (T1_3D_CTXNO_SC + n);\r
+}\r
+\r
+static int t1_3d_init_ctxno_mag(unsigned int f, int f2) {\r
+       int n;\r
+       if (!(f2 & T1_3D_REFINE))       //First refinement for this coefficient (no previous refinement)\r
+               n = (f & (T1_3D_SIG_PRIM)) ? 1 : 0;\r
+       else\r
+               n = 2;\r
+       \r
+       return (T1_3D_CTXNO_MAG + n);\r
+}\r
+\r
+static int t1_3d_init_spb(unsigned int f) {\r
+       int hc, vc, cc;\r
+       int n = 0;\r
+       \r
+       hc = int_min( ( (f & (T1_3D_SIG_E | T1_3D_SGN_E)) == T1_3D_SIG_E ) \r
+                                       + ( (f & (T1_3D_SIG_W | T1_3D_SGN_W)) == T1_3D_SIG_W ) , 1) \r
+               - int_min( ( (f & (T1_3D_SIG_E | T1_3D_SGN_E)) == (T1_3D_SIG_E | T1_3D_SGN_E) ) \r
+                                       + ( (f & (T1_3D_SIG_W | T1_3D_SGN_W) ) == (T1_3D_SIG_W | T1_3D_SGN_W)), 1);\r
+       \r
+       vc = int_min(((f & (T1_3D_SIG_N | T1_3D_SGN_N)) == T1_3D_SIG_N) \r
+                                       + ((f & (T1_3D_SIG_S | T1_3D_SGN_S)) == T1_3D_SIG_S), 1) \r
+               - int_min(((f & (T1_3D_SIG_N | T1_3D_SGN_N)) == (T1_3D_SIG_N | T1_3D_SGN_N)) \r
+                                       + ((f & (T1_3D_SIG_S | T1_3D_SGN_S)) == (T1_3D_SIG_S | T1_3D_SGN_S)), 1);\r
+       \r
+       cc = int_min(((f & (T1_3D_SIG_FC | T1_3D_SGN_F)) == T1_3D_SIG_FC) \r
+                                       + ((f & (T1_3D_SIG_BC | T1_3D_SGN_B)) == T1_3D_SIG_BC), 1) \r
+               - int_min(((f & (T1_3D_SIG_FC | T1_3D_SGN_F)) == (T1_3D_SIG_FC | T1_3D_SGN_F)) \r
+                                       + ((f & (T1_3D_SIG_BC | T1_3D_SGN_B)) == (T1_3D_SIG_BC | T1_3D_SGN_B)), 1);\r
+       \r
+       n = ((hc + vc + cc) < 0); \r
+       \r
+       return n;\r
+}\r
+\r
+static void t1_3d_init_luts(opj_t1_3d_t *t1) {\r
+       int i;\r
+       double u, v, t;\r
+       /*for (j = 0; j < 4; j++) {\r
+               for (i = 0; i < 256; ++i) {\r
+                       t1->lut_ctxno_zc[(j << 8) | i] = t1_3d_init_ctxno_zc(i, j);\r
+               }\r
+       }\r
+       for (i = 0; i < 4096; i++) {\r
+               t1->lut_ctxno_sc[i] = t1_3d_init_ctxno_sc(i << 4);\r
+       }\r
+       for (j = 0; j < 2; j++) {\r
+               for (i = 0; i < 2048; ++i) {\r
+                       t1->lut_ctxno_mag[(j << 11) + i] = t1_3d_init_ctxno_mag((j ? T1_3D_REFINE : 0) | i);\r
+               }\r
+       }\r
+       for (i = 0; i < 4096; ++i) {\r
+               t1->lut_spb[i] = t1_3d_init_spb(i << 4);\r
+       }*/\r
+       /* FIXME FIXME FIXME */\r
+       for (i = 0; i < (1 << T1_NMSEDEC_BITS); i++) {\r
+               t = i / pow(2, T1_NMSEDEC_FRACBITS);\r
+               u = t;\r
+               v = t - 1.5;\r
+               t1->lut_nmsedec_sig[i] = \r
+                       int_max(0, \r
+                       (int) (floor((u * u - v * v) * pow(2, T1_NMSEDEC_FRACBITS) + 0.5) / pow(2, T1_NMSEDEC_FRACBITS) * 8192.0));\r
+               t1->lut_nmsedec_sig0[i] =\r
+                       int_max(0,\r
+                       (int) (floor((u * u) * pow(2, T1_NMSEDEC_FRACBITS) + 0.5) / pow(2, T1_NMSEDEC_FRACBITS) * 8192.0));\r
+               u = t - 1.0;\r
+               if (i & (1 << (T1_NMSEDEC_BITS - 1))) {\r
+                       v = t - 1.5;\r
+               } else {\r
+                       v = t - 0.5;\r
+               }\r
+               t1->lut_nmsedec_ref[i] =\r
+                       int_max(0,\r
+                       (int) (floor((u * u - v * v) * pow(2, T1_NMSEDEC_FRACBITS) + 0.5) / pow(2, T1_NMSEDEC_FRACBITS) * 8192.0));\r
+               t1->lut_nmsedec_ref0[i] =\r
+                       int_max(0,\r
+                       (int) (floor((u * u) * pow(2, T1_NMSEDEC_FRACBITS) + 0.5) / pow(2, T1_NMSEDEC_FRACBITS) * 8192.0));\r
+       }\r
+}\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+opj_t1_3d_t* t1_3d_create(opj_common_ptr cinfo) {\r
+       opj_t1_3d_t *t1 = (opj_t1_3d_t*)opj_malloc(sizeof(opj_t1_3d_t));\r
+       if(t1) {\r
+               t1->cinfo = cinfo;\r
+               /* create MQC and RAW handles */\r
+               t1->mqc = mqc_create();\r
+               t1->raw = raw_create();\r
+               /* initialize the look-up tables of the Tier-1 coder/decoder */\r
+               t1_3d_init_luts(t1);\r
+       }\r
+       return t1;\r
+}\r
+\r
+void t1_3d_destroy(opj_t1_3d_t *t1) {\r
+       if(t1) {\r
+               /* destroy MQC and RAW handles */\r
+               mqc_destroy(t1->mqc);\r
+               raw_destroy(t1->raw);\r
+               opj_free(t1);\r
+       }\r
+}\r
+\r
+void t1_3d_encode_cblks(opj_t1_3d_t *t1, opj_tcd_tile_t *tile, opj_tcp_t *tcp) {\r
+       int compno, resno, bandno, precno, cblkno;\r
+       int x, y, z, i, j, k, orient;\r
+       int level[3];\r
+       tile->distotile = 0;            /* fixed_quality */\r
+\r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+\r
+               for (resno = 0; resno < tilec->numresolution[0]; resno++) {\r
+                       opj_tcd_resolution_t *res = &tilec->resolutions[resno];\r
+\r
+                       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                               opj_tcd_band_t *band = &res->bands[bandno];\r
+\r
+                               for (precno = 0; precno < res->prctno[0] * res->prctno[1] * res->prctno[2]; precno++) {\r
+                                       opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+\r
+                                       for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                                               opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+\r
+                                               if (band->bandno == 0) {\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 1) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 2) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 3) {         \r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 4) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 5) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 6) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 7) {         \r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               }\r
+\r
+                                               if (tcp->tccps[compno].reversible == 1) {\r
+                                                       for (k = 0; k < cblk->z1 - cblk->z0; k++) {\r
+                                                               for (j = 0; j < cblk->y1 - cblk->y0; j++) {\r
+                                    for (i = 0; i < cblk->x1 - cblk->x0; i++) {\r
+                                        t1->data[k][j][i] = \r
+                                                                               tilec->data[(x + i) + (y + j) * (tilec->x1 - tilec->x0) + (z + k) * (tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0)] << T1_NMSEDEC_FRACBITS;\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               } else if (tcp->tccps[compno].reversible == 0) {\r
+                                                       for (k = 0; k < cblk->z1 - cblk->z0; k++) {\r
+                                                               for (j = 0; j < cblk->y1 - cblk->y0; j++) {\r
+                                    for (i = 0; i < cblk->x1 - cblk->x0; i++) {\r
+                                        t1->data[k][j][i] = fix_mul(\r
+                                                                               tilec->data[(x + i) + (y + j) * (tilec->x1 - tilec->x0) + (z + k) * (tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0)],\r
+                                                                               8192 * 8192 / ((int) floor(band->stepsize * 8192))) >> (13 - T1_NMSEDEC_FRACBITS);\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                               orient = band->bandno;  /* FIXME */\r
+                                               for (i = 0; i < 3; i++) \r
+                                                       level[i] = tilec->numresolution[i] - 1 - resno;\r
+\r
+                                               t1_3d_encode_cblk(t1, cblk, orient, compno, level, tcp->tccps[compno].dwtid, band->stepsize, tcp->tccps[compno].cblksty, tile->numcomps, tile);\r
+                                                       \r
+                                       } /* cblkno */\r
+                               } /* precno */\r
+                       } /* bandno */\r
+               } /* resno  */\r
+       } /* compno  */\r
+}\r
+\r
+void t1_3d_decode_cblks(opj_t1_3d_t *t1, opj_tcd_tile_t *tile, opj_tcp_t *tcp) {\r
+       int compno, resno, bandno, precno, cblkno;\r
+       \r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+\r
+               for (resno = 0; resno < tilec->numresolution[0]; resno++) {\r
+                       opj_tcd_resolution_t *res = &tilec->resolutions[resno];\r
+\r
+                       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                               opj_tcd_band_t *band = &res->bands[bandno];\r
+\r
+                               for (precno = 0; precno < res->prctno[0] * res->prctno[1] * res->prctno[2]; precno++) {\r
+                                       opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+\r
+                                       for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                                               int x, y, z, i, j, k, orient;\r
+                                               opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+\r
+                                               orient = band->bandno;  /* FIXME */\r
+\r
+                                               //fprintf(stdout,"[INFO] t1_3d_decode_cblk(t1, cblk, orient(%d), tcp->tccps[compno].roishift (%d), tcp->tccps[compno].cblksty (%d));\n",orient,tcp->tccps[compno].roishift, tcp->tccps[compno].cblksty);\r
+                                               t1_3d_decode_cblk(t1, cblk, orient, tcp->tccps[compno].roishift, tcp->tccps[compno].cblksty);\r
+\r
+                                               if (band->bandno == 0) {\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 1) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 2) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 3) {         \r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 4) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 5) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 6) {\r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               } else if (band->bandno == 7) {         \r
+                                                       opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];\r
+                                                       x = pres->x1 - pres->x0 + cblk->x0 - band->x0;\r
+                                                       y = pres->y1 - pres->y0 + cblk->y0 - band->y0;\r
+                                                       z = pres->z1 - pres->z0 + cblk->z0 - band->z0;\r
+                                               }\r
+                                       \r
+                                               if (tcp->tccps[compno].roishift) {\r
+                                                       int thresh, val, mag;\r
+                                                       thresh = 1 << tcp->tccps[compno].roishift;\r
+                                                       for (k = 0; k < cblk->z1 - cblk->z0; k++) {\r
+                                                               for (j = 0; j < cblk->y1 - cblk->y0; j++) {\r
+                                                                       for (i = 0; i < cblk->x1 - cblk->x0; i++) {\r
+                                                                               val = t1->data[k][j][i];\r
+                                                                               mag = int_abs(val);\r
+                                                                               if (mag >= thresh) {\r
+                                                                                       mag >>= tcp->tccps[compno].roishift;\r
+                                                                                       t1->data[k][j][i] = val < 0 ? -mag : mag;\r
+                                                                               }\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                               \r
+                                               if (tcp->tccps[compno].reversible == 1) {\r
+                                                       for (k = 0; k < cblk->z1 - cblk->z0; k++) {\r
+                                                               for (j = 0; j < cblk->y1 - cblk->y0; j++) {\r
+                                                                       for (i = 0; i < cblk->x1 - cblk->x0; i++) {\r
+                                                                               int tmp = t1->data[k][j][i];\r
+                                                                               tilec->data[x + i + (y + j) * (tilec->x1 - tilec->x0) + (z + k) * (tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0)] = tmp/2;\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               } else {                /* if (tcp->tccps[compno].reversible == 0) */\r
+                                                       for (k = 0; k < cblk->z1 - cblk->z0; k++) {\r
+                                                               for (j = 0; j < cblk->y1 - cblk->y0; j++) {\r
+                                                                       for (i = 0; i < cblk->x1 - cblk->x0; i++) {\r
+                                                                               double tmp = (double)(t1->data[k][j][i] * band->stepsize * 4096.0);\r
+                                                                               if (t1->data[k][j][i] >> 1 == 0) {\r
+                                                                                       tilec->data[x + i + (y + j) * (tilec->x1 - tilec->x0) + (z + k) * (tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0)] = 0;\r
+                                                                               } else {\r
+                                                                                       int tmp2 = ((int) (floor(fabs(tmp)))) + ((int) floor(fabs(tmp*2))%2);\r
+                                                                                       tilec->data[x + i + (y + j) * (tilec->x1 - tilec->x0) + (z + k) * (tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0)] = ((tmp<0)?-tmp2:tmp2);\r
+                                                                               }\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                       } /* cblkno */\r
+                               } /* precno */\r
+                       } /* bandno */\r
+               } /* resno */\r
+       } /* compno */\r
+}\r
diff --git a/src/lib/openjp3d/t1_3d.h b/src/lib/openjp3d/t1_3d.h
new file mode 100755 (executable)
index 0000000..dd73763
--- /dev/null
@@ -0,0 +1,173 @@
+/*\r
+ * Copyrigth (c) 2006, Mónica Díez, LPI-UVA, Spain\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
+#ifndef __T1_3D_H\r
+#define __T1_3D_H\r
+/**\r
+@file t1_3d.h\r
+@brief Implementation of the tier-1 coding (coding of code-block coefficients) (T1)\r
+\r
+The functions in T1_3D.C have for goal to realize the tier-1 coding operation of 3D-EBCOT.\r
+The functions in T1_3D.C are used by some function in TCD.C.\r
+*/\r
+\r
+/** @defgroup T1_3D T1_3D - Implementation of the tier-1 coding */\r
+/*@{*/\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+/* Neighbourhood of 3D EBCOT (Significance context)*/\r
+#define T1_3D_SIG_NE  0x00000001       /*< Context orientation : North-East direction */\r
+#define T1_3D_SIG_SE  0x00000002       /*< Context orientation : South-East direction */\r
+#define T1_3D_SIG_SW  0x00000004       /*< Context orientation : South-West direction */\r
+#define T1_3D_SIG_NW  0x00000008       /* Context orientation : North-West direction */\r
+#define T1_3D_SIG_N   0x00000010       /*< Context orientation : North direction */\r
+#define T1_3D_SIG_E   0x00000020       /*< Context orientation : East direction */\r
+#define T1_3D_SIG_S   0x00000040       /*< Context orientation : South direction */\r
+#define T1_3D_SIG_W   0x00000080       /*< Context orientation : West direction */\r
+#define T1_3D_SIG_FC  0x00000100       /*< Context orientation : Forward Central direction */          \r
+#define T1_3D_SIG_BC  0x00000200       /*< Context orientation : Backward Central direction */ \r
+#define T1_3D_SIG_FNE 0x00000400       /*< Context orientation : Forward North-East direction */       \r
+#define T1_3D_SIG_FSE 0x00000800       /*< Context orientation : Forward South-East direction */       \r
+#define T1_3D_SIG_FSW 0x00001000       /*< Context orientation : Forward South-West direction */       \r
+#define T1_3D_SIG_FNW 0x00002000       /*< Context orientation : Forward North-West direction */       \r
+#define T1_3D_SIG_FN  0x00004000       /*< Context orientation : Forward North direction */            \r
+#define T1_3D_SIG_FE  0x00008000       /*< Context orientation : Forward East direction */             \r
+#define T1_3D_SIG_FS  0x00010000       /*< Context orientation : Forward South direction */            \r
+#define T1_3D_SIG_FW  0x00020000       /*< Context orientation : Forward West direction */             \r
+#define T1_3D_SIG_BNE 0x00040000       /*< Context orientation : Backward North-East direction */      \r
+#define T1_3D_SIG_BSE 0x00080000       /*< Context orientation : Backward South-East direction */      \r
+#define T1_3D_SIG_BSW 0x00100000       /*< Context orientation : Backward South-West direction */      \r
+#define T1_3D_SIG_BNW 0x00200000       /*< Context orientation : Backward North-West direction */      \r
+#define T1_3D_SIG_BN  0x00400000       /*< Context orientation : Backward North direction */           \r
+#define T1_3D_SIG_BE  0x00800000       /*< Context orientation : Backward East direction */            \r
+#define T1_3D_SIG_BS  0x01000000       /*< Context orientation : Backward South direction */           \r
+#define T1_3D_SIG_BW  0x02000000       /*< Context orientation : Backward West direction */            \r
+#define T1_3D_SIG_COTH (T1_3D_SIG_N|T1_3D_SIG_NE|T1_3D_SIG_E|T1_3D_SIG_SE|T1_3D_SIG_S|T1_3D_SIG_SW|T1_3D_SIG_W|T1_3D_SIG_NW)\r
+#define T1_3D_SIG_BOTH (T1_3D_SIG_BN|T1_3D_SIG_BNE|T1_3D_SIG_BE|T1_3D_SIG_BSE|T1_3D_SIG_BS|T1_3D_SIG_BSW|T1_3D_SIG_BW|T1_3D_SIG_BNW|T1_3D_SIG_BC)\r
+#define T1_3D_SIG_FOTH  (T1_3D_SIG_FN|T1_3D_SIG_FNE|T1_3D_SIG_FE|T1_3D_SIG_FSE|T1_3D_SIG_FS|T1_3D_SIG_FSW|T1_3D_SIG_FW|T1_3D_SIG_FNW|T1_3D_SIG_FC)\r
+#define T1_3D_SIG_OTH  (T1_3D_SIG_FOTH|T1_3D_SIG_BOTH|T1_3D_SIG_COTH)\r
+#define T1_3D_SIG_PRIM (T1_3D_SIG_N|T1_3D_SIG_E|T1_3D_SIG_S|T1_3D_SIG_W|T1_3D_SIG_FC|T1_3D_SIG_BC)\r
+\r
+#define T1_3D_SGN_N            0x0400          \r
+#define T1_3D_SGN_E            0x0800          \r
+#define T1_3D_SGN_S            0x1000          \r
+#define T1_3D_SGN_W            0x2000          \r
+#define T1_3D_SGN_F            0x4000  \r
+#define T1_3D_SGN_B            0x8000\r
+#define T1_3D_SGN              (T1_3D_SGN_N|T1_3D_SGN_E|T1_3D_SGN_S|T1_3D_SGN_W|T1_3D_SGN_F|T1_3D_SGN_B)\r
+\r
+#define T1_3D_SIG              0x0001  //Significance state\r
+#define T1_3D_REFINE   0x0002  //Delayed significance\r
+#define T1_3D_VISIT            0x0004  //First-pass membership\r
+\r
+#define T1_3D_NUMCTXS_AGG      1\r
+#define T1_3D_NUMCTXS_ZC       16\r
+#define T1_3D_NUMCTXS_MAG      3\r
+#define T1_3D_NUMCTXS_SC       6\r
+#define T1_3D_NUMCTXS_UNI      1\r
+\r
+#define T1_3D_CTXNO_AGG 0\r
+#define T1_3D_CTXNO_ZC (T1_3D_CTXNO_AGG+T1_3D_NUMCTXS_AGG) //1\r
+#define T1_3D_CTXNO_MAG (T1_3D_CTXNO_ZC+T1_3D_NUMCTXS_ZC)      //17\r
+#define T1_3D_CTXNO_SC (T1_3D_CTXNO_MAG+T1_3D_NUMCTXS_MAG)     //20\r
+#define T1_3D_CTXNO_UNI (T1_3D_CTXNO_SC+T1_3D_NUMCTXS_SC)      //26\r
+#define T1_3D_NUMCTXS  (T1_3D_CTXNO_UNI+T1_3D_NUMCTXS_UNI) //27\r
+\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+/**\r
+Tier-1 coding (coding of code-block coefficients)\r
+*/\r
+typedef struct opj_t1_3d {\r
+       /** Codec context */\r
+       opj_common_ptr cinfo;\r
+       /** MQC component */\r
+       opj_mqc_t *mqc;\r
+       /** RAW component */\r
+       opj_raw_t *raw;\r
+       /** LUTs for decoding normalised MSE */\r
+       int lut_nmsedec_sig[1 << T1_NMSEDEC_BITS];\r
+       int lut_nmsedec_sig0[1 << T1_NMSEDEC_BITS];\r
+       int lut_nmsedec_ref[1 << T1_NMSEDEC_BITS];\r
+       int lut_nmsedec_ref0[1 << T1_NMSEDEC_BITS];\r
+       /** Codeblock data */\r
+       int data[T1_CBLKD][T1_CBLKH][T1_CBLKW];\r
+       /** Context information for each voxel in codeblock */\r
+       unsigned int flags[T1_CBLKD + 2][T1_CBLKH + 2][T1_CBLKH + 2];\r
+       /** Voxel information (significance/visited/refined) */\r
+       int flagSVR[T1_CBLKD + 2][T1_CBLKH + 2][T1_CBLKH + 2];\r
+} opj_t1_3d_t;\r
+\r
+/** @name Exported functions */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Create a new T1_3D handle \r
+and initialize the look-up tables of the Tier-1 coder/decoder\r
+@return Returns a new T1 handle if successful, returns NULL otherwise\r
+@see t1_init_luts\r
+*/\r
+opj_t1_3d_t* t1_3d_create(opj_common_ptr cinfo);\r
+/**\r
+Destroy a previously created T1_3D handle\r
+@param t1 T1_3D handle to destroy\r
+*/\r
+void t1_3d_destroy(opj_t1_3d_t *t1);\r
+/**\r
+Encode the code-blocks of a tile\r
+@param t1 T1_3D handle\r
+@param tile The tile to encode\r
+@param tcp Tile coding parameters\r
+*/\r
+void t1_3d_encode_cblks(opj_t1_3d_t *t1, opj_tcd_tile_t *tile, opj_tcp_t *tcp);\r
+/**\r
+Decode the code-blocks of a tile\r
+@param t1 T1_3D handle\r
+@param tile The tile to decode\r
+@param tcp Tile coding parameters\r
+*/\r
+void t1_3d_decode_cblks(opj_t1_3d_t *t1, opj_tcd_tile_t *tile, opj_tcp_t *tcp);\r
+/**\r
+Get weigths of MSE decoding\r
+@param nmsedec The normalized MSE reduction\r
+@param compno \r
+@param level \r
+@param orient\r
+@param bpno\r
+@param reversible\r
+@param stepsize\r
+@param numcomps\r
+@param dwtid\r
+returns MSE associated to decoding pass\r
+double t1_3d_getwmsedec(int nmsedec, int compno, int levelxy, int levelz, int orient, int bpno, int reversible, double stepsize, int numcomps, int dwtid);\r
+*/\r
+/* ----------------------------------------------------------------------- */\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* __T1_H */\r
diff --git a/src/lib/openjp3d/t2.c b/src/lib/openjp3d/t2.c
new file mode 100755 (executable)
index 0000000..6638b32
--- /dev/null
@@ -0,0 +1,675 @@
+/*\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
+ * 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 "opj_includes.h"\r
+\r
+/** @defgroup T2 T2 - Implementation of a tier-2 coding */\r
+/*@{*/\r
+\r
+/** @name Local static functions */\r
+/*@{*/\r
+\r
+static void t2_putcommacode(opj_bio_t *bio, int n);\r
+static int t2_getcommacode(opj_bio_t *bio);\r
+/**\r
+Variable length code for signalling delta Zil (truncation point)\r
+@param bio Bit Input/Output component\r
+@param n delta Zil\r
+*/\r
+static void t2_putnumpasses(opj_bio_t *bio, int n);\r
+static int t2_getnumpasses(opj_bio_t *bio);\r
+/**\r
+Encode a packet of a tile to a destination buffer\r
+@param tile Tile for which to write the packets\r
+@param tcp Tile coding parameters\r
+@param pi Packet identity\r
+@param dest Destination buffer\r
+@param len Length of the destination buffer\r
+@param volume_info Structure to create an index file\r
+@param tileno Number of the tile encoded\r
+@param cp Coding parameters\r
+@return Number of bytes encoded from the packet\r
+*/\r
+static int t2_encode_packet(opj_tcd_tile_t *tile, opj_tcp_t *tcp, opj_pi_iterator_t *pi, unsigned char *dest, int len, opj_volume_info_t *volume_info, int tileno, opj_cp_t *cp);\r
+/**\r
+Initialize the segment decoder\r
+@param seg Segment instance\r
+@param cblksty Codeblock style\r
+@param first Is first segment\r
+*/\r
+static void t2_init_seg(opj_tcd_seg_t *seg, int cblksty, int first);\r
+/**\r
+Decode a packet of a tile from a source buffer\r
+@param t2 T2 handle\r
+@param src Source buffer\r
+@param len Length of the source buffer\r
+@param tile Tile for which to write the packets\r
+@param tcp Tile coding parameters\r
+@param pi Packet identity\r
+@return Number of bytes decoded from the packet\r
+*/\r
+int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_tile_t *tile, opj_tcp_t *tcp, opj_pi_iterator_t *pi);\r
+\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+/* #define RESTART 0x04 */\r
+static void t2_putcommacode(opj_bio_t *bio, int n) {\r
+       while (--n >= 0) {\r
+               bio_write(bio, 1, 1);\r
+       }\r
+       bio_write(bio, 0, 1);\r
+}\r
+\r
+static int t2_getcommacode(opj_bio_t *bio) {\r
+       int n;\r
+       for (n = 0; bio_read(bio, 1); n++) {\r
+               ;\r
+       }\r
+       return n;\r
+}\r
+\r
+static void t2_putnumpasses(opj_bio_t *bio, int n) {\r
+       if (n == 1) {\r
+               bio_write(bio, 0, 1);\r
+       } else if (n == 2) {\r
+               bio_write(bio, 2, 2);\r
+       } else if (n <= 5) {\r
+               bio_write(bio, 0xc | (n - 3), 4);\r
+       } else if (n <= 36) {\r
+               bio_write(bio, 0x1e0 | (n - 6), 9);\r
+       } else if (n <= 164) {\r
+               bio_write(bio, 0xff80 | (n - 37), 16);\r
+       }\r
+}\r
+\r
+static int t2_getnumpasses(opj_bio_t *bio) {\r
+       int n;\r
+       if (!bio_read(bio, 1))\r
+               return 1;\r
+       if (!bio_read(bio, 1))\r
+               return 2;\r
+       if ((n = bio_read(bio, 2)) != 3)\r
+               return (3 + n);\r
+       if ((n = bio_read(bio, 5)) != 31)\r
+               return (6 + n);\r
+       return (37 + bio_read(bio, 7));\r
+}\r
+\r
+static int t2_encode_packet(opj_tcd_tile_t * tile, opj_tcp_t * tcp, opj_pi_iterator_t *pi, unsigned char *dest, int len, opj_volume_info_t * volume_info, int tileno, opj_cp_t *cp) {\r
+       int bandno, cblkno;\r
+       unsigned char *sop = 0, *eph = 0;\r
+       unsigned char *c = dest;\r
+\r
+       int compno = pi->compno;        /* component value */\r
+       int resno  = pi->resno;         /* resolution level value */\r
+       int precno = pi->precno;        /* precinct value */\r
+       int layno  = pi->layno;         /* quality layer value */\r
+\r
+       opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+       opj_tcd_resolution_t *res = &tilec->resolutions[resno];\r
+       \r
+       opj_bio_t *bio = NULL;  /* BIO component */\r
+\r
+       /* <SOP 0xff91> */\r
+       if ((tcp->csty & J3D_CP_CSTY_SOP)) {\r
+               sop = (unsigned char *) opj_malloc(6 * sizeof(unsigned char));\r
+               sop[0] = 255;\r
+               sop[1] = 145;\r
+               sop[2] = 0;\r
+               sop[3] = 4;\r
+               sop[4] = (volume_info) ? (volume_info->num % 65536) / 256 : (0 % 65536) / 256 ;\r
+               sop[5] = (volume_info) ? (volume_info->num % 65536) % 256 : (0 % 65536) % 256 ;\r
+               memcpy(c, sop, 6);\r
+               opj_free(sop);\r
+               c += 6;\r
+       } \r
+       /* </SOP> */\r
+       \r
+       if (!layno) {\r
+               for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                       opj_tcd_band_t *band = &res->bands[bandno];\r
+                       opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+                       tgt_reset(prc->incltree);\r
+                       tgt_reset(prc->imsbtree);\r
+                       for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                               opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+                               cblk->numpasses = 0;\r
+                tgt_setvalue(prc->imsbtree, cblkno, band->numbps - cblk->numbps);\r
+                       }\r
+               }\r
+       }\r
+               \r
+       bio = bio_create();\r
+       bio_init_enc(bio, c, len);\r
+       bio_write(bio, 1, 1);           /* Empty header bit */\r
+       \r
+       /* Writing Packet header */\r
+       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+               opj_tcd_band_t *band = &res->bands[bandno];\r
+               opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+               for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                       opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+                       opj_tcd_layer_t *layer = &cblk->layers[layno];\r
+                       if (!cblk->numpasses && layer->numpasses) {\r
+                tgt_setvalue(prc->incltree, cblkno, layno);\r
+                       }\r
+               }\r
+\r
+               for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                       opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+                       opj_tcd_layer_t *layer = &cblk->layers[layno];\r
+                       int increment = 0;\r
+                       int nump = 0;\r
+                       int len = 0, passno;\r
+                       /* cblk inclusion bits */\r
+                       if (!cblk->numpasses) {\r
+                               tgt_encode(bio, prc->incltree, cblkno, layno + 1);\r
+                       } else {\r
+                               bio_write(bio, layer->numpasses != 0, 1);\r
+                       }\r
+                       /* if cblk not included, go to the next cblk  */\r
+                       if (!layer->numpasses) {\r
+                               continue;\r
+                       }\r
+                       /* if first instance of cblk --> zero bit-planes information */\r
+                       if (!cblk->numpasses) {\r
+                               cblk->numlenbits = 3;\r
+                               tgt_encode(bio, prc->imsbtree, cblkno, 999);\r
+                       }\r
+                       /* number of coding passes included */\r
+                       t2_putnumpasses(bio, layer->numpasses);\r
+                       \r
+                       /* computation of the increase of the length indicator and insertion in the header     */\r
+                       for (passno = cblk->numpasses; passno < cblk->numpasses + layer->numpasses; passno++) {\r
+                               opj_tcd_pass_t *pass = &cblk->passes[passno];\r
+                               nump++;\r
+                               len += pass->len;\r
+                               if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {\r
+                                       increment = int_max(increment, int_floorlog2(len) + 1 - (cblk->numlenbits + int_floorlog2(nump)));\r
+                                       len = 0;\r
+                                       nump = 0;\r
+                               }\r
+                       }\r
+                       t2_putcommacode(bio, increment);\r
+\r
+                       /* computation of the new Length indicator */\r
+                       cblk->numlenbits += increment;\r
+\r
+                       /* insertion of the codeword segment length */\r
+                       for (passno = cblk->numpasses; passno < cblk->numpasses + layer->numpasses; passno++) {\r
+                               opj_tcd_pass_t *pass = &cblk->passes[passno];\r
+                               nump++;\r
+                               len += pass->len;\r
+                               if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {\r
+                                       bio_write(bio, len, cblk->numlenbits + int_floorlog2(nump));\r
+                                       len = 0;\r
+                                       nump = 0;\r
+                               }\r
+                       }\r
+\r
+               }\r
+       }\r
+       \r
+       \r
+       if (bio_flush(bio)) {\r
+               return -999;            /* modified to eliminate longjmp !! */\r
+       }\r
+       \r
+       c += bio_numbytes(bio);\r
+\r
+       bio_destroy(bio);\r
+       \r
+       /* <EPH 0xff92> */\r
+       if (tcp->csty & J3D_CP_CSTY_EPH) {\r
+               eph = (unsigned char *) opj_malloc(2 * sizeof(unsigned char));\r
+               eph[0] = 255;\r
+               eph[1] = 146;\r
+               memcpy(c, eph, 2);\r
+               opj_free(eph);\r
+               c += 2;\r
+       }\r
+       /* </EPH> */\r
+       \r
+       /* Writing the packet body */\r
+       \r
+       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+               opj_tcd_band_t *band = &res->bands[bandno];\r
+               opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+               for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                       opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+                       opj_tcd_layer_t *layer = &cblk->layers[layno];\r
+                       if (!layer->numpasses) {\r
+                               continue;\r
+                       }\r
+                       if (c + layer->len > dest + len) {\r
+                               return -999;\r
+                       }\r
+                       \r
+                       memcpy(c, layer->data, layer->len);\r
+                       cblk->numpasses += layer->numpasses;\r
+                       c += layer->len;\r
+                       /* ADD for index Cfr. Marcela --> delta disto by packet */\r
+                       if(volume_info && volume_info->index_write && volume_info->index_on) {\r
+                               opj_tile_info_t *info_TL = &volume_info->tile[tileno];\r
+                               opj_packet_info_t *info_PK = &info_TL->packet[volume_info->num];\r
+                               info_PK->disto += layer->disto;\r
+                               if (volume_info->D_max < info_PK->disto) {\r
+                                       volume_info->D_max = info_PK->disto;\r
+                               }\r
+                       }\r
+                       /* </ADD> */\r
+               }\r
+       }\r
+       \r
+       return (c - dest);\r
+}\r
+\r
+static void t2_init_seg(opj_tcd_seg_t * seg, int cblksty, int first) {\r
+       seg->numpasses = 0;\r
+       seg->len = 0;\r
+       if (cblksty & J3D_CCP_CBLKSTY_TERMALL) {\r
+               seg->maxpasses = 1;\r
+       }\r
+       else if (cblksty & J3D_CCP_CBLKSTY_LAZY) {\r
+               if (first) {\r
+                       seg->maxpasses = 10;\r
+               } else {\r
+                       seg->maxpasses = (((seg - 1)->maxpasses == 1) || ((seg - 1)->maxpasses == 10)) ? 2 : 1;\r
+               }\r
+       } else {\r
+               seg->maxpasses = 109;\r
+       }\r
+}\r
+\r
+int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_tile_t *tile, opj_tcp_t *tcp, opj_pi_iterator_t *pi) {\r
+       int bandno, cblkno;\r
+       unsigned char *c = src;\r
+\r
+       opj_cp_t *cp = t2->cp;\r
+\r
+       int compno = pi->compno;        /* component value */\r
+       int resno  = pi->resno;         /* resolution level value */\r
+       int precno = pi->precno;        /* precinct value */\r
+       int layno  = pi->layno;         /* quality layer value */\r
+\r
+       opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+       opj_tcd_resolution_t *res = &tilec->resolutions[resno];\r
+       \r
+       unsigned char *hd = NULL;\r
+       int present;\r
+       \r
+       opj_bio_t *bio = NULL;  /* BIO component */\r
+       \r
+       if (layno == 0) {\r
+               for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                       opj_tcd_band_t *band = &res->bands[bandno];\r
+                       opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+                       \r
+                       if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)||(band->z1-band->z0 == 0)) continue;\r
+\r
+                       tgt_reset(prc->incltree);\r
+                       tgt_reset(prc->imsbtree);\r
+                       for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                               opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+                               cblk->numsegs = 0;\r
+                       }\r
+               }\r
+       }\r
+       \r
+       /* SOP markers */\r
+       \r
+       if (tcp->csty & J3D_CP_CSTY_SOP) {\r
+               if ((*c) != 0xff || (*(c + 1) != 0x91)) {\r
+                       opj_event_msg(t2->cinfo, EVT_WARNING, "Expected SOP marker\n");\r
+               } else {\r
+                       c += 6;\r
+               }\r
+               \r
+               /** TODO : check the Nsop value */\r
+       }\r
+       \r
+       /* \r
+       When the marker PPT/PPM is used the packet header are store in PPT/PPM marker\r
+       This part deal with this caracteristic\r
+       step 1: Read packet header in the saved structure\r
+       step 2: Return to codestream for decoding \r
+       */\r
+\r
+       bio = bio_create();\r
+       \r
+       if (cp->ppm == 1) {             /* PPM */\r
+               hd = cp->ppm_data;\r
+               bio_init_dec(bio, hd, cp->ppm_len);\r
+       } else if (tcp->ppt == 1) {     /* PPT */\r
+               hd = tcp->ppt_data;\r
+               bio_init_dec(bio, hd, tcp->ppt_len);\r
+       } else {                        /* Normal Case */\r
+               hd = c;\r
+               bio_init_dec(bio, hd, src+len-hd);\r
+       }\r
+       \r
+       present = bio_read(bio, 1);\r
+       \r
+       if (!present) {\r
+               bio_inalign(bio);\r
+               hd += bio_numbytes(bio);\r
+               bio_destroy(bio);\r
+               \r
+               /* EPH markers */\r
+               \r
+               if (tcp->csty & J3D_CP_CSTY_EPH) {\r
+                       if ((*hd) != 0xff || (*(hd + 1) != 0x92)) {\r
+                               printf("Error : expected EPH marker\n");\r
+                       } else {\r
+                               hd += 2;\r
+                       }\r
+               }\r
+               \r
+               if (cp->ppm == 1) {             /* PPM case */\r
+                       cp->ppm_len += cp->ppm_data-hd;\r
+                       cp->ppm_data = hd;\r
+                       return (c - src);\r
+               }\r
+               if (tcp->ppt == 1) {    /* PPT case */\r
+                       tcp->ppt_len+=tcp->ppt_data-hd;\r
+                       tcp->ppt_data = hd;\r
+                       return (c - src);\r
+               }\r
+               \r
+               return (hd - src);\r
+       }\r
+       \r
+       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+               opj_tcd_band_t *band = &res->bands[bandno];\r
+               opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+               \r
+               if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)||(band->z1-band->z0 == 0)) continue;\r
+               \r
+               for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                       int included, increment, n;\r
+                       opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+                       opj_tcd_seg_t *seg = NULL;\r
+                       /* if cblk not yet included before --> inclusion tagtree */\r
+                       if (!cblk->numsegs) {\r
+                included = tgt_decode(bio, prc->incltree, cblkno, layno + 1);\r
+                               /* else one bit */\r
+                       } else {\r
+                               included = bio_read(bio, 1);\r
+                       }\r
+                       /* if cblk not included */\r
+                       if (!included) {\r
+                               cblk->numnewpasses = 0;\r
+                               continue;\r
+                       }\r
+                       /* if cblk not yet included --> zero-bitplane tagtree */\r
+                       if (!cblk->numsegs) {\r
+                               int i, numimsbs;\r
+                               for (i = 0; !tgt_decode(bio, prc->imsbtree, cblkno, i); i++);\r
+                               numimsbs = i - 1;\r
+                               cblk->numbps = band->numbps - numimsbs;\r
+                               cblk->numlenbits = 3;\r
+                       }\r
+                       /* number of coding passes */\r
+                       cblk->numnewpasses = t2_getnumpasses(bio);\r
+                       increment = t2_getcommacode(bio);\r
+                       /* length indicator increment */\r
+                       cblk->numlenbits += increment;\r
+                       if (!cblk->numsegs) {\r
+                               seg = &cblk->segs[0];\r
+                               t2_init_seg(seg, tcp->tccps[compno].cblksty, 1);\r
+                       } else {\r
+                               seg = &cblk->segs[cblk->numsegs - 1];\r
+                               if (seg->numpasses == seg->maxpasses) {\r
+                                       t2_init_seg(++seg, tcp->tccps[compno].cblksty, 0);\r
+                               }\r
+                       }\r
+                       n = cblk->numnewpasses;\r
+                       \r
+                       do {\r
+                               seg->numnewpasses = int_min(seg->maxpasses - seg->numpasses, n);\r
+                               seg->newlen = bio_read(bio, cblk->numlenbits + int_floorlog2(seg->numnewpasses));\r
+                               n -= seg->numnewpasses;\r
+                               if (n > 0) {\r
+                                       t2_init_seg(++seg, tcp->tccps[compno].cblksty, 0);\r
+                               }\r
+                       } while (n > 0);\r
+               }\r
+       }\r
+       \r
+       if (bio_inalign(bio)) {\r
+               bio_destroy(bio);\r
+               return -999;\r
+       }\r
+       \r
+       hd += bio_numbytes(bio);\r
+       bio_destroy(bio);\r
+       \r
+       /* EPH markers */\r
+       if (tcp->csty & J3D_CP_CSTY_EPH) {\r
+               if ((*hd) != 0xff || (*(hd + 1) != 0x92)) {\r
+                       opj_event_msg(t2->cinfo, EVT_ERROR, "Expected EPH marker\n");\r
+               } else {\r
+                       hd += 2;\r
+               }\r
+       }\r
+       \r
+       if (cp->ppm==1) {\r
+               cp->ppm_len+=cp->ppm_data-hd;\r
+               cp->ppm_data = hd;\r
+       } else if (tcp->ppt == 1) {\r
+               tcp->ppt_len+=tcp->ppt_data-hd;\r
+               tcp->ppt_data = hd;\r
+       } else {\r
+               c=hd;\r
+       }\r
+       \r
+       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+               opj_tcd_band_t *band = &res->bands[bandno];\r
+               opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+               \r
+               if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)||(band->z1-band->z0 == 0)) continue;             \r
+\r
+               for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                       opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+                       opj_tcd_seg_t *seg = NULL;\r
+                       if (!cblk->numnewpasses)\r
+                               continue;\r
+                       if (!cblk->numsegs) {\r
+                               seg = &cblk->segs[0];\r
+                               cblk->numsegs++;\r
+                               cblk->len = 0;\r
+                       } else {\r
+                               seg = &cblk->segs[cblk->numsegs - 1];\r
+                               if (seg->numpasses == seg->maxpasses) {\r
+                                       seg++;\r
+                                       cblk->numsegs++;\r
+                               }\r
+                       }\r
+                       \r
+                       do {\r
+                               if (c + seg->newlen > src + len) {\r
+                                       return -999;\r
+                               }\r
+                               \r
+                               memcpy(cblk->data + cblk->len, c, seg->newlen);\r
+                               if (seg->numpasses == 0) {\r
+                                       seg->data = cblk->data + cblk->len;\r
+                               }\r
+                               c += seg->newlen;\r
+                               cblk->len += seg->newlen;\r
+                               seg->len += seg->newlen;\r
+                               seg->numpasses += seg->numnewpasses;\r
+                               cblk->numnewpasses -= seg->numnewpasses;\r
+                               if (cblk->numnewpasses > 0) {\r
+                                       seg++;\r
+                                       cblk->numsegs++;\r
+                               }\r
+                       } while (cblk->numnewpasses > 0);\r
+               }\r
+       }\r
+       \r
+       return (c - src);\r
+}\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+int t2_encode_packets(opj_t2_t* t2, int tileno, opj_tcd_tile_t *tile, int maxlayers, unsigned char *dest, int len, opj_volume_info_t *volume_info) {\r
+       unsigned char *c = dest;\r
+       int e = 0;\r
+       opj_pi_iterator_t *pi = NULL;\r
+       int pino;\r
+\r
+       opj_volume_t *volume = t2->volume;\r
+       opj_cp_t *cp = t2->cp;\r
+       \r
+       /* create a packet iterator */\r
+       pi = pi_create(volume, cp, tileno);\r
+       if(!pi) {\r
+               fprintf(stdout,"[ERROR] Failed to create a pi structure\n");\r
+               return -999;\r
+       }\r
+       \r
+       if(volume_info) {\r
+               volume_info->num = 0;\r
+       }\r
+       \r
+       for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++) {\r
+               while (pi_next(&pi[pino])) {\r
+                       if (pi[pino].layno < maxlayers) {\r
+                               e = t2_encode_packet(tile, &cp->tcps[tileno], &pi[pino], c, dest + len - c, volume_info, tileno, cp);\r
+                               //opj_event_msg(t2->cinfo, EVT_INFO, "  t2_encode_packet: %d bytes coded\n",e);\r
+                               if (e == -999) {\r
+                                       break;\r
+                               } else {\r
+                                       c += e;\r
+                               }\r
+                               \r
+                               /* INDEX >> */\r
+                               if(volume_info && volume_info->index_on) {\r
+                                       if(volume_info->index_write) {\r
+                                               opj_tile_info_t *info_TL = &volume_info->tile[tileno];\r
+                                               opj_packet_info_t *info_PK = &info_TL->packet[volume_info->num];\r
+                                               if (!volume_info->num) {\r
+                                                       info_PK->start_pos = info_TL->end_header + 1;\r
+                                               } else {\r
+                                                       info_PK->start_pos = info_TL->packet[volume_info->num - 1].end_pos + 1;\r
+                                               }\r
+                                               info_PK->end_pos = info_PK->start_pos + e - 1;\r
+                                       }\r
+\r
+                                       volume_info->num++;\r
+                               }\r
+                               /* << INDEX */\r
+                       }\r
+               }\r
+       }\r
+\r
+       /* don't forget to release pi */\r
+       pi_destroy(pi, cp, tileno);\r
+       \r
+       if (e == -999) {\r
+               return e;\r
+       }\r
+\r
+    return (c - dest);\r
+}\r
+\r
+int t2_decode_packets(opj_t2_t *t2, unsigned char *src, int len, int tileno, opj_tcd_tile_t *tile) {\r
+       unsigned char *c = src;\r
+       opj_pi_iterator_t *pi;\r
+       int pino, e = 0;\r
+       int n = 0,i;\r
+\r
+       opj_volume_t *volume = t2->volume;\r
+       opj_cp_t *cp = t2->cp;\r
+       \r
+       /* create a packet iterator */\r
+       pi = pi_create(volume, cp, tileno);\r
+       if(!pi) {\r
+               /* TODO: throw an error */\r
+               return -999;\r
+       }\r
+       \r
+       for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++) {\r
+               while (pi_next(&pi[pino])) {\r
+                       if ((cp->layer==0) || (cp->layer>=((pi[pino].layno)+1))) {\r
+                               e = t2_decode_packet(t2, c, src + len - c, tile, &cp->tcps[tileno], &pi[pino]);\r
+                       } else {\r
+                               e = 0;\r
+                       }\r
+                       \r
+                       /* progression in resolution */\r
+                       for (i = 0; i < 3; i++){\r
+                volume->comps[pi[pino].compno].resno_decoded[i] = (e > 0) ? int_max(pi[pino].resno, volume->comps[pi[pino].compno].resno_decoded[i]) : volume->comps[pi[pino].compno].resno_decoded[i];\r
+                       }\r
+                       n++;\r
+                       \r
+                       if (e == -999) {                /* ADD */\r
+                               break;\r
+                       } else {\r
+                               opj_event_msg(t2->cinfo, EVT_INFO, "  t2_decode_packet: %d bytes decoded\n",e);\r
+                               c += e;\r
+                       }\r
+               }\r
+       }\r
+\r
+       /* don't forget to release pi */\r
+       pi_destroy(pi, cp, tileno);\r
+       \r
+       if (e == -999) {\r
+               return e;\r
+       }\r
+       \r
+    return (c - src);\r
+}\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+opj_t2_t* t2_create(opj_common_ptr cinfo, opj_volume_t *volume, opj_cp_t *cp) {\r
+       /* create the tcd structure */\r
+       opj_t2_t *t2 = (opj_t2_t*)opj_malloc(sizeof(opj_t2_t));\r
+       if(!t2) return NULL;\r
+       t2->cinfo = cinfo;\r
+       t2->volume = volume;\r
+       t2->cp = cp;\r
+\r
+       return t2;\r
+}\r
+\r
+void t2_destroy(opj_t2_t *t2) {\r
+       if(t2) {\r
+               opj_free(t2);\r
+       }\r
+}\r
+\r
diff --git a/src/lib/openjp3d/t2.h b/src/lib/openjp3d/t2.h
new file mode 100755 (executable)
index 0000000..b937290
--- /dev/null
@@ -0,0 +1,101 @@
+/*\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) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain\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
+#ifndef __T2_H\r
+#define __T2_H\r
+/**\r
+@file t2.h\r
+@brief Implementation of a tier-2 coding (packetization of code-block data) (T2)\r
+\r
+*/\r
+\r
+/** @defgroup T2 T2 - Implementation of a tier-2 coding */\r
+/*@{*/\r
+\r
+/**\r
+Tier-2 coding\r
+*/\r
+typedef struct opj_t2 {\r
+/** Codec context */\r
+       opj_common_ptr cinfo;   \r
+/** Encoding: pointer to the src volume. Decoding: pointer to the dst volume. */\r
+       opj_volume_t *volume;   \r
+/** Pointer to the volume coding parameters */\r
+       opj_cp_t *cp;                   \r
+} opj_t2_t;\r
+\r
+/** @name Funciones generales */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+\r
+/**\r
+Encode the packets of a tile to a destination buffer\r
+@param t2 T2 handle\r
+@param tileno number of the tile encoded\r
+@param tile the tile for which to write the packets\r
+@param maxlayers maximum number of layers\r
+@param dest the destination buffer\r
+@param len the length of the destination buffer\r
+@param volume_info structure to create an index file\r
+@return Number of bytes written from packets\r
+*/\r
+int t2_encode_packets(opj_t2_t* t2, int tileno, opj_tcd_tile_t *tile, int maxlayers, unsigned char *dest, int len, opj_volume_info_t *volume_info);\r
+\r
+/**\r
+Decode the packets of a tile from a source buffer\r
+@param t2 T2 handle\r
+@param src the source buffer\r
+@param len length of the source buffer\r
+@param tileno number that identifies the tile for which to decode the packets\r
+@param tile tile for which to decode the packets\r
+@return Number of bytes read from packets\r
+ */\r
+int t2_decode_packets(opj_t2_t *t2, unsigned char *src, int len, int tileno, opj_tcd_tile_t *tile);\r
+\r
+/**\r
+Create a T2 handle\r
+@param cinfo Codec context info\r
+@param volume Source or destination volume\r
+@param cp Volume coding parameters\r
+@return Returns a new T2 handle if successful, returns NULL otherwise\r
+*/\r
+opj_t2_t* t2_create(opj_common_ptr cinfo, opj_volume_t *volume, opj_cp_t *cp);\r
+/**\r
+Destroy a T2 handle\r
+@param t2 T2 handle to destroy\r
+*/\r
+void t2_destroy(opj_t2_t *t2);\r
+\r
+/* ----------------------------------------------------------------------- */\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* __T2_H */\r
diff --git a/src/lib/openjp3d/tcd.c b/src/lib/openjp3d/tcd.c
new file mode 100755 (executable)
index 0000000..e5147e2
--- /dev/null
@@ -0,0 +1,1738 @@
+/*\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) 2006, Mónica Díez, LPI-UVA, Spain\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 "opj_includes.h"\r
+\r
+void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_volume_t * vol) {\r
+       int tileno, compno, resno, bandno, precno, cblkno;\r
+\r
+       fprintf(fd, "volume {\n");\r
+       fprintf(fd, "  tw=%d, th=%d, tl=%d, x0=%d x1=%d y0=%d y1=%d z0=%d z1=%d\n", \r
+               vol->tw, vol->th, vol->tl, tcd->volume->x0, tcd->volume->x1, tcd->volume->y0, tcd->volume->y1, tcd->volume->z0, tcd->volume->z1);\r
+\r
+       for (tileno = 0; tileno < vol->th * vol->tw * vol->tl; tileno++) {\r
+               opj_tcd_tile_t *tile = &tcd->tcd_volume->tiles[tileno];\r
+               fprintf(fd, "  tile {\n");\r
+               fprintf(fd, "    x0=%d, y0=%d, z0=%d, x1=%d, y1=%d, z1=%d, numcomps=%d\n",\r
+                       tile->x0, tile->y0, tile->z0, tile->x1, tile->y1, tile->z1, tile->numcomps);\r
+               for (compno = 0; compno < tile->numcomps; compno++) {\r
+                       opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+                       fprintf(fd, "    tilecomp %d {\n",compno);\r
+                       fprintf(fd,     "     x0=%d, y0=%d, z0=%d, x1=%d, y1=%d, z1=%d, numresx=%d, numresy=%d, numresz=%d\n",\r
+                               tilec->x0, tilec->y0, tilec->z0, tilec->x1, tilec->y1, tilec->z1, tilec->numresolution[0], tilec->numresolution[1], tilec->numresolution[2]);\r
+                       for (resno = 0; resno < tilec->numresolution[0]; resno++) {\r
+                               opj_tcd_resolution_t *res = &tilec->resolutions[resno];\r
+                               fprintf(fd, "     res %d{\n",resno);\r
+                               fprintf(fd,"      x0=%d, y0=%d, z0=%d, x1=%d, y1=%d, z1=%d, pw=%d, ph=%d, pl=%d, numbands=%d\n",\r
+                                       res->x0, res->y0, res->z0, res->x1, res->y1, res->z1, res->prctno[0], res->prctno[1], res->prctno[2], res->numbands);\r
+                               for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                                       opj_tcd_band_t *band = &res->bands[bandno];\r
+                                       fprintf(fd, "       band %d{\n", bandno);\r
+                                       fprintf(fd,     "                x0=%d, y0=%d, z0=%d, x1=%d, y1=%d, z1=%d, stepsize=%f, numbps=%d\n",\r
+                                               band->x0, band->y0, band->z0, band->x1, band->y1, band->z1, band->stepsize, band->numbps);\r
+                                       for (precno = 0; precno < (res->prctno[0] * res->prctno[1] * res->prctno[2]); precno++) {\r
+                                               opj_tcd_precinct_t *prec = &band->precincts[precno];\r
+                                               fprintf(fd, "             prec %d{\n",precno);\r
+                                               fprintf(fd,     "                  x0=%d, y0=%d, z0=%d, x1=%d, y1=%d, z1=%d, cw=%d, ch=%d, cl=%d,\n",\r
+                                                       prec->x0, prec->y0, prec->z0, prec->x1, prec->y1, prec->z1, prec->cblkno[0], prec->cblkno[1], prec->cblkno[2]);\r
+                                               for (cblkno = 0; cblkno < (prec->cblkno[0] * prec->cblkno[1] * prec->cblkno[2]); cblkno++) {\r
+                                                       opj_tcd_cblk_t *cblk = &prec->cblks[cblkno];\r
+                                                       fprintf(fd, "               cblk %d{\n",cblkno);\r
+                                                       fprintf(fd,     "                    x0=%d, y0=%d, z0=%d, x1=%d, y1=%d, z1=%d\n", cblk->x0, cblk->y0, cblk->z0, cblk->x1, cblk->y1, cblk->z1);\r
+                                                       fprintf(fd, "            }\n");\r
+                                               }\r
+                                               fprintf(fd, "          }\n");\r
+                                       }\r
+                                       fprintf(fd, "        }\n");\r
+                               }\r
+                               fprintf(fd, "      }\n");\r
+                       }\r
+                       fprintf(fd, "    }\n");\r
+               }\r
+               fprintf(fd, "  }\n");\r
+       }\r
+       fprintf(fd, "}\n");\r
+}\r
+\r
+void tilec_dump(FILE *fd, opj_tcd_tilecomp_t *tilec) {\r
+\r
+       int i=0,k;\r
+       int datalen;\r
+       int *a;\r
+\r
+       fprintf(fd, "    tilecomp{\n");\r
+       fprintf(fd,     "     x0=%d, y0=%d, z0=%d, x1=%d, y1=%d, z1=%d, numresx=%d, numresy=%d, numresz=%d\n",\r
+               tilec->x0, tilec->y0, tilec->z0, tilec->x1, tilec->y1, tilec->z1, tilec->numresolution[0], tilec->numresolution[1], tilec->numresolution[2]);\r
+       fprintf(fd, "     data {\n");\r
+       datalen = (tilec->z1 - tilec->z0) * (tilec->y1 - tilec->y0) * (tilec->x1 - tilec->x0);\r
+       a = tilec->data;\r
+       for (k = 0; k < datalen; k++) {\r
+               if (!(k % tilec->x1)){\r
+                       fprintf(fd, "\n");\r
+               }\r
+               if (!(k % (tilec->y1 * tilec->x1))){\r
+                       fprintf(fd, "Slice %d\n",i++);\r
+               }\r
+               fprintf(fd," %d",a[k]);\r
+               \r
+               \r
+       }                       \r
+       fprintf(fd, "     }\n");\r
+       /*i=0;\r
+       fprintf(fd, "Slice %d\n");\r
+       if (tilec->prediction->prederr) {\r
+               fprintf(fd, "     prederror {\n");\r
+               a = tilec->prediction->prederr;\r
+               for (k = 0; k < datalen; k++) {\r
+                       fprintf(fd," %d",*(a++));\r
+                       if (!(k % (tilec->y1 - tilec->y0) * (tilec->x1 - tilec->x0))){\r
+                               fprintf(fd, "\n");fprintf(fd, "Slice %d\n",i++);\r
+                       }\r
+                       if (!(k % (tilec->x1 - tilec->x0))){\r
+                               fprintf(fd, "\n");\r
+                       }\r
+               }\r
+       }\r
+       fprintf(fd, "     }\n");*/\r
+       fprintf(fd, "}\n");\r
+}\r
+\r
+/* ----------------------------------------------------------------------- */\r
+\r
+/**\r
+Create a new TCD handle\r
+*/\r
+opj_tcd_t* tcd_create(opj_common_ptr cinfo) {\r
+       /* create the tcd structure */\r
+       opj_tcd_t *tcd = (opj_tcd_t*)opj_malloc(sizeof(opj_tcd_t));\r
+       if(!tcd) return NULL;\r
+       tcd->cinfo = cinfo;\r
+       tcd->tcd_volume = (opj_tcd_volume_t*)opj_malloc(sizeof(opj_tcd_volume_t));\r
+       if(!tcd->tcd_volume) {\r
+               opj_free(tcd);\r
+               return NULL;\r
+       }\r
+\r
+       return tcd;\r
+}\r
+\r
+/**\r
+Destroy a previously created TCD handle\r
+*/\r
+void tcd_destroy(opj_tcd_t *tcd) {\r
+       if(tcd) {\r
+               opj_free(tcd->tcd_volume);\r
+               opj_free(tcd);\r
+       }\r
+}\r
+\r
+/* ----------------------------------------------------------------------- */\r
+void tcd_malloc_encode(opj_tcd_t *tcd, opj_volume_t * volume, opj_cp_t * cp, int curtileno) {\r
+       int compno, resno, bandno, precno, cblkno, i, j;//, k;\r
+\r
+       opj_tcd_tile_t          *tile = NULL;           /* pointer to tcd->tile */\r
+       opj_tcd_tilecomp_t      *tilec = NULL;          /* pointer to tcd->tilec */\r
+       opj_tcd_resolution_t    *res = NULL;            /* pointer to tcd->res */\r
+       opj_tcd_band_t          *band = NULL;           /* pointer to tcd->band */\r
+       opj_tcd_precinct_t      *prc = NULL;            /* pointer to tcd->prc */\r
+       opj_tcd_cblk_t          *cblk = NULL;           /* pointer to tcd->cblk */\r
+       opj_tcp_t               *tcp = &cp->tcps[curtileno];\r
+       int p,q,r;\r
+\r
+       tcd->volume = volume;\r
+       tcd->cp = cp;\r
+       tcd->tcd_volume->tw = cp->tw;\r
+       tcd->tcd_volume->th = cp->th;\r
+       tcd->tcd_volume->tl = cp->tl;\r
+       tcd->tcd_volume->tiles = (opj_tcd_tile_t *) opj_malloc(sizeof(opj_tcd_tile_t));\r
+       tcd->tile = tcd->tcd_volume->tiles;\r
+       tile = tcd->tile;\r
+       \r
+\r
+       /* p61 ISO/IEC IS15444-1 : 2002 */\r
+       /* curtileno --> raster scanned index of tiles */\r
+       /* p,q,r --> matricial index of tiles */\r
+       p = curtileno % cp->tw; \r
+       q = curtileno / cp->tw; \r
+       r = curtileno / (cp->tw * cp->th); /* extension to 3-D */\r
+\r
+       /* 4 borders of the tile rescale on the volume if necessary (B.3)*/\r
+       tile->x0 = int_max(cp->tx0 + p * cp->tdx, volume->x0);\r
+       tile->y0 = int_max(cp->ty0 + q * cp->tdy, volume->y0);\r
+       tile->z0 = int_max(cp->tz0 + r * cp->tdz, volume->z0);\r
+       tile->x1 = int_min(cp->tx0 + (p + 1) * cp->tdx, volume->x1);\r
+       tile->y1 = int_min(cp->ty0 + (q + 1) * cp->tdy, volume->y1);\r
+       tile->z1 = int_min(cp->tz0 + (r + 1) * cp->tdz, volume->z1);\r
+       tile->numcomps = volume->numcomps;\r
+\r
+       /* Modification of the RATE >> */\r
+       for (j = 0; j < tcp->numlayers; j++) {\r
+               if (tcp->rates[j] <= 1) {\r
+                       tcp->rates[j] = 0;\r
+               } else {\r
+                       float num = (float) (tile->numcomps * (tile->x1 - tile->x0) * (tile->y1 - tile->y0) * (tile->z1 - tile->z0) * volume->comps[0].prec);\r
+                       float den = (float) (8 * volume->comps[0].dx * volume->comps[0].dy * volume->comps[0].dz);\r
+                       den = tcp->rates[j] * den;\r
+                       tcp->rates[j] = (num + den - 1) / den;\r
+               }\r
+               /*tcp->rates[j] = tcp->rates[j] ? int_ceildiv(\r
+                       tile->numcomps * (tile->x1 - tile->x0) * (tile->y1 - tile->y0) * (tile->z1 - tile->z0) * volume->comps[0].prec,\r
+            (tcp->rates[j] * 8 * volume->comps[0].dx * volume->comps[0].dy * volume->comps[0].dz)) : 0;*/\r
+               if (tcp->rates[j]) {\r
+                       if (j && tcp->rates[j] < tcp->rates[j - 1] + 10) {\r
+                               tcp->rates[j] = tcp->rates[j - 1] + 20;\r
+                       } else if (!j && tcp->rates[j] < 30){\r
+                               tcp->rates[j] = 30;\r
+                       }\r
+               }\r
+       }\r
+       /* << Modification of the RATE */\r
+\r
+       tile->comps = (opj_tcd_tilecomp_t *) opj_malloc(volume->numcomps * sizeof(opj_tcd_tilecomp_t));\r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               opj_tccp_t *tccp = &tcp->tccps[compno];\r
+               int res_max;\r
+               int prevnumbands = 0;\r
+\r
+               /* opj_tcd_tilecomp_t *tilec=&tile->comps[compno]; */\r
+               tcd->tilec = &tile->comps[compno];\r
+               tilec = tcd->tilec;\r
+\r
+               /* border of each tile component (global) (B.3) */\r
+               tilec->x0 = int_ceildiv(tile->x0, volume->comps[compno].dx);\r
+               tilec->y0 = int_ceildiv(tile->y0, volume->comps[compno].dy);\r
+               tilec->z0 = int_ceildiv(tile->z0, volume->comps[compno].dz);\r
+               tilec->x1 = int_ceildiv(tile->x1, volume->comps[compno].dx);\r
+               tilec->y1 = int_ceildiv(tile->y1, volume->comps[compno].dy);\r
+               tilec->z1 = int_ceildiv(tile->z1, volume->comps[compno].dz);\r
+\r
+               tilec->data = (int *) opj_malloc((tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0) * (tilec->z1 - tilec->z0) * sizeof(int));\r
+               \r
+               res_max = 0;\r
+               for (i = 0;i < 3; i++){\r
+                       tilec->numresolution[i] = tccp->numresolution[i];\r
+                       //Greater of 3 resolutions contains all information\r
+                       res_max = (tilec->numresolution[i] > res_max) ? tilec->numresolution[i] : res_max;\r
+               }\r
+               \r
+\r
+               tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(res_max * sizeof(opj_tcd_resolution_t));\r
+               for (resno = 0; resno < res_max; resno++) {\r
+                       \r
+                       int pdx, pdy, pdz;\r
+                       int tlprcxstart, tlprcystart, tlprczstart;\r
+                       int brprcxend, brprcyend, brprczend;\r
+                       int tlcbgxstart, tlcbgystart, tlcbgzstart;\r
+                       int brcbgxend, brcbgyend, brcbgzend;\r
+                       int cbgwidthexpn, cbgheightexpn, cbglengthexpn;\r
+                       int cblkwidthexpn, cblkheightexpn, cblklengthexpn;\r
+\r
+                       int diff = tccp->numresolution[0] - tccp->numresolution[2]; \r
+                       int levelnox = tilec->numresolution[0] - 1 - resno; \r
+                       int levelnoy = tilec->numresolution[1] - 1 - resno;\r
+                       int levelnoz = tilec->numresolution[2] - 1 - ((resno <= diff) ? 0 : (resno - diff));\r
+                               if (levelnoz < 0) levelnoz = 0;\r
+\r
+                       /* opj_tcd_resolution_t *res=&tilec->resolutions[resno]; */\r
+                       tcd->res = &tilec->resolutions[resno];\r
+                       res = tcd->res;\r
+                       \r
+                       /* border for each resolution level (global) (B.14)*/\r
+                       res->x0 = int_ceildivpow2(tilec->x0, levelnox);\r
+                       res->y0 = int_ceildivpow2(tilec->y0, levelnoy);\r
+                       res->z0 = int_ceildivpow2(tilec->z0, levelnoz);\r
+                       res->x1 = int_ceildivpow2(tilec->x1, levelnox);\r
+                       res->y1 = int_ceildivpow2(tilec->y1, levelnoy);\r
+                       res->z1 = int_ceildivpow2(tilec->z1, levelnoz);\r
+                       //if (res->z1 < 0)fprintf(stdout,"Res: %d       %d/%d --> %d\n",resno,tilec->z1, levelnoz, int_ceildivpow2(tilec->z1, levelnoz));\r
+\r
+                       res->numbands = (resno == 0) ? 1 : (resno <= diff) ? 3 : 7; /* --> 3D */\r
+\r
+                       /* p. 30, table A-13, ISO/IEC IS154444-1 : 2002 */\r
+                       if (tccp->csty & J3D_CCP_CSTY_PRT) {\r
+                               pdx = tccp->prctsiz[0][resno];\r
+                               pdy = tccp->prctsiz[1][resno];\r
+                               pdz = tccp->prctsiz[2][resno];\r
+                       } else {\r
+                               pdx = 15;\r
+                               pdy = 15;\r
+                               pdz = 15;\r
+                       }\r
+                       \r
+                       /* p. 66, B.16, ISO/IEC IS15444-1 : 2002  */\r
+                       tlprcxstart = int_floordivpow2(res->x0, pdx) << pdx;\r
+                       tlprcystart = int_floordivpow2(res->y0, pdy) << pdy;\r
+                       tlprczstart = int_floordivpow2(res->z0, pdz) << pdz;\r
+                       brprcxend = int_ceildivpow2(res->x1, pdx) << pdx;\r
+                       brprcyend = int_ceildivpow2(res->y1, pdy) << pdy;\r
+                       brprczend = int_ceildivpow2(res->z1, pdz) << pdz;\r
+                       \r
+                       res->prctno[0] = (brprcxend - tlprcxstart) >> pdx;\r
+                       res->prctno[1] = (brprcyend - tlprcystart) >> pdy;\r
+                       res->prctno[2] = (brprczend - tlprczstart) >> pdz;\r
+                               if (res->prctno[2] == 0) res->prctno[2] = 1;\r
+                               \r
+                       /* p. 67, B.17 & B.18, ISO/IEC IS15444-1 : 2002  */\r
+                       if (resno == 0) {\r
+                               tlcbgxstart = tlprcxstart;\r
+                               tlcbgystart = tlprcystart;\r
+                               tlcbgzstart = tlprczstart;\r
+                               brcbgxend = brprcxend;\r
+                               brcbgyend = brprcyend;\r
+                               brcbgzend = brprczend;\r
+                               cbgwidthexpn = pdx;\r
+                               cbgheightexpn = pdy;\r
+                               cbglengthexpn = pdz;\r
+                       } else {\r
+                               tlcbgxstart = int_ceildivpow2(tlprcxstart, 1);\r
+                               tlcbgystart = int_ceildivpow2(tlprcystart, 1);\r
+                               tlcbgzstart = int_ceildivpow2(tlprczstart, 1);\r
+                               brcbgxend = int_ceildivpow2(brprcxend, 1);\r
+                               brcbgyend = int_ceildivpow2(brprcyend, 1);\r
+                               brcbgzend = int_ceildivpow2(brprczend, 1);\r
+                               cbgwidthexpn = pdx - 1;\r
+                               cbgheightexpn = pdy - 1;\r
+                               cbglengthexpn = pdz - 1;\r
+                       }\r
+                       \r
+                       cblkwidthexpn = int_min(tccp->cblk[0], cbgwidthexpn); //6\r
+                       cblkheightexpn = int_min(tccp->cblk[1], cbgheightexpn); //6\r
+                       cblklengthexpn = int_min(tccp->cblk[2], cbglengthexpn); //6\r
+                       \r
+                       res->bands = (opj_tcd_band_t *) opj_malloc(res->numbands * sizeof(opj_tcd_band_t));\r
+                       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                               int x0b, y0b, z0b, i;\r
+                               int gain, numbps;\r
+                               opj_stepsize_t *ss = NULL;\r
+\r
+                               tcd->band = &res->bands[bandno];\r
+                               band = tcd->band;\r
+\r
+                               band->bandno = (resno == 0) ? 0 : bandno + 1;\r
+                               /* Bandno:      0 - LLL         2 - LHL \r
+                                                       1 - HLL         3 - HHL\r
+                                                       4 - LLH         6 - LHH\r
+                                                       5 - HLH         7 - HHH         */\r
+                               x0b = (band->bandno == 1) || (band->bandno == 3) || (band->bandno == 5 ) || (band->bandno == 7 ) ? 1 : 0; \r
+                               y0b = (band->bandno == 2) || (band->bandno == 3) || (band->bandno == 6 ) || (band->bandno == 7 ) ? 1 : 0;\r
+                               z0b = (band->bandno == 4) || (band->bandno == 5) || (band->bandno == 6 ) || (band->bandno == 7 ) ? 1 : 0; \r
+                               \r
+                               /* p. 65, B.15, ISO/IEC IS15444-1 : 2002  */\r
+                               if (band->bandno == 0) {\r
+                                       /* band border (global) */\r
+                                       band->x0 = int_ceildivpow2(tilec->x0, levelnox);\r
+                                       band->y0 = int_ceildivpow2(tilec->y0, levelnoy);\r
+                                       band->z0 = int_ceildivpow2(tilec->z0, levelnoz);\r
+                                       band->x1 = int_ceildivpow2(tilec->x1, levelnox);\r
+                                       band->y1 = int_ceildivpow2(tilec->y1, levelnoy);\r
+                                       band->z1 = int_ceildivpow2(tilec->z1, levelnoz);\r
+                               } else {\r
+                                       band->x0 = int_ceildivpow2(tilec->x0 - (1 << levelnox) * x0b, levelnox + 1);\r
+                                       band->y0 = int_ceildivpow2(tilec->y0 - (1 << levelnoy) * y0b, levelnoy + 1);\r
+                                       band->z0 = int_ceildivpow2(tilec->z0 - (1 << levelnoz) * z0b, (resno <= diff) ? levelnoz : levelnoz + 1);\r
+                                       band->x1 = int_ceildivpow2(tilec->x1 - (1 << levelnox) * x0b, levelnox + 1);\r
+                                       band->y1 = int_ceildivpow2(tilec->y1 - (1 << levelnoy) * y0b, levelnoy + 1);\r
+                                       band->z1 = int_ceildivpow2(tilec->z1 - (1 << levelnoz) * z0b, (resno <= diff) ? levelnoz : levelnoz + 1);\r
+                               }\r
+                               \r
+                               ss = &tccp->stepsizes[(resno == 0) ? 0 : (prevnumbands + bandno + 1)];\r
+                               if (bandno == (res->numbands - 1)) \r
+                                       prevnumbands += (resno == 0) ? 0 : res->numbands;\r
+                               gain = dwt_getgain(band->bandno,tccp->reversible);                                      \r
+                               numbps = volume->comps[compno].prec + gain;\r
+                               band->stepsize = (float)((1.0 + ss->mant / 2048.0) * pow(2.0, numbps - ss->expn));\r
+                               band->numbps = ss->expn + tccp->numgbits - 1;   /* WHY -1 ? */\r
+                               \r
+                               band->precincts = (opj_tcd_precinct_t *) opj_malloc((res->prctno[0] * res->prctno[1] * res->prctno[2]) * sizeof(opj_tcd_precinct_t));\r
+                               \r
+                               for (i = 0; i < (res->prctno[0] * res->prctno[1] * res->prctno[2]); i++) {\r
+                                       band->precincts[i].imsbtree = NULL;\r
+                                       band->precincts[i].incltree = NULL;\r
+                               }\r
+\r
+                               for (precno = 0; precno < (res->prctno[0] * res->prctno[1] * res->prctno[2]); precno++) {\r
+                                       int tlcblkxstart, tlcblkystart, tlcblkzstart, brcblkxend, brcblkyend, brcblkzend;\r
+                                       int cbgxstart, cbgystart, cbgzstart, cbgxend, cbgyend, cbgzend;\r
+\r
+                                       cbgxstart = tlcbgxstart + (precno % res->prctno[0]) * (1 << cbgwidthexpn);\r
+                                       cbgystart = tlcbgystart + ((precno % (res->prctno[0] * res->prctno[1])) / res->prctno[0]) * (1 << cbgheightexpn);\r
+                                       cbgzstart = tlcbgzstart + (precno / (res->prctno[0] * res->prctno[1])) * (1 << cbglengthexpn);\r
+                                       cbgxend = cbgxstart + (1 << cbgwidthexpn);\r
+                                       cbgyend = cbgystart + (1 << cbgheightexpn);\r
+                                       cbgzend = cbgzstart + (1 << cbglengthexpn);\r
+                                       \r
+                                       tcd->prc = &band->precincts[precno];\r
+                                       prc = tcd->prc;\r
+\r
+                                       /* precinct size (global) */\r
+                                       prc->x0 = int_max(cbgxstart, band->x0);\r
+                                       prc->y0 = int_max(cbgystart, band->y0);\r
+                                       prc->z0 = int_max(cbgzstart, band->z0);\r
+                                       prc->x1 = int_min(cbgxend, band->x1);\r
+                                       prc->y1 = int_min(cbgyend, band->y1);\r
+                                       prc->z1 = int_min(cbgzend, band->z1);\r
+                                       \r
+                                       tlcblkxstart = int_floordivpow2(prc->x0, cblkwidthexpn) << cblkwidthexpn;\r
+                                       tlcblkystart = int_floordivpow2(prc->y0, cblkheightexpn) << cblkheightexpn;\r
+                                       tlcblkzstart = int_floordivpow2(prc->z0, cblklengthexpn) << cblklengthexpn;\r
+                                       brcblkxend = int_ceildivpow2(prc->x1, cblkwidthexpn) << cblkwidthexpn;\r
+                                       brcblkyend = int_ceildivpow2(prc->y1, cblkheightexpn) << cblkheightexpn;\r
+                                       brcblkzend = int_ceildivpow2(prc->z1, cblklengthexpn) << cblklengthexpn;\r
+                                       prc->cblkno[0] = (brcblkxend - tlcblkxstart) >> cblkwidthexpn;\r
+                                       prc->cblkno[1] = (brcblkyend - tlcblkystart) >> cblkheightexpn;\r
+                                       prc->cblkno[2] = (brcblkzend - tlcblkzstart) >> cblklengthexpn;\r
+                                       prc->cblkno[2] = (prc->cblkno[2] == 0) ? 1 : prc->cblkno[2];\r
+\r
+                                       prc->cblks = (opj_tcd_cblk_t *) opj_malloc((prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]) * sizeof(opj_tcd_cblk_t));\r
+                                       prc->incltree = tgt_create(prc->cblkno[0], prc->cblkno[1], prc->cblkno[2]);\r
+                                       prc->imsbtree = tgt_create(prc->cblkno[0], prc->cblkno[1], prc->cblkno[2]);\r
+                                       //tgt_tree_dump(stdout,prc->incltree);\r
+                                       for (cblkno = 0; cblkno < (prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]); cblkno++) {\r
+                                               int cblkxstart = tlcblkxstart + (cblkno % prc->cblkno[0]) * (1 << cblkwidthexpn);\r
+                                               int cblkystart = tlcblkystart + ((cblkno % (prc->cblkno[0] * prc->cblkno[1])) / prc->cblkno[0]) * (1 << cblkheightexpn);\r
+                                               int cblkzstart = tlcblkzstart + (cblkno / (prc->cblkno[0] * prc->cblkno[1])) * (1 << cblklengthexpn);\r
+                                               int cblkxend = cblkxstart + (1 << cblkwidthexpn);\r
+                                               int cblkyend = cblkystart + (1 << cblkheightexpn);\r
+                                               int cblkzend = cblkzstart + (1 << cblklengthexpn);\r
+                                               int prec = ((tilec->bpp > 16) ? 3 : ((tilec->bpp > 8) ? 2 : 1));\r
+                                               \r
+                                               tcd->cblk = &prc->cblks[cblkno];\r
+                                               cblk = tcd->cblk;\r
+\r
+                                               /* code-block size (global) */\r
+                                               cblk->x0 = int_max(cblkxstart, prc->x0);\r
+                                               cblk->y0 = int_max(cblkystart, prc->y0);\r
+                                               cblk->z0 = int_max(cblkzstart, prc->z0);\r
+                                               cblk->x1 = int_min(cblkxend, prc->x1);\r
+                                               cblk->y1 = int_min(cblkyend, prc->y1);\r
+                                               cblk->z1 = int_min(cblkzend, prc->z1);\r
+                                       }                                       \r
+                               }\r
+                       }\r
+               }\r
+       }\r
+       //tcd_dump(stdout, tcd, tcd->tcd_volume);\r
+\r
+}\r
+void tcd_init_encode(opj_tcd_t *tcd, opj_volume_t * volume, opj_cp_t * cp, int curtileno) {\r
+       int compno, resno, bandno, precno, cblkno;\r
+       int j, p, q, r;\r
+\r
+       opj_tcd_tile_t          *tile = NULL;           /* pointer to tcd->tile */\r
+       opj_tcd_tilecomp_t      *tilec = NULL;          /* pointer to tcd->tilec */\r
+       opj_tcd_resolution_t    *res = NULL;    /* pointer to tcd->res */\r
+       opj_tcd_band_t          *band = NULL;           /* pointer to tcd->band */\r
+       opj_tcd_precinct_t      *prc = NULL;            /* pointer to tcd->prc */\r
+       opj_tcd_cblk_t          *cblk = NULL;           /* pointer to tcd->cblk */\r
+       opj_tcp_t *tcp = &cp->tcps[curtileno];\r
+\r
+       tcd->tile = tcd->tcd_volume->tiles;\r
+       tile = tcd->tile;\r
+\r
+       /* p61 ISO/IEC IS15444-1 : 2002 */\r
+       /* curtileno --> raster scanned index of tiles */\r
+       /* p,q,r --> matricial index of tiles */\r
+       p = curtileno % cp->tw; \r
+       q = curtileno / cp->tw; \r
+       r = curtileno / (cp->tw * cp->th); /* extension to 3-D */\r
+       \r
+       /* 4 borders of the tile rescale on the volume if necessary (B.3)*/\r
+       tile->x0 = int_max(cp->tx0 + p * cp->tdx, volume->x0);\r
+       tile->y0 = int_max(cp->ty0 + q * cp->tdy, volume->y0);\r
+       tile->z0 = int_max(cp->tz0 + r * cp->tdz, volume->z0);\r
+       tile->x1 = int_min(cp->tx0 + (p + 1) * cp->tdx, volume->x1);\r
+       tile->y1 = int_min(cp->ty0 + (q + 1) * cp->tdy, volume->y1);\r
+       tile->z1 = int_min(cp->tz0 + (r + 1) * cp->tdz, volume->z1);\r
+       tile->numcomps = volume->numcomps;\r
+\r
+       /* Modification of the RATE >> */\r
+       for (j = 0; j < tcp->numlayers; j++) {\r
+               if (tcp->rates[j] <= 1) {\r
+                       tcp->rates[j] = 0;\r
+               } else {\r
+                       float num = (float) (tile->numcomps * (tile->x1 - tile->x0) * (tile->y1 - tile->y0) * (tile->z1 - tile->z0) * volume->comps[0].prec);\r
+                       float den = (float) (8 * volume->comps[0].dx * volume->comps[0].dy * volume->comps[0].dz);\r
+                       den = tcp->rates[j] * den;\r
+                       tcp->rates[j] = (num + den - 1) / den;\r
+               }\r
+               /*tcp->rates[j] = tcp->rates[j] ? int_ceildiv(\r
+                       tile->numcomps * (tile->x1 - tile->x0) * (tile->y1 - tile->y0) * (tile->z1 - tile->z0) * volume->comps[0].prec,\r
+            (tcp->rates[j] * 8 * volume->comps[0].dx * volume->comps[0].dy * volume->comps[0].dz)) : 0;*/\r
+               if (tcp->rates[j]) {\r
+                       if (j && tcp->rates[j] < tcp->rates[j - 1] + 10) {\r
+                               tcp->rates[j] = tcp->rates[j - 1] + 20;\r
+                       } else if (!j && tcp->rates[j] < 30){\r
+                               tcp->rates[j] = 30;\r
+                       }\r
+               }\r
+       }\r
+       /* << Modification of the RATE */\r
+\r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               opj_tccp_t *tccp = &tcp->tccps[compno];\r
+               int res_max, i;\r
+               int prevnumbands = 0;\r
+\r
+               /* opj_tcd_tilecomp_t *tilec=&tile->comps[compno]; */\r
+               tcd->tilec = &tile->comps[compno];\r
+               tilec = tcd->tilec;\r
+\r
+               /* border of each tile component (global) (B.3) */\r
+               tilec->x0 = int_ceildiv(tile->x0, volume->comps[compno].dx);\r
+               tilec->y0 = int_ceildiv(tile->y0, volume->comps[compno].dy);\r
+               tilec->z0 = int_ceildiv(tile->z0, volume->comps[compno].dz);\r
+               tilec->x1 = int_ceildiv(tile->x1, volume->comps[compno].dx);\r
+               tilec->y1 = int_ceildiv(tile->y1, volume->comps[compno].dy);\r
+               tilec->z1 = int_ceildiv(tile->z1, volume->comps[compno].dz);\r
+\r
+               tilec->data = (int *) opj_malloc((tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0) * (tilec->z1 - tilec->z0) * sizeof(int));\r
+               \r
+               res_max = 0;\r
+               for (i = 0;i < 3; i++){\r
+                       tilec->numresolution[i] = tccp->numresolution[i];\r
+                       //Greater of 3 resolutions contains all information\r
+                       res_max = (tilec->numresolution[i] > res_max) ? tilec->numresolution[i] : res_max;\r
+               }\r
+\r
+               tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(res_max * sizeof(opj_tcd_resolution_t));\r
+               for (resno = 0; resno < res_max; resno++) {\r
+                       int pdx, pdy, pdz;\r
+                       int tlprcxstart, tlprcystart, tlprczstart, brprcxend, brprcyend, brprczend;\r
+                       int tlcbgxstart, tlcbgystart, tlcbgzstart, brcbgxend, brcbgyend, brcbgzend;\r
+                       int cbgwidthexpn, cbgheightexpn, cbglengthexpn;\r
+                       int cblkwidthexpn, cblkheightexpn, cblklengthexpn;\r
+                       \r
+                       int levelnox = tilec->numresolution[0] - 1 - resno; \r
+                       int levelnoy = tilec->numresolution[1] - 1 - resno;\r
+                       int diff = tccp->numresolution[0] - tccp->numresolution[2]; \r
+                       int levelnoz = tilec->numresolution[2] - 1 - ((resno <= diff) ? 0 : (resno - diff));\r
+                               if (levelnoz < 0) levelnoz = 0;\r
+\r
+                       tcd->res = &tilec->resolutions[resno];\r
+                       res = tcd->res;\r
+                       \r
+                       /* border for each resolution level (global) (B.14)*/\r
+                       res->x0 = int_ceildivpow2(tilec->x0, levelnox);\r
+                       res->y0 = int_ceildivpow2(tilec->y0, levelnoy);\r
+                       res->z0 = int_ceildivpow2(tilec->z0, levelnoz);\r
+                       res->x1 = int_ceildivpow2(tilec->x1, levelnox);\r
+                       res->y1 = int_ceildivpow2(tilec->y1, levelnoy);\r
+                       res->z1 = int_ceildivpow2(tilec->z1, levelnoz);\r
+\r
+                       // res->numbands = resno == 0 ? 1 : 3; /* --> 2D */\r
+                       res->numbands = (resno == 0) ? 1 : (resno <= diff) ? 3 : 7; /* --> 3D */\r
+\r
+                       /* p. 30, table A-13, ISO/IEC IS154444-1 : 2002 */                      \r
+                       if (tccp->csty & J3D_CCP_CSTY_PRT) {\r
+                               pdx = tccp->prctsiz[0][resno];\r
+                               pdy = tccp->prctsiz[1][resno];\r
+                               pdz = tccp->prctsiz[2][resno];\r
+                       } else {\r
+                               pdx = 15;\r
+                               pdy = 15;\r
+                               pdz = 15;\r
+                       }\r
+                       /* p. 66, B.16, ISO/IEC IS15444-1 : 2002  */\r
+                       tlprcxstart = int_floordivpow2(res->x0, pdx) << pdx;\r
+                       tlprcystart = int_floordivpow2(res->y0, pdy) << pdy;\r
+                       tlprczstart = int_floordivpow2(res->z0, pdz) << pdz;\r
+                       brprcxend = int_ceildivpow2(res->x1, pdx) << pdx;\r
+                       brprcyend = int_ceildivpow2(res->y1, pdy) << pdy;\r
+                       brprczend = int_ceildivpow2(res->z1, pdz) << pdz;\r
+                       \r
+                       res->prctno[0] = (brprcxend - tlprcxstart) >> pdx;\r
+                       res->prctno[1] = (brprcyend - tlprcystart) >> pdy;\r
+                       res->prctno[2] = (brprczend - tlprczstart) >> pdz;\r
+                       if (res->prctno[2] == 0) res->prctno[2] = 1;\r
+\r
+                       /* p. 67, B.17 & B.18, ISO/IEC IS15444-1 : 2002  */\r
+                       if (resno == 0) {\r
+                               tlcbgxstart = tlprcxstart;\r
+                               tlcbgystart = tlprcystart;\r
+                               tlcbgzstart = tlprczstart;\r
+                               brcbgxend = brprcxend;\r
+                               brcbgyend = brprcyend;\r
+                               brcbgzend = brprczend;\r
+                               cbgwidthexpn = pdx;\r
+                               cbgheightexpn = pdy;\r
+                               cbglengthexpn = pdz;\r
+                       } else {\r
+                               tlcbgxstart = int_ceildivpow2(tlprcxstart, 1);\r
+                               tlcbgystart = int_ceildivpow2(tlprcystart, 1);\r
+                               tlcbgzstart = int_ceildivpow2(tlprczstart, 1);\r
+                               brcbgxend = int_ceildivpow2(brprcxend, 1);\r
+                               brcbgyend = int_ceildivpow2(brprcyend, 1);\r
+                               brcbgzend = int_ceildivpow2(brprczend, 1);\r
+                               cbgwidthexpn = pdx - 1;\r
+                               cbgheightexpn = pdy - 1;\r
+                               cbglengthexpn = pdz - 1;\r
+                       }\r
+                       \r
+                       cblkwidthexpn = int_min(tccp->cblk[0], cbgwidthexpn);\r
+                       cblkheightexpn = int_min(tccp->cblk[1], cbgheightexpn);\r
+                       cblklengthexpn = int_min(tccp->cblk[2], cbglengthexpn);\r
+                       \r
+                       res->bands = (opj_tcd_band_t *) opj_malloc(res->numbands * sizeof(opj_tcd_band_t));\r
+                       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                               int x0b, y0b, z0b;\r
+                               int gain, numbps;\r
+                               opj_stepsize_t *ss = NULL;\r
+\r
+                               tcd->band = &res->bands[bandno];\r
+                               band = tcd->band;\r
+\r
+                               band->bandno = resno == 0 ? 0 : bandno + 1;\r
+                               /* Bandno:      0 - LLL         2 - LHL \r
+                                                       1 - HLL         3 - HHL\r
+                                                       4 - LLH         6 - LHH\r
+                                                       5 - HLH         7 - HHH         */\r
+                               x0b = (band->bandno == 1) || (band->bandno == 3) || (band->bandno == 5 ) || (band->bandno == 7 ) ? 1 : 0; \r
+                               y0b = (band->bandno == 2) || (band->bandno == 3) || (band->bandno == 6 ) || (band->bandno == 7 ) ? 1 : 0;\r
+                               z0b = (band->bandno == 4) || (band->bandno == 5) || (band->bandno == 6 ) || (band->bandno == 7 ) ? 1 : 0; \r
+                               \r
+                               /* p. 65, B.15, ISO/IEC IS15444-1 : 2002  */\r
+                               if (band->bandno == 0) {\r
+                                       /* band border (global) */\r
+                                       band->x0 = int_ceildivpow2(tilec->x0, levelnox);\r
+                                       band->y0 = int_ceildivpow2(tilec->y0, levelnoy);\r
+                                       band->z0 = int_ceildivpow2(tilec->z0, levelnoz);\r
+                                       band->x1 = int_ceildivpow2(tilec->x1, levelnox);\r
+                                       band->y1 = int_ceildivpow2(tilec->y1, levelnoy);\r
+                                       band->z1 = int_ceildivpow2(tilec->z1, levelnoz);\r
+                               } else {\r
+                                       band->x0 = int_ceildivpow2(tilec->x0 - (1 << levelnox) * x0b, levelnox + 1);\r
+                                       band->y0 = int_ceildivpow2(tilec->y0 - (1 << levelnoy) * y0b, levelnoy + 1);\r
+                                       band->z0 = int_ceildivpow2(tilec->z0 - (1 << levelnoz) * z0b, (resno <= diff) ? levelnoz : levelnoz + 1);\r
+                                       band->x1 = int_ceildivpow2(tilec->x1 - (1 << levelnox) * x0b, levelnox + 1);\r
+                                       band->y1 = int_ceildivpow2(tilec->y1 - (1 << levelnoy) * y0b, levelnoy + 1);\r
+                                       band->z1 = int_ceildivpow2(tilec->z1 - (1 << levelnoz) * z0b, (resno <= diff) ? levelnoz : levelnoz + 1);\r
+                               }\r
+                                                               \r
+                               ss = &tccp->stepsizes[(resno == 0) ? 0 : (prevnumbands + bandno + 1)];\r
+                               if (bandno == (res->numbands - 1)) \r
+                                       prevnumbands += (resno == 0) ? 0 : res->numbands;\r
+                               gain = dwt_getgain(band->bandno,tccp->reversible);                                      \r
+                               numbps = volume->comps[compno].prec + gain;\r
+                               \r
+                               band->stepsize = (float)((1.0 + ss->mant / 2048.0) * pow(2.0, numbps - ss->expn));\r
+                               band->numbps = ss->expn + tccp->numgbits - 1;   /* WHY -1 ? */\r
+                               \r
+                               for (precno = 0; precno < res->prctno[0] * res->prctno[1] * res->prctno[2]; precno++) {\r
+                                       int tlcblkxstart, tlcblkystart, tlcblkzstart, brcblkxend, brcblkyend, brcblkzend;\r
+\r
+                                       int cbgxstart = tlcbgxstart + (precno % res->prctno[0]) * (1 << cbgwidthexpn);\r
+                                       int cbgystart = tlcbgystart + ((precno / (res->prctno[0] * res->prctno[1])) / res->prctno[0]) * (1 << cbgheightexpn);\r
+                                       int cbgzstart = tlcbgzstart + (precno / (res->prctno[0] * res->prctno[1])) * (1 << cbglengthexpn);\r
+                                       int cbgxend = cbgxstart + (1 << cbgwidthexpn);\r
+                                       int cbgyend = cbgystart + (1 << cbgheightexpn);\r
+                                       int cbgzend = cbgzstart + (1 << cbglengthexpn);\r
+\r
+                                       /* opj_tcd_precinct_t *prc=&band->precincts[precno]; */\r
+                                       tcd->prc = &band->precincts[precno];\r
+                                       prc = tcd->prc;\r
+\r
+                                       /* precinct size (global) */\r
+                                       prc->x0 = int_max(cbgxstart, band->x0);\r
+                                       prc->y0 = int_max(cbgystart, band->y0);\r
+                                       prc->z0 = int_max(cbgzstart, band->z0);\r
+                                       prc->x1 = int_min(cbgxend, band->x1);\r
+                                       prc->y1 = int_min(cbgyend, band->y1);\r
+                                       prc->z1 = int_min(cbgzend, band->z1);\r
+\r
+                                       tlcblkxstart = int_floordivpow2(prc->x0, cblkwidthexpn) << cblkwidthexpn;\r
+                                       tlcblkystart = int_floordivpow2(prc->y0, cblkheightexpn) << cblkheightexpn;\r
+                                       tlcblkzstart = int_floordivpow2(prc->z0, cblklengthexpn) << cblklengthexpn;\r
+                                       brcblkxend = int_ceildivpow2(prc->x1, cblkwidthexpn) << cblkwidthexpn;\r
+                                       brcblkyend = int_ceildivpow2(prc->y1, cblkheightexpn) << cblkheightexpn;\r
+                                       brcblkzend = int_ceildivpow2(prc->z1, cblklengthexpn) << cblklengthexpn;\r
+                                       prc->cblkno[0] = (brcblkxend - tlcblkxstart) >> cblkwidthexpn;\r
+                                       prc->cblkno[1] = (brcblkyend - tlcblkystart) >> cblkheightexpn;\r
+                                       prc->cblkno[2] = (brcblkzend - tlcblkzstart) >> cblklengthexpn;\r
+                                       prc->cblkno[2] = (prc->cblkno[2] == 0) ? 1 : prc->cblkno[2];\r
+\r
+                                       opj_free(prc->cblks);\r
+                                       prc->cblks = (opj_tcd_cblk_t *) opj_malloc((prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]) * sizeof(opj_tcd_cblk_t));\r
+                                       prc->incltree = tgt_create(prc->cblkno[0], prc->cblkno[1], prc->cblkno[2]);\r
+                                       prc->imsbtree = tgt_create(prc->cblkno[0], prc->cblkno[1], prc->cblkno[2]);\r
+\r
+                                       for (cblkno = 0; cblkno < (prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]); cblkno++) {\r
+                                                       int cblkxstart = tlcblkxstart + (cblkno % prc->cblkno[0]) * (1 << cblkwidthexpn);\r
+                                                       int cblkystart = tlcblkystart + ((cblkno % (prc->cblkno[0] * prc->cblkno[1])) / prc->cblkno[0]) * (1 << cblkheightexpn);\r
+                                                       int cblkzstart = tlcblkzstart + (cblkno / (prc->cblkno[0] * prc->cblkno[1])) * (1 << cblklengthexpn);\r
+                                                       int cblkxend = cblkxstart + (1 << cblkwidthexpn);\r
+                                                       int cblkyend = cblkystart + (1 << cblkheightexpn);\r
+                                                       int cblkzend = cblkzstart + (1 << cblklengthexpn);\r
+                                                       int prec = ((tilec->bpp > 16) ? 3 : ((tilec->bpp > 8) ? 2 : 1));\r
+\r
+                                                       tcd->cblk = &prc->cblks[cblkno];\r
+                                                       cblk = tcd->cblk;\r
+\r
+                                                       /* code-block size (global) */\r
+                                                       cblk->x0 = int_max(cblkxstart, prc->x0);\r
+                                                       cblk->y0 = int_max(cblkystart, prc->y0);\r
+                                                       cblk->z0 = int_max(cblkzstart, prc->z0);\r
+                                                       cblk->x1 = int_min(cblkxend, prc->x1);\r
+                                                       cblk->y1 = int_min(cblkyend, prc->y1);\r
+                                                       cblk->z1 = int_min(cblkzend, prc->z1);\r
+                                       }\r
+                               } /* precno */\r
+                       } /* bandno */\r
+               } /* resno */\r
+       } /* compno */\r
+       //tcd_dump(stdout, tcd, tcd->tcd_volume);\r
+}\r
+\r
+\r
+void tcd_free_encode(opj_tcd_t *tcd) {\r
+       int tileno, compno, resno, bandno, precno;\r
+\r
+       opj_tcd_tile_t *tile = NULL;            /* pointer to tcd->tile         */\r
+//     opj_tcd_slice_t *slice = NULL;          /* pointer to tcd->slice */\r
+       opj_tcd_tilecomp_t *tilec = NULL;       /* pointer to tcd->tilec        */\r
+       opj_tcd_resolution_t *res = NULL;       /* pointer to tcd->res          */\r
+       opj_tcd_band_t *band = NULL;            /* pointer to tcd->band         */\r
+       opj_tcd_precinct_t *prc = NULL;         /* pointer to tcd->prc          */\r
+\r
+       for (tileno = 0; tileno < 1; tileno++) {\r
+               tcd->tile = tcd->tcd_volume->tiles;\r
+               tile = tcd->tile;\r
+\r
+               for (compno = 0; compno < tile->numcomps; compno++) {\r
+                       tcd->tilec = &tile->comps[compno];\r
+                       tilec = tcd->tilec;\r
+\r
+                       for (resno = 0; resno < tilec->numresolution[0]; resno++) {\r
+                               tcd->res = &tilec->resolutions[resno];\r
+                               res = tcd->res;\r
+\r
+                               for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                                       tcd->band = &res->bands[bandno];\r
+                                       band = tcd->band;\r
+\r
+                                       for (precno = 0; precno < res->prctno[0] * res->prctno[1] * res->prctno[2]; precno++) {\r
+                                               tcd->prc = &band->precincts[precno];\r
+                                               prc = tcd->prc;\r
+\r
+                                               if (prc->incltree != NULL) {\r
+                            tgt_destroy(prc->incltree);\r
+                            prc->incltree = NULL;\r
+                                               }\r
+                                               if (prc->imsbtree != NULL) {\r
+                            tgt_destroy(prc->imsbtree);\r
+                            prc->imsbtree = NULL;\r
+                                               }\r
+                                               opj_free(prc->cblks);\r
+                                               prc->cblks = NULL;\r
+                                       } /* for (precno */\r
+                                       opj_free(band->precincts);\r
+                                       band->precincts = NULL;\r
+                               } /* for (bandno */\r
+                       } /* for (resno */\r
+                       opj_free(tilec->resolutions);\r
+                       tilec->resolutions = NULL;\r
+               } /* for (compno */\r
+               opj_free(tile->comps);\r
+               tile->comps = NULL;\r
+       } /* for (tileno */\r
+       opj_free(tcd->tcd_volume->tiles);\r
+       tcd->tcd_volume->tiles = NULL;\r
+}\r
+\r
+/* ----------------------------------------------------------------------- */\r
+void tcd_malloc_decode(opj_tcd_t *tcd, opj_volume_t * volume, opj_cp_t * cp) {\r
+       int tileno, compno, resno, bandno, precno, cblkno, res_max,\r
+               i, j, p, q, r;\r
+       unsigned int x0 = 0, y0 = 0, z0 = 0, \r
+               x1 = 0, y1 = 0, z1 = 0, \r
+               w, h, l;\r
+\r
+       tcd->volume = volume;\r
+       tcd->cp = cp;\r
+       tcd->tcd_volume->tw = cp->tw;\r
+       tcd->tcd_volume->th = cp->th;\r
+       tcd->tcd_volume->tl = cp->tl;\r
+       tcd->tcd_volume->tiles = (opj_tcd_tile_t *) opj_malloc(cp->tw * cp->th * cp->tl * sizeof(opj_tcd_tile_t));\r
+       \r
+       for (i = 0; i < cp->tileno_size; i++) {\r
+               opj_tcp_t *tcp = &(cp->tcps[cp->tileno[i]]);\r
+               opj_tcd_tile_t *tile = &(tcd->tcd_volume->tiles[cp->tileno[i]]);\r
+       \r
+               /* p61 ISO/IEC IS15444-1 : 2002 */\r
+               /* curtileno --> raster scanned index of tiles */\r
+               /* p,q,r --> matricial index of tiles */\r
+               tileno = cp->tileno[i];\r
+               p = tileno % cp->tw;    \r
+               q = tileno / cp->tw;    \r
+               r = tileno / (cp->tw * cp->th); /* extension to 3-D */\r
+\r
+               /* 4 borders of the tile rescale on the volume if necessary (B.3)*/\r
+               tile->x0 = int_max(cp->tx0 + p * cp->tdx, volume->x0);\r
+               tile->y0 = int_max(cp->ty0 + q * cp->tdy, volume->y0);\r
+               tile->z0 = int_max(cp->tz0 + r * cp->tdz, volume->z0);\r
+               tile->x1 = int_min(cp->tx0 + (p + 1) * cp->tdx, volume->x1);\r
+               tile->y1 = int_min(cp->ty0 + (q + 1) * cp->tdy, volume->y1);\r
+               tile->z1 = int_min(cp->tz0 + (r + 1) * cp->tdz, volume->z1);\r
+               tile->numcomps = volume->numcomps;              \r
+               \r
+               tile->comps = (opj_tcd_tilecomp_t *) opj_malloc(volume->numcomps * sizeof(opj_tcd_tilecomp_t));\r
+               for (compno = 0; compno < tile->numcomps; compno++) {\r
+                       opj_tccp_t *tccp = &tcp->tccps[compno];\r
+                       opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+                       int prevnumbands = 0;\r
+\r
+                       /* border of each tile component (global) */\r
+                       tilec->x0 = int_ceildiv(tile->x0, volume->comps[compno].dx);\r
+                       tilec->y0 = int_ceildiv(tile->y0, volume->comps[compno].dy);\r
+                       tilec->z0 = int_ceildiv(tile->z0, volume->comps[compno].dz);\r
+                       tilec->x1 = int_ceildiv(tile->x1, volume->comps[compno].dx);\r
+                       tilec->y1 = int_ceildiv(tile->y1, volume->comps[compno].dy);\r
+                       tilec->z1 = int_ceildiv(tile->z1, volume->comps[compno].dz);\r
+                       \r
+                       tilec->data = (int *) opj_malloc((tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0) * (tilec->z1 - tilec->z0) * sizeof(int));\r
+\r
+                       res_max = 0;\r
+                       for (i = 0;i < 3; i++){\r
+                               tilec->numresolution[i] = tccp->numresolution[i];\r
+                               //Greater of 3 resolutions contains all information\r
+                               res_max = (tilec->numresolution[i] > res_max) ? tilec->numresolution[i] : res_max;\r
+                       }\r
+\r
+                       tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(res_max * sizeof(opj_tcd_resolution_t));\r
+\r
+                       for (resno = 0; resno < res_max; resno++) {\r
+                               opj_tcd_resolution_t *res = &tilec->resolutions[resno];\r
+                               int pdx, pdy, pdz;\r
+                               int tlprcxstart, tlprcystart, tlprczstart, brprcxend, brprcyend, brprczend;\r
+                               int tlcbgxstart, tlcbgystart, tlcbgzstart, brcbgxend, brcbgyend, brcbgzend;\r
+                               int cbgwidthexpn, cbgheightexpn, cbglengthexpn;\r
+                               int cblkwidthexpn, cblkheightexpn, cblklengthexpn;\r
+                               int levelnox = tilec->numresolution[0] - 1 - resno; \r
+                               int levelnoy = tilec->numresolution[1] - 1 - resno;\r
+                               int diff = tccp->numresolution[0] - tccp->numresolution[2]; \r
+                               int levelnoz = tilec->numresolution[2] - 1 - ((resno <= diff) ? 0 : (resno - diff));\r
+                                       if (levelnoz < 0) levelnoz = 0;\r
+\r
+                               /* border for each resolution level (global) */\r
+                               res->x0 = int_ceildivpow2(tilec->x0, levelnox);\r
+                               res->y0 = int_ceildivpow2(tilec->y0, levelnoy);\r
+                               res->z0 = int_ceildivpow2(tilec->z0, levelnoz);\r
+                               res->x1 = int_ceildivpow2(tilec->x1, levelnox);\r
+                               res->y1 = int_ceildivpow2(tilec->y1, levelnoy);\r
+                               res->z1 = int_ceildivpow2(tilec->z1, levelnoz);\r
+                               res->numbands = (resno == 0) ? 1 : (resno <= diff) ? 3 : 7; /* --> 3D */\r
+                               \r
+                               /* p. 30, table A-13, ISO/IEC IS154444-1 : 2002 */\r
+                               if (tccp->csty & J3D_CCP_CSTY_PRT) {\r
+                                       pdx = tccp->prctsiz[0][resno];\r
+                                       pdy = tccp->prctsiz[1][resno];\r
+                                       pdz = tccp->prctsiz[2][resno];\r
+                               } else {\r
+                                       pdx = 15;\r
+                                       pdy = 15;\r
+                                       pdz = 15;\r
+                               }\r
+                               \r
+                               /* p. 66, B.16, ISO/IEC IS15444-1 : 2002  */\r
+                               tlprcxstart = int_floordivpow2(res->x0, pdx) << pdx;\r
+                               tlprcystart = int_floordivpow2(res->y0, pdy) << pdy;\r
+                               tlprczstart = int_floordivpow2(res->z0, pdz) << pdz;\r
+                               brprcxend = int_ceildivpow2(res->x1, pdx) << pdx;\r
+                               brprcyend = int_ceildivpow2(res->y1, pdy) << pdy;\r
+                               brprczend = int_ceildivpow2(res->z1, pdz) << pdz;\r
+                               \r
+                               res->prctno[0] = (brprcxend - tlprcxstart) >> pdx;\r
+                               res->prctno[1] = (brprcyend - tlprcystart) >> pdy;\r
+                               res->prctno[2] = (brprczend - tlprczstart) >> pdz;\r
+                               \r
+                               /* p. 67, B.17 & B.18, ISO/IEC IS15444-1 : 2002  */\r
+                               if (resno == 0) {\r
+                                       tlcbgxstart = tlprcxstart;//0\r
+                                       tlcbgystart = tlprcystart;\r
+                                       tlcbgzstart = tlprczstart;\r
+                                       brcbgxend = brprcxend;//1\r
+                                       brcbgyend = brprcyend;\r
+                                       brcbgzend = brprczend;\r
+                                       cbgwidthexpn = pdx; //15\r
+                                       cbgheightexpn = pdy;\r
+                                       cbglengthexpn = pdz;\r
+                               } else {\r
+                                       tlcbgxstart = int_ceildivpow2(tlprcxstart, 1);\r
+                                       tlcbgystart = int_ceildivpow2(tlprcystart, 1);\r
+                                       tlcbgzstart = int_ceildivpow2(tlprczstart, 1);\r
+                                       brcbgxend = int_ceildivpow2(brprcxend, 1);\r
+                                       brcbgyend = int_ceildivpow2(brprcyend, 1);\r
+                                       brcbgzend = int_ceildivpow2(brprczend, 1);\r
+                                       cbgwidthexpn = pdx - 1;\r
+                                       cbgheightexpn = pdy - 1;\r
+                                       cbglengthexpn = pdz - 1;\r
+                               }\r
+                               \r
+                               cblkwidthexpn = int_min(tccp->cblk[0], cbgwidthexpn); //6\r
+                               cblkheightexpn = int_min(tccp->cblk[1], cbgheightexpn); //6\r
+                               cblklengthexpn = int_min(tccp->cblk[2], cbglengthexpn); //6\r
+\r
+                               res->bands = (opj_tcd_band_t *) opj_malloc(res->numbands * sizeof(opj_tcd_band_t));\r
+                               for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                                       int x0b, y0b, z0b;\r
+                                       int gain, numbps;\r
+                                       opj_stepsize_t *ss = NULL;\r
+\r
+                                       opj_tcd_band_t *band = &res->bands[bandno];\r
+                                       band->bandno = resno == 0 ? 0 : bandno + 1;\r
+                                       /* Bandno:      0 - LLL         2 - LHL \r
+                                                               1 - HLL         3 - HHL\r
+                                                               4 - LLH         6 - LHH\r
+                                                               5 - HLH         7 - HHH         */\r
+                                       x0b = (band->bandno == 1) || (band->bandno == 3) || (band->bandno == 5 ) || (band->bandno == 7 ) ? 1 : 0; \r
+                                       y0b = (band->bandno == 2) || (band->bandno == 3) || (band->bandno == 6 ) || (band->bandno == 7 ) ? 1 : 0;\r
+                                       z0b = (band->bandno == 4) || (band->bandno == 5) || (band->bandno == 6 ) || (band->bandno == 7 ) ? 1 : 0; \r
+                                       \r
+                                       /* p. 65, B.15, ISO/IEC IS15444-1 : 2002  */\r
+                                       if (band->bandno == 0) {\r
+                                               /* band border (global) */\r
+                                               band->x0 = int_ceildivpow2(tilec->x0, levelnox);\r
+                                               band->y0 = int_ceildivpow2(tilec->y0, levelnoy);\r
+                                               band->z0 = int_ceildivpow2(tilec->z0, levelnoz);\r
+                                               band->x1 = int_ceildivpow2(tilec->x1, levelnox);\r
+                                               band->y1 = int_ceildivpow2(tilec->y1, levelnoy);\r
+                                               band->z1 = int_ceildivpow2(tilec->z1, levelnoz);\r
+                                       } else {\r
+                                               band->x0 = int_ceildivpow2(tilec->x0 - (1 << levelnox) * x0b, levelnox + 1);\r
+                                               band->y0 = int_ceildivpow2(tilec->y0 - (1 << levelnoy) * y0b, levelnoy + 1);\r
+                                               band->z0 = int_ceildivpow2(tilec->z0 - (1 << levelnoz) * z0b, (resno <= diff) ? levelnoz : levelnoz + 1);\r
+                                               band->x1 = int_ceildivpow2(tilec->x1 - (1 << levelnox) * x0b, levelnox + 1);\r
+                                               band->y1 = int_ceildivpow2(tilec->y1 - (1 << levelnoy) * y0b, levelnoy + 1);\r
+                                               band->z1 = int_ceildivpow2(tilec->z1 - (1 << levelnoz) * z0b, (resno <= diff) ? levelnoz : levelnoz + 1);\r
+                                       }       \r
+\r
+                                       ss = &tccp->stepsizes[(resno == 0) ? 0 : (prevnumbands + bandno + 1)];\r
+                                       if (bandno == (res->numbands - 1)) \r
+                                               prevnumbands += (resno == 0) ? 0 : res->numbands;\r
+                                       gain = dwt_getgain(band->bandno,tccp->reversible);                                      \r
+                                       numbps = volume->comps[compno].prec + gain;\r
+\r
+                                       band->stepsize = (float)((1.0 + ss->mant / 2048.0) * pow(2.0, numbps - ss->expn));\r
+                                       band->numbps = ss->expn + tccp->numgbits - 1;   /* WHY -1 ? */\r
+                                       \r
+                                       band->precincts = (opj_tcd_precinct_t *) opj_malloc(res->prctno[0] * res->prctno[1] * res->prctno[2] * sizeof(opj_tcd_precinct_t));\r
+                                       \r
+                                       for (precno = 0; precno < res->prctno[0] * res->prctno[1] * res->prctno[2]; precno++) {\r
+                                               int tlcblkxstart, tlcblkystart, tlcblkzstart, brcblkxend, brcblkyend, brcblkzend;\r
+\r
+                                               int cbgxstart = tlcbgxstart + (precno % res->prctno[0]) * (1 << cbgwidthexpn);\r
+                                               int cbgystart = tlcbgystart + (precno / res->prctno[0]) * (1 << cbgheightexpn);\r
+                                               int cbgzstart = tlcbgzstart + (precno / (res->prctno[0] * res->prctno[1])) * (1 << cbglengthexpn);\r
+                                               int cbgxend = cbgxstart + (1 << cbgwidthexpn);\r
+                                               int cbgyend = cbgystart + (1 << cbgheightexpn);\r
+                                               int cbgzend = cbgzstart + (1 << cbglengthexpn);\r
+\r
+                                               opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+                                               /* precinct size (global) */\r
+                                               prc->x0 = int_max(cbgxstart, band->x0);\r
+                                               prc->y0 = int_max(cbgystart, band->y0);\r
+                                               prc->z0 = int_max(cbgzstart, band->z0);\r
+                                               prc->x1 = int_min(cbgxend, band->x1);\r
+                                               prc->y1 = int_min(cbgyend, band->y1);\r
+                                               prc->z1 = int_min(cbgzend, band->z1);\r
+\r
+                                               tlcblkxstart = int_floordivpow2(prc->x0, cblkwidthexpn) << cblkwidthexpn;\r
+                                               tlcblkystart = int_floordivpow2(prc->y0, cblkheightexpn) << cblkheightexpn;\r
+                                               tlcblkzstart = int_floordivpow2(prc->z0, cblklengthexpn) << cblklengthexpn;\r
+                                               brcblkxend = int_ceildivpow2(prc->x1, cblkwidthexpn) << cblkwidthexpn;\r
+                                               brcblkyend = int_ceildivpow2(prc->y1, cblkheightexpn) << cblkheightexpn;\r
+                                               brcblkzend = int_ceildivpow2(prc->z1, cblklengthexpn) << cblklengthexpn;\r
+                                               prc->cblkno[0] = (brcblkxend - tlcblkxstart) >> cblkwidthexpn;\r
+                                               prc->cblkno[1] = (brcblkyend - tlcblkystart) >> cblkheightexpn;\r
+                                               prc->cblkno[2] = (brcblkzend - tlcblkzstart) >> cblklengthexpn;\r
+                                               prc->cblkno[2] = (prc->cblkno[2] == 0) ? 1 : prc->cblkno[2];\r
+\r
+                                               prc->cblks = (opj_tcd_cblk_t *) opj_malloc((prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]) * sizeof(opj_tcd_cblk_t));\r
+                                               prc->incltree = tgt_create(prc->cblkno[0], prc->cblkno[1], prc->cblkno[2]);\r
+                                               prc->imsbtree = tgt_create(prc->cblkno[0], prc->cblkno[1], prc->cblkno[2]);\r
+                                               \r
+                                               for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                                                       int cblkxstart = tlcblkxstart + (cblkno % prc->cblkno[0]) * (1 << cblkwidthexpn);\r
+                                                       int cblkystart = tlcblkystart + ((cblkno % (prc->cblkno[0] * prc->cblkno[1])) / prc->cblkno[0]) * (1 << cblkheightexpn);\r
+                                                       int cblkzstart = tlcblkzstart + (cblkno / (prc->cblkno[0] * prc->cblkno[1])) * (1 << cblklengthexpn);\r
+                                                       int cblkxend = cblkxstart + (1 << cblkwidthexpn);\r
+                                                       int cblkyend = cblkystart + (1 << cblkheightexpn);\r
+                                                       int cblkzend = cblkzstart + (1 << cblklengthexpn);\r
+                                                       int prec = ((tilec->bpp > 16) ? 3 : ((tilec->bpp > 8) ? 2 : 1));\r
+                                                       /* code-block size (global) */\r
+                                                       opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+                                                       \r
+                                                       /* code-block size (global) */\r
+                                                       cblk->x0 = int_max(cblkxstart, prc->x0);\r
+                                                       cblk->y0 = int_max(cblkystart, prc->y0);\r
+                                                       cblk->z0 = int_max(cblkzstart, prc->z0);\r
+                                                       cblk->x1 = int_min(cblkxend, prc->x1);\r
+                                                       cblk->y1 = int_min(cblkyend, prc->y1);\r
+                                                       cblk->z1 = int_min(cblkzend, prc->z1);\r
+                                               }\r
+                                       } /* precno */\r
+                               } /* bandno */\r
+                       } /* resno */\r
+               } /* compno */\r
+       } /* i = 0..cp->tileno_size */\r
+\r
+       //tcd_dump(stdout, tcd, tcd->tcd_volume);\r
+\r
+       /* \r
+       Allocate place to store the decoded data = final volume\r
+       Place limited by the tile really present in the codestream \r
+       */\r
+       \r
+       for (i = 0; i < volume->numcomps; i++) {\r
+               for (j = 0; j < cp->tileno_size; j++) {\r
+                       tileno = cp->tileno[j];\r
+                       x0 = (j == 0) ? tcd->tcd_volume->tiles[tileno].comps[i].x0 : int_min(x0,(unsigned int) tcd->tcd_volume->tiles[tileno].comps[i].x0);\r
+                       y0 = (j == 0) ? tcd->tcd_volume->tiles[tileno].comps[i].y0 : int_min(y0,(unsigned int) tcd->tcd_volume->tiles[tileno].comps[i].y0);\r
+                       z0 = (j == 0) ? tcd->tcd_volume->tiles[tileno].comps[i].z0 : int_min(z0,(unsigned int) tcd->tcd_volume->tiles[tileno].comps[i].z0);\r
+                       x1 = (j == 0) ? tcd->tcd_volume->tiles[tileno].comps[i].x1 : int_max(x1,(unsigned int) tcd->tcd_volume->tiles[tileno].comps[i].x1);\r
+                       y1 = (j == 0) ? tcd->tcd_volume->tiles[tileno].comps[i].y1 : int_max(y1,(unsigned int) tcd->tcd_volume->tiles[tileno].comps[i].y1);\r
+                       z1 = (j == 0) ? tcd->tcd_volume->tiles[tileno].comps[i].z1 : int_max(z1,(unsigned int) tcd->tcd_volume->tiles[tileno].comps[i].z1);\r
+               }\r
+               \r
+               w = x1 - x0;\r
+               h = y1 - y0;\r
+               l = z1 - z0;\r
+               \r
+               volume->comps[i].data = (int *) opj_malloc(w * h * l * sizeof(int));\r
+               volume->comps[i].w = w;\r
+               volume->comps[i].h = h;\r
+               volume->comps[i].l = l;\r
+               volume->comps[i].x0 = x0;\r
+               volume->comps[i].y0 = y0;\r
+               volume->comps[i].z0 = z0;\r
+               volume->comps[i].bigendian = cp->bigendian;\r
+       }\r
+}\r
+\r
+void tcd_free_decode(opj_tcd_t *tcd) {\r
+       int tileno,compno,resno,bandno,precno;\r
+\r
+       opj_tcd_volume_t *tcd_volume = tcd->tcd_volume;\r
+       \r
+       for (tileno = 0; tileno < tcd_volume->tw * tcd_volume->th * tcd_volume->tl; tileno++) {\r
+               opj_tcd_tile_t *tile = &tcd_volume->tiles[tileno];\r
+               for (compno = 0; compno < tile->numcomps; compno++) {\r
+                       opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+                       for (resno = 0; resno < tilec->numresolution[0]; resno++) {\r
+                               opj_tcd_resolution_t *res = &tilec->resolutions[resno];\r
+                               for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                                       opj_tcd_band_t *band = &res->bands[bandno];\r
+                                       for (precno = 0; precno < res->prctno[1] * res->prctno[0] * res->prctno[2]; precno++) {\r
+                                               opj_tcd_precinct_t *prec = &band->precincts[precno];\r
+                                               if (prec->cblks != NULL) opj_free(prec->cblks);\r
+                                               if (prec->imsbtree != NULL) tgt_destroy(prec->imsbtree);\r
+                        if (prec->incltree != NULL) tgt_destroy(prec->incltree);\r
+                                               /*for (treeno = 0; treeno < prec->numtrees; treeno++){\r
+                            if (prec->imsbtree[treeno] != NULL) tgt_destroy(prec->imsbtree[treeno]);\r
+                            if (prec->incltree[treeno] != NULL) tgt_destroy(prec->incltree[treeno]);\r
+                                               }*/\r
+                                       }\r
+                                       if (band->precincts != NULL) opj_free(band->precincts);\r
+                               }\r
+                       }\r
+                       if (tilec->resolutions != NULL) opj_free(tilec->resolutions);\r
+               }\r
+               if (tile->comps != NULL) opj_free(tile->comps);\r
+       }\r
+\r
+       if (tcd_volume->tiles != NULL) opj_free(tcd_volume->tiles);\r
+}\r
+\r
+\r
+\r
+/* ----------------------------------------------------------------------- */\r
+void tcd_makelayer_fixed(opj_tcd_t *tcd, int layno, int final) {\r
+       int compno, resno, bandno, precno, cblkno;\r
+       int value;                      /*, matrice[tcd_tcp->numlayers][tcd_tile->comps[0].numresolution[0]][3]; */\r
+       int matrice[10][10][3];\r
+       int i, j, k;\r
+\r
+       opj_cp_t *cp = tcd->cp;\r
+       opj_tcd_tile_t *tcd_tile = tcd->tcd_tile;\r
+       opj_tcp_t *tcd_tcp = tcd->tcp;\r
+\r
+       /*matrice=(int*)opj_malloc(tcd_tcp->numlayers*tcd_tile->comps[0].numresolution[0]*3*sizeof(int)); */\r
+       \r
+       for (compno = 0; compno < tcd_tile->numcomps; compno++) {\r
+               opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];\r
+               for (i = 0; i < tcd_tcp->numlayers; i++) {\r
+                       for (j = 0; j < tilec->numresolution[0]; j++) {\r
+                               for (k = 0; k < 3; k++) {\r
+                                       matrice[i][j][k] =\r
+                                               (int) (cp->matrice[i * tilec->numresolution[0] * 3 + j * 3 + k] \r
+                                               * (float) (tcd->volume->comps[compno].prec / 16.0));\r
+                               }\r
+                       }\r
+               }\r
+        \r
+               for (resno = 0; resno < tilec->numresolution[0]; resno++) {\r
+                       opj_tcd_resolution_t *res = &tilec->resolutions[resno];\r
+                       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                               opj_tcd_band_t *band = &res->bands[bandno];\r
+                               for (precno = 0; precno < res->prctno[0] * res->prctno[1] * res->prctno[2]; precno++) {\r
+                                       opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+                                       for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                                               opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+                                               opj_tcd_layer_t *layer = &cblk->layers[layno];\r
+                                               int n;\r
+                                               int imsb = tcd->volume->comps[compno].prec - cblk->numbps;      /* number of bit-plan equal to zero */\r
+                                               /* Correction of the matrix of coefficient to include the IMSB information */\r
+                                               if (layno == 0) {\r
+                                                       value = matrice[layno][resno][bandno];\r
+                                                       if (imsb >= value) {\r
+                                                               value = 0;\r
+                                                       } else {\r
+                                                               value -= imsb;\r
+                                                       }\r
+                                               } else {\r
+                                                       value = matrice[layno][resno][bandno] - matrice[layno - 1][resno][bandno];\r
+                                                       if (imsb >= matrice[layno - 1][resno][bandno]) {\r
+                                                               value -= (imsb - matrice[layno - 1][resno][bandno]);\r
+                                                               if (value < 0) {\r
+                                                                       value = 0;\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                               \r
+                                               if (layno == 0) {\r
+                                                       cblk->numpassesinlayers = 0;\r
+                                               }\r
+                                               \r
+                                               n = cblk->numpassesinlayers;\r
+                                               if (cblk->numpassesinlayers == 0) {\r
+                                                       if (value != 0) {\r
+                                                               n = 3 * value - 2 + cblk->numpassesinlayers;\r
+                                                       } else {\r
+                                                               n = cblk->numpassesinlayers;\r
+                                                       }\r
+                                               } else {\r
+                                                       n = 3 * value + cblk->numpassesinlayers;\r
+                                               }\r
+                                               \r
+                                               layer->numpasses = n - cblk->numpassesinlayers;\r
+                                               \r
+                                               if (!layer->numpasses)\r
+                                                       continue;\r
+                                               \r
+                                               if (cblk->numpassesinlayers == 0) {\r
+                                                       layer->len = cblk->passes[n - 1].rate;\r
+                                                       layer->data = cblk->data;\r
+                                               } else {\r
+                                                       layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate;\r
+                                                       layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate;\r
+                                               }\r
+                                               if (final)\r
+                                                       cblk->numpassesinlayers = n;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+}\r
+\r
+void tcd_rateallocate_fixed(opj_tcd_t *tcd) {\r
+       int layno;\r
+       for (layno = 0; layno < tcd->tcp->numlayers; layno++) {\r
+               tcd_makelayer_fixed(tcd, layno, 1);\r
+       }\r
+}\r
+\r
+void tcd_makelayer(opj_tcd_t *tcd, int layno, double thresh, int final) {\r
+       int compno, resno, bandno, precno, cblkno, passno;\r
+       \r
+       opj_tcd_tile_t *tcd_tile = tcd->tcd_tile;\r
+\r
+       tcd_tile->distolayer[layno] = 0;        /* fixed_quality */\r
+       \r
+       for (compno = 0; compno < tcd_tile->numcomps; compno++) {\r
+               opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];\r
+               for (resno = 0; resno < tilec->numresolution[0]; resno++) {\r
+                       opj_tcd_resolution_t *res = &tilec->resolutions[resno];\r
+                       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                               opj_tcd_band_t *band = &res->bands[bandno];\r
+                               for (precno = 0; precno < res->prctno[0] * res->prctno[1] * res->prctno[2]; precno++) {\r
+                                       opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+                                       for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                                               opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+                                               opj_tcd_layer_t *layer = &cblk->layers[layno];\r
+                                               \r
+                                               int n;\r
+                                               if (layno == 0) {\r
+                                                       cblk->numpassesinlayers = 0;\r
+                                               }\r
+                                               n = cblk->numpassesinlayers;\r
+                                               for (passno = cblk->numpassesinlayers; passno < cblk->totalpasses; passno++) {\r
+                                                       int dr;\r
+                                                       double dd;\r
+                                                       opj_tcd_pass_t *pass = &cblk->passes[passno];\r
+                                                       if (n == 0) {\r
+                                                               dr = pass->rate;\r
+                                                               dd = pass->distortiondec;\r
+                                                       } else {\r
+                                                               dr = pass->rate - cblk->passes[n - 1].rate;\r
+                                                               dd = pass->distortiondec - cblk->passes[n - 1].distortiondec;\r
+                                                       }\r
+                                                       if (!dr) {\r
+                                                               if (dd)\r
+                                                                       n = passno + 1;\r
+                                                               continue;\r
+                                                       }\r
+                                                       if (dd / dr >= thresh){\r
+                                                               n = passno + 1;\r
+                                                       }\r
+                                               }\r
+                                               layer->numpasses = n - cblk->numpassesinlayers;\r
+                                               \r
+                                               if (!layer->numpasses) {\r
+                                                       layer->disto = 0;\r
+                                                       continue;\r
+                                               }\r
+                                               if (cblk->numpassesinlayers == 0) {\r
+                                                       layer->len = cblk->passes[n - 1].rate;\r
+                                                       layer->data = cblk->data;\r
+                                                       layer->disto = cblk->passes[n - 1].distortiondec;\r
+                                               } else {\r
+                                                       layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate;\r
+                                                       layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate;\r
+                                                       layer->disto = cblk->passes[n - 1].distortiondec - cblk->passes[cblk->numpassesinlayers - 1].distortiondec;\r
+                                               }\r
+                                               \r
+                                               tcd_tile->distolayer[layno] += layer->disto;    /* fixed_quality */\r
+                                               \r
+                                               if (final)\r
+                                                       cblk->numpassesinlayers = n;\r
+\r
+                                       //      fprintf(stdout,"MakeLayer : %d %f %d %d \n",layer->len, layer->disto, layer->numpasses, n);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+}\r
+\r
+bool tcd_rateallocate(opj_tcd_t *tcd, unsigned char *dest, int len, opj_volume_info_t * volume_info) {\r
+       int compno, resno, bandno, precno, cblkno, passno, layno;\r
+       double min, max;\r
+       double cumdisto[100];   /* fixed_quality */\r
+       const double K = 1;             /* 1.1; // fixed_quality */\r
+       double maxSE = 0;\r
+\r
+       opj_cp_t *cp = tcd->cp;\r
+       opj_tcd_tile_t *tcd_tile = tcd->tcd_tile;\r
+       opj_tcp_t *tcd_tcp = tcd->tcp;\r
+\r
+       min = DBL_MAX;\r
+       max = 0;\r
+       \r
+       tcd_tile->nbpix = 0;            /* fixed_quality */\r
+       \r
+       for (compno = 0; compno < tcd_tile->numcomps; compno++) {\r
+               opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];\r
+               tilec->nbpix = 0;\r
+               for (resno = 0; resno < tilec->numresolution[0]; resno++) {\r
+                       opj_tcd_resolution_t *res = &tilec->resolutions[resno];\r
+                       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                               opj_tcd_band_t *band = &res->bands[bandno];\r
+                               for (precno = 0; precno < res->prctno[0] * res->prctno[1] * res->prctno[2]; precno++) {\r
+                                       opj_tcd_precinct_t *prc = &band->precincts[precno];\r
+                                       for (cblkno = 0; cblkno < prc->cblkno[0] * prc->cblkno[1] * prc->cblkno[2]; cblkno++) {\r
+                                               opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];\r
+                                               for (passno = 0; passno < cblk->totalpasses; passno++) {\r
+                                                       opj_tcd_pass_t *pass = &cblk->passes[passno];\r
+                                                       int dr;\r
+                                                       double dd, rdslope;\r
+                                                       if (passno == 0) {\r
+                                                               dr = pass->rate;\r
+                                                               dd = pass->distortiondec;\r
+                                                       } else {\r
+                                                               dr = pass->rate - cblk->passes[passno - 1].rate;\r
+                                                               dd = pass->distortiondec - cblk->passes[passno - 1].distortiondec;\r
+                                                       }\r
+                                                       if (dr == 0) {\r
+                                                               continue;\r
+                                                       }\r
+                                                       rdslope = dd / dr;\r
+                                                       if (rdslope < min) {\r
+                                                               min = rdslope;\r
+                                                       }\r
+                                                       if (rdslope > max) {\r
+                                                               max = rdslope;\r
+                                                       }\r
+\r
+                                               } /* passno */\r
+                                               \r
+                                               /* fixed_quality */\r
+                                               tcd_tile->nbpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0) * (cblk->z1 - cblk->z0));\r
+                        tilec->nbpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0) * (cblk->z1 - cblk->z0));\r
+                                       } /* cbklno */ \r
+                               } /* precno */\r
+                       } /* bandno */\r
+               } /* resno */\r
+               \r
+               maxSE += (((double)(1 << tcd->volume->comps[compno].prec) - 1.0) \r
+                       * ((double)(1 << tcd->volume->comps[compno].prec) -1.0)) \r
+                       * ((double)(tilec->nbpix));\r
+       } /* compno */\r
+       \r
+       /* add antonin index */\r
+       if(volume_info && volume_info->index_on) {\r
+               opj_tile_info_t *info_TL = &volume_info->tile[tcd->tcd_tileno];\r
+               info_TL->nbpix = tcd_tile->nbpix;\r
+               info_TL->distotile = tcd_tile->distotile;\r
+               info_TL->thresh = (double *) opj_malloc(tcd_tcp->numlayers * sizeof(double));\r
+       }\r
+       /* dda */\r
+       \r
+       for (layno = 0; layno < tcd_tcp->numlayers; layno++) {\r
+               double lo = min;\r
+               double hi = max;\r
+               int success = 0;\r
+               int maxlen = tcd_tcp->rates[layno] ? int_min(((int) tcd_tcp->rates[layno]), len) : len;\r
+               double goodthresh;\r
+               double distotarget;             /* fixed_quality */\r
+               int i = 0;\r
+               \r
+        /* fixed_quality */\r
+               distotarget = tcd_tile->distotile - ((K * maxSE) / pow((float)10, tcd_tcp->distoratio[layno] / 10));\r
+        \r
+               if ((tcd_tcp->rates[layno]) || (cp->disto_alloc==0)) {\r
+                       opj_t2_t *t2 = t2_create(tcd->cinfo, tcd->volume, cp);\r
+                       int oldl = 0, oldoldl = 0;\r
+                       for (i = 0; i < 128; i++) {\r
+                               double thresh = (lo + hi) / 2;\r
+                               int l = 0;\r
+                               double distoachieved = 0;       /* fixed_quality -q */\r
+                       \r
+                               tcd_makelayer(tcd, layno, thresh, 0);\r
+               \r
+                               if (cp->fixed_quality) {        /* fixed_quality -q */\r
+                                       distoachieved = (layno == 0) ? tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno];\r
+                                       if (distoachieved < distotarget) {\r
+                                               hi = thresh; \r
+                                               continue;\r
+                                       }\r
+                                       lo = thresh;\r
+                               } else {                /* disto_alloc -r, fixed_alloc -f */\r
+                                       l = t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest, maxlen, volume_info);\r
+                                       //fprintf(stdout, "layno %d i %d len=%d max=%d \n",layno,i,l,maxlen);\r
+                                       if (l == -999) {\r
+                                               lo = thresh; \r
+                                               continue;\r
+                                       } else if (l == oldl && oldl == oldoldl && tcd_tile->distolayer[layno] > 0.0 && i>32)\r
+                                               break;\r
+                                       hi = thresh;\r
+                                       oldoldl = oldl;\r
+                                       oldl = l;\r
+                               }\r
+                               success = 1;\r
+                               goodthresh = thresh;\r
+                       } \r
+                       t2_destroy(t2);\r
+               } else {\r
+                       success = 1;\r
+                       goodthresh = min;\r
+               }\r
+               if (!success) {\r
+                       return false;\r
+               }\r
+               \r
+               if(volume_info && volume_info->index_on) {      /* Threshold for Marcela Index */\r
+                       volume_info->tile[tcd->tcd_tileno].thresh[layno] = goodthresh;\r
+               }\r
+               tcd_makelayer(tcd, layno, goodthresh, 1);\r
+               \r
+               /* fixed_quality */\r
+               cumdisto[layno] = (layno == 0) ? tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno];   \r
+       }\r
+\r
+       return true;\r
+}\r
+\r
+/* ----------------------------------------------------------------------- */\r
+int tcd_encode_tile(opj_tcd_t *tcd, int tileno, unsigned char *dest, int len, opj_volume_info_t * volume_info) {\r
+       int compno;\r
+       int l, i, npck = 0;\r
+       double encoding_time;\r
+       \r
+       opj_tcd_tile_t  *tile = NULL;\r
+       opj_tcp_t               *tcd_tcp = NULL;\r
+       opj_cp_t                *cp = NULL;\r
+\r
+       opj_tcp_t               *tcp = &tcd->cp->tcps[0];\r
+       opj_tccp_t              *tccp = &tcp->tccps[0];\r
+       opj_volume_t    *volume = tcd->volume;\r
+       opj_t2_t                *t2 = NULL;             /* T2 component */\r
+\r
+       tcd->tcd_tileno = tileno;                       /* current encoded/decoded tile */\r
+       \r
+       tcd->tcd_tile = tcd->tcd_volume->tiles; /* tile information */\r
+       tile = tcd->tcd_tile;\r
+       \r
+       tcd->tcp = &tcd->cp->tcps[tileno];      /* coding/decoding params of tileno */  \r
+       tcd_tcp = tcd->tcp;\r
+       \r
+       cp = tcd->cp;           /* coding parameters */\r
+\r
+       /* INDEX >> */\r
+       if(volume_info && volume_info->index_on) {\r
+               opj_tcd_tilecomp_t *tilec_idx = &tile->comps[0];        /* based on component 0 */\r
+               for (i = 0; i < tilec_idx->numresolution[0]; i++) {\r
+                       opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[i];\r
+\r
+                       volume_info->tile[tileno].prctno[0][i] = res_idx->prctno[0];\r
+                       volume_info->tile[tileno].prctno[1][i] = res_idx->prctno[1];\r
+                       volume_info->tile[tileno].prctno[2][i] = res_idx->prctno[2];\r
+\r
+                       npck += res_idx->prctno[0] * res_idx->prctno[1] * res_idx->prctno[2];\r
+\r
+                       volume_info->tile[tileno].prctsiz[0][i] = tccp->prctsiz[0][i];\r
+                       volume_info->tile[tileno].prctsiz[1][i] = tccp->prctsiz[1][i];\r
+                       volume_info->tile[tileno].prctsiz[2][i] = tccp->prctsiz[2][i];\r
+               }\r
+               volume_info->tile[tileno].packet = (opj_packet_info_t *) opj_malloc(volume_info->comp * volume_info->layer * npck * sizeof(opj_packet_info_t));\r
+       }\r
+       /* << INDEX */\r
+       \r
+       /*---------------TILE-------------------*/\r
+       encoding_time = opj_clock();    /* time needed to encode a tile */\r
+       \r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               int x, y, z;\r
+               opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+               \r
+               int adjust;\r
+               int offset_x = int_ceildiv(volume->x0, volume->comps[compno].dx); //ceil(x0 / subsampling_dx)\r
+               int offset_y = int_ceildiv(volume->y0, volume->comps[compno].dy);\r
+               int offset_z = int_ceildiv(volume->z0, volume->comps[compno].dz);\r
+               \r
+               int tw = tilec->x1 - tilec->x0;\r
+               int w = int_ceildiv(volume->x1 - volume->x0, volume->comps[compno].dx);\r
+               int th = tilec->y1 - tilec->y0;\r
+               int h = int_ceildiv(volume->y1 - volume->y0, volume->comps[compno].dy);\r
+               int tl = tilec->z1 - tilec->z0;\r
+               int l = int_ceildiv(volume->z1 - volume->z0, volume->comps[compno].dz);\r
+\r
+               \r
+               \r
+               /* extract tile data from volume.comps[0].data to tile.comps[0].data */\r
+               //fprintf(stdout,"[INFO] Extract tile data\n");\r
+               if (tcd->cp->transform_format == TRF_3D_RLS || tcd->cp->transform_format == TRF_3D_LSE) {\r
+                       adjust = 0;\r
+               } else {\r
+            adjust = volume->comps[compno].sgnd ? 0 : 1 << (volume->comps[compno].prec - 1); //sign=='+' --> 2^(prec-1)\r
+                       if (volume->comps[compno].dcoffset != 0){\r
+                               adjust += volume->comps[compno].dcoffset;\r
+                               fprintf(stdout,"[INFO] DC Offset applied: DCO = %d -> adjust = %d\n",volume->comps[compno].dcoffset,adjust);\r
+                       }\r
+               }               \r
+\r
+               if (tcd_tcp->tccps[compno].reversible == 1) { //IF perfect reconstruction (DWT.5-3)\r
+                       for (z = tilec->z0; z < tilec->z1; z++) {\r
+                               for (y = tilec->y0; y < tilec->y1; y++) {\r
+                                       /* start of the src tile scanline */\r
+                                       int *data = &volume->comps[compno].data[(tilec->x0 - offset_x) + (y - offset_y) * w + (z - offset_z) * w * h];\r
+                                       /* start of the dst tile scanline */\r
+                                       int *tile_data = &tilec->data[(y - tilec->y0) * tw + (z - tilec->z0) * tw * th];\r
+                                       for (x = tilec->x0; x < tilec->x1; x++) {\r
+                                               *tile_data++ = *data++ - adjust;\r
+                                       }\r
+                               }\r
+                       }\r
+               } else if (tcd_tcp->tccps[compno].reversible == 0) { //IF not (DWT.9-7)\r
+                       for (z = tilec->z0; z < tilec->z1; z++) {\r
+                               for (y = tilec->y0; y < tilec->y1; y++) {\r
+                                       /* start of the src tile scanline */\r
+                                       int *data = &volume->comps[compno].data[(tilec->x0 - offset_x) + (y - offset_y) * w + (z - offset_z) * w * h];\r
+                                       /* start of the dst tile scanline */\r
+                                       int *tile_data = &tilec->data[(y - tilec->y0) * tw + (z - tilec->z0) * tw * th];\r
+                                       for (x = tilec->x0; x < tilec->x1; x++) {\r
+                                               *tile_data++ = (*data++ - adjust) << 13;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+       \r
+       }\r
+\r
+       /*----------------MCT-------------------*/\r
+       if (tcd_tcp->mct) {\r
+               int samples = (tile->comps[0].x1 - tile->comps[0].x0) * (tile->comps[0].y1 - tile->comps[0].y0) * (tile->comps[0].z1 - tile->comps[0].z0);\r
+               fprintf(stdout,"[INFO] Tcd_encode_tile: mct\n");\r
+               if (tcd_tcp->tccps[0].reversible == 0) {\r
+                       mct_encode_real(tile->comps[0].data, tile->comps[1].data, tile->comps[2].data, samples);\r
+               } else {\r
+                       mct_encode(tile->comps[0].data, tile->comps[1].data, tile->comps[2].data, samples);\r
+               }\r
+       }\r
+       /*----------------TRANSFORM---------------------------------*/\r
+       fprintf(stdout,"[INFO] Tcd_encode_tile: Transform\n");\r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+               dwt_encode(tilec, tcd_tcp->tccps[compno].dwtid);\r
+       } \r
+\r
+       /*-------------------ENTROPY CODING-----------------------------*/\r
+       fprintf(stdout,"[INFO] Tcd_encode_tile: Entropy coding\n");\r
+       if ((cp->encoding_format == ENCOD_2EB)||(cp->encoding_format == ENCOD_3EB))\r
+       {\r
+               if (cp->encoding_format == ENCOD_2EB) {\r
+                       opj_t1_t *t1 = NULL;\r
+                       t1 = t1_create(tcd->cinfo);\r
+                       t1_encode_cblks(t1, tile, tcd_tcp);\r
+                       t1_destroy(t1); \r
+               } else if (cp->encoding_format == ENCOD_3EB) {\r
+                       opj_t1_3d_t *t1 = NULL;         \r
+                       t1 = t1_3d_create(tcd->cinfo);\r
+                       t1_3d_encode_cblks(t1, tile, tcd_tcp);\r
+                       t1_3d_destroy(t1);      \r
+               }\r
+               /*-----------RATE-ALLOCATE------------------*/\r
+               /* INDEX */\r
+               if(volume_info) {\r
+                       volume_info->index_write = 0;\r
+               }\r
+               if (cp->disto_alloc || cp->fixed_quality) {     \r
+                       fprintf(stdout,"[INFO] Tcd_encode_tile: Rate-allocate\n");\r
+                       tcd_rateallocate(tcd, dest, len, volume_info);                  /* Normal Rate/distortion allocation */\r
+               } else {/* fixed_alloc */\r
+           fprintf(stdout,"[INFO] Tcd_encode_tile: Rate-allocate fixed\n");\r
+            tcd_rateallocate_fixed(tcd);                                                       /* Fixed layer allocation */\r
+               }\r
+\r
+               /*--------------TIER2------------------*/\r
+               /* INDEX */\r
+               if(volume_info) {\r
+                       volume_info->index_write = 1;\r
+               }\r
+               fprintf(stdout,"[INFO] Tcd_encode_tile: Tier - 2\n");\r
+        t2 = t2_create(tcd->cinfo, volume, cp);\r
+               l = t2_encode_packets(t2, tileno, tile, tcd_tcp->numlayers, dest, len, volume_info);\r
+        t2_destroy(t2);\r
+       } else if ((cp->encoding_format == ENCOD_2GR)||(cp->encoding_format == ENCOD_3GR)) {\r
+               /*if(volume_info) {\r
+                       volume_info->index_write = 1;\r
+               }\r
+               gr = golomb_create(tcd->cinfo, volume, cp);\r
+               l = golomb_encode(gr, tileno, tile, dest, len, volume_info);\r
+               golomb_destroy(gr);*/\r
+       }\r
+\r
+       \r
+       /*---------------CLEAN-------------------*/\r
+       fprintf(stdout,"[INFO] Tcd_encode_tile: %d bytes coded\n",l);\r
+       encoding_time = opj_clock() - encoding_time;\r
+       opj_event_msg(tcd->cinfo, EVT_INFO, "- tile encoded in %f s\n", encoding_time);\r
+       \r
+       /* cleaning memory */\r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               tcd->tilec = &tile->comps[compno];\r
+               opj_free(tcd->tilec->data);\r
+       }\r
+       \r
+       if (l == -999){\r
+               fprintf(stdout,"[ERROR] Unable to perform T2 tier. Return -999.\n");\r
+               return 0;\r
+       }\r
+\r
+       return l;\r
+}\r
+\r
+\r
+bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno) {\r
+       int l, i;\r
+       int compno, eof = 0;\r
+       double tile_time, t1_time, dwt_time;\r
+\r
+       opj_tcd_tile_t *tile = NULL;\r
+       opj_t2_t *t2 = NULL;            /* T2 component */\r
+       \r
+       tcd->tcd_tileno = tileno;\r
+       tcd->tcd_tile = &(tcd->tcd_volume->tiles[tileno]);\r
+       tcd->tcp = &(tcd->cp->tcps[tileno]);\r
+       tile = tcd->tcd_tile;\r
+       \r
+       tile_time = opj_clock();        /* time needed to decode a tile */\r
+       opj_event_msg(tcd->cinfo, EVT_INFO, "tile %d / %d\n", tileno + 1, tcd->cp->tw * tcd->cp->th * tcd->cp->tl);\r
+\r
+       if ((tcd->cp->encoding_format == ENCOD_2EB) || (tcd->cp->encoding_format == ENCOD_3EB)) {\r
+               /*--------------TIER2------------------*/\r
+               t2 = t2_create(tcd->cinfo, tcd->volume, tcd->cp);\r
+               l = t2_decode_packets(t2, src, len, tileno, tile);\r
+               t2_destroy(t2);\r
+               opj_event_msg(tcd->cinfo, EVT_INFO, "Tcd_decode_tile: %d bytes decoded\n",l);\r
+               \r
+               if (l == -999) {\r
+                       eof = 1;\r
+                       opj_event_msg(tcd->cinfo, EVT_ERROR, "Tcd_decode_tile: incomplete bistream\n");\r
+               }\r
+       \r
+               /*------------------TIER1-----------------*/\r
+               opj_event_msg(tcd->cinfo, EVT_INFO, "Tcd_decode_tile: Entropy decoding %d \n",tcd->cp->encoding_format);\r
+               t1_time = opj_clock();  /* time needed to decode a tile */\r
+               if (tcd->cp->encoding_format == ENCOD_2EB) {\r
+                       opj_t1_t *t1 = NULL;            /* T1 component */\r
+                       t1 = t1_create(tcd->cinfo);\r
+                       t1_decode_cblks(t1, tile, tcd->tcp);\r
+                       t1_destroy(t1);\r
+               }else if (tcd->cp->encoding_format == ENCOD_3EB) {\r
+                       opj_t1_3d_t *t1 = NULL;         /* T1 component */\r
+                       t1 = t1_3d_create(tcd->cinfo);\r
+                       t1_3d_decode_cblks(t1, tile, tcd->tcp);\r
+                       t1_3d_destroy(t1);\r
+               }\r
+\r
+               t1_time = opj_clock() - t1_time;\r
+               #ifdef VERBOSE\r
+                               opj_event_msg(tcd->cinfo, EVT_INFO, "- tier-1 took %f s\n", t1_time);\r
+               #endif\r
+       } else if ((tcd->cp->encoding_format == ENCOD_2GR)||(tcd->cp->encoding_format == ENCOD_3GR)) {\r
+               opj_event_msg(tcd->cinfo, EVT_INFO, "Tcd_decode_tile: Entropy decoding -- Does nothing :-D\n");\r
+               /*\r
+               gr = golomb_create(tcd->cinfo, tcd->volume, tcd->cp);\r
+               l = golomb_decode(gr, tileno, tile, src, len);\r
+               golomb_destroy(gr);\r
+               if (l == -999) {\r
+                       eof = 1;\r
+                       opj_event_msg(tcd->cinfo, EVT_ERROR, "Tcd_decode_tile: incomplete bistream\n");\r
+               }\r
+               */\r
+       } \r
+\r
+       /*----------------DWT---------------------*/\r
+       fprintf(stdout,"[INFO] Tcd_decode_tile: Inverse DWT\n");\r
+       dwt_time = opj_clock(); /* time needed to decode a tile */\r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+               int stops[3], dwtid[3];\r
+       \r
+               for (i = 0; i < 3; i++) {\r
+                       if (tcd->cp->reduce[i] != 0) \r
+                               tcd->volume->comps[compno].resno_decoded[i] = tile->comps[compno].numresolution[i] - tcd->cp->reduce[i] - 1;\r
+                       stops[i] = tilec->numresolution[i] - 1 - tcd->volume->comps[compno].resno_decoded[i];\r
+                       if (stops[i] < 0) stops[i]=0;\r
+                       dwtid[i] = tcd->cp->tcps->tccps[compno].dwtid[i];\r
+               }\r
+               \r
+               dwt_decode(tilec, stops, dwtid);\r
+\r
+               for (i = 0; i < 3; i++) {\r
+                       if (tile->comps[compno].numresolution[i] > 0) {\r
+                               tcd->volume->comps[compno].factor[i] = tile->comps[compno].numresolution[i] - (tcd->volume->comps[compno].resno_decoded[i] + 1);\r
+                               if ( (tcd->volume->comps[compno].factor[i]) < 0 )\r
+                                       tcd->volume->comps[compno].factor[i] = 0;\r
+                       }\r
+               }\r
+       }\r
+       dwt_time = opj_clock() - dwt_time;\r
+       #ifdef VERBOSE\r
+                       opj_event_msg(tcd->cinfo, EVT_INFO, "- dwt took %f s\n", dwt_time);\r
+       #endif\r
+\r
+       /*----------------MCT-------------------*/\r
+       \r
+       if (tcd->tcp->mct) {\r
+               if (tcd->tcp->tccps[0].reversible == 1) {\r
+                       mct_decode(tile->comps[0].data, tile->comps[1].data, tile->comps[2].data, \r
+                               (tile->comps[0].x1 - tile->comps[0].x0) * (tile->comps[0].y1 - tile->comps[0].y0) * (tile->comps[0].z1 - tile->comps[0].z0));\r
+               } else {\r
+                       mct_decode_real(tile->comps[0].data, tile->comps[1].data, tile->comps[2].data, \r
+                               (tile->comps[0].x1 - tile->comps[0].x0) * (tile->comps[0].y1 - tile->comps[0].y0)* (tile->comps[0].z1 - tile->comps[0].z0));\r
+               }\r
+       }\r
+       \r
+       /*---------------TILE-------------------*/\r
+       \r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               opj_tcd_tilecomp_t *tilec = &tile->comps[compno];\r
+               opj_tcd_resolution_t *res =     &tilec->resolutions[tcd->volume->comps[compno].resno_decoded[0]];\r
+               int adjust;\r
+               int minval = tcd->volume->comps[compno].sgnd ? -(1 << (tcd->volume->comps[compno].prec - 1)) : 0;\r
+               int maxval = tcd->volume->comps[compno].sgnd ? (1 << (tcd->volume->comps[compno].prec - 1)) - 1 : (1 << tcd->volume->comps[compno].prec) - 1;\r
+               \r
+               int tw = tilec->x1 - tilec->x0;\r
+               int w = tcd->volume->comps[compno].w;\r
+               int th = tilec->y1 - tilec->y0;\r
+               int h = tcd->volume->comps[compno].h;\r
+\r
+               int i, j, k;\r
+               int offset_x = int_ceildivpow2(tcd->volume->comps[compno].x0, tcd->volume->comps[compno].factor[0]);\r
+               int offset_y = int_ceildivpow2(tcd->volume->comps[compno].y0, tcd->volume->comps[compno].factor[1]);\r
+               int offset_z = int_ceildivpow2(tcd->volume->comps[compno].z0, tcd->volume->comps[compno].factor[2]);\r
+               \r
+               if (tcd->cp->transform_format == TRF_3D_RLS || tcd->cp->transform_format == TRF_3D_LSE) {\r
+                       adjust = 0;\r
+               } else {\r
+            adjust = tcd->volume->comps[compno].sgnd ? 0 : 1 << (tcd->volume->comps[compno].prec - 1); //sign=='+' --> 2^(prec-1)\r
+                       if (tcd->volume->comps[compno].dcoffset != 0){\r
+                               adjust += tcd->volume->comps[compno].dcoffset;\r
+                               fprintf(stdout,"[INFO] DC Offset applied: DCO = %d -> adjust = %d\n",tcd->volume->comps[compno].dcoffset,adjust);\r
+                       }\r
+               }\r
+\r
+               for (k = res->z0; k < res->z1; k++) {\r
+                       for (j = res->y0; j < res->y1; j++) {\r
+                               for (i = res->x0; i < res->x1; i++) {\r
+                                       int v;\r
+                                       float tmp = (float)((tilec->data[i - res->x0 + (j - res->y0) * tw + (k - res->z0) * tw * th]) / 8192.0);\r
+\r
+                                       if (tcd->tcp->tccps[compno].reversible == 1) {\r
+                                               v = tilec->data[i - res->x0 + (j - res->y0) * tw + (k - res->z0) * tw * th];\r
+                                       } else {\r
+                                               int tmp2 = ((int) (floor(fabs(tmp)))) + ((int) floor(fabs(tmp*2))%2);\r
+                                               v = ((tmp < 0) ? -tmp2:tmp2);\r
+                                       }\r
+                                       v += adjust;\r
+                                       \r
+                                       tcd->volume->comps[compno].data[(i - offset_x) + (j - offset_y) * w + (k - offset_z) * w * h] = int_clamp(v, minval, maxval);\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+       \r
+       tile_time = opj_clock() - tile_time;    /* time needed to decode a tile */\r
+       opj_event_msg(tcd->cinfo, EVT_INFO, "- tile decoded in %f s\n", tile_time);\r
+               \r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               opj_free(tcd->tcd_volume->tiles[tileno].comps[compno].data);\r
+               tcd->tcd_volume->tiles[tileno].comps[compno].data = NULL;\r
+       }\r
+       \r
+       if (eof) {\r
+               return false;\r
+       }\r
+       \r
+       return true;\r
+}\r
+\r
diff --git a/src/lib/openjp3d/tcd.h b/src/lib/openjp3d/tcd.h
new file mode 100755 (executable)
index 0000000..52504d1
--- /dev/null
@@ -0,0 +1,334 @@
+/*
+ * 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) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain
+ * 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
+/**
+@file tcd.h
+@brief Implementation of a tile coder/decoder (TCD)
+
+The functions in TCD.C have for goal to encode or decode each tile independently from
+each other. The functions in TCD.C are used by some function in JP3D.C.
+*/
+
+/** @defgroup TCD TCD - Implementation of a tile coder/decoder */
+/*@{*/
+
+/**
+Tile coder/decoder: segment instance
+*/
+typedef struct opj_tcd_seg {
+/** Number of passes in the segment */
+       int numpasses;                  
+/** Length of information */
+    int len;                                   
+/** Data */
+       unsigned char *data;            
+/** Number of passes posible for the segment */
+       int maxpasses;                  
+/** Number of passes added to the segment */
+       int numnewpasses;                   
+/** New length after inclusion of segments */
+       int newlen;
+} opj_tcd_seg_t;
+
+/**
+Tile coder/decoder: pass instance
+*/
+typedef struct opj_tcd_pass {
+/** Rate obtained in the pass*/
+  int rate;                                    
+/** Distorsion obtained in the pass*/
+  double distortiondec;                
+  int term;
+/** Length of information */
+  int len;                                     
+} opj_tcd_pass_t;
+
+/**
+Tile coder/decoder: layer instance
+*/
+typedef struct opj_tcd_layer {
+/** Number of passes in the layer */
+       int numpasses;                  
+/** Length of information */
+  int len;                                     
+/** Distortion within layer */
+  double disto;                                /* add for index (Cfr. Marcela) */
+  unsigned char *data;         /* data */
+} opj_tcd_layer_t;
+
+/**
+Tile coder/decoder: codeblock instance
+*/
+typedef struct opj_tcd_cblk {
+/** Dimension of the code-blocks : left upper corner (x0, y0, z0) */
+  int x0, y0, z0;
+/** Dimension of the code-blocks : right low corner (x1,y1,z1) */
+  int x1, y1, z1;              
+/** Number of bits per simbol in codeblock */
+  int numbps;
+  int numlenbits;
+  int len;                                             /* length */
+/** Number of pass already done for the code-blocks */
+  int numpasses;                               
+/** number of pass added to the code-blocks */
+  int numnewpasses;                            
+/** Number of segments */
+  int numsegs;                                 
+/** Segments informations */
+  opj_tcd_seg_t segs[100];             
+/** Number of passes in the layer */
+  int numpassesinlayers;               
+/** Layer information */
+  opj_tcd_layer_t layers[100]; 
+/** Total number of passes */
+  int totalpasses;                             
+/** Information about the passes */
+  opj_tcd_pass_t passes[100];  
+/* Data */
+  unsigned char data[524288];          
+  //unsigned char *data;
+} opj_tcd_cblk_t;
+
+/**
+Tile coder/decoder: precint instance
+*/
+typedef struct opj_tcd_precinct {
+/** Dimension of the precint : left upper corner (x0, y0, z0) */
+  int x0, y0, z0;
+/** Dimension of the precint : right low corner (x1,y1,z1) */
+  int x1, y1, z1;
+/** Number of codeblocks in precinct in width and heigth and length*/
+  int cblkno[3];                               
+/** Information about the codeblocks */
+  opj_tcd_cblk_t *cblks;               
+/** Inclusion tree */
+  opj_tgt_tree_t *incltree;            
+/** Missing MSBs tree */
+  opj_tgt_tree_t *imsbtree;            
+} opj_tcd_precinct_t;
+
+/**
+Tile coder/decoder: subband instance
+*/
+typedef struct opj_tcd_band {
+/** Dimension of the subband : left upper corner (x0, y0, z0) */
+  int x0, y0, z0;
+/** Dimension of the subband : right low corner (x1,y1,z1) */
+  int x1, y1, z1;
+/** Information about the precints */
+  opj_tcd_precinct_t *precincts;       /* precinct information */
+/** Number of bits per symbol in band */
+  int numbps;
+/** Quantization stepsize associated */
+  float stepsize;
+/** Band orientation (O->LLL,...,7->HHH) */
+  int bandno;
+} opj_tcd_band_t;
+
+/**
+Tile coder/decoder: resolution instance
+*/
+typedef struct opj_tcd_resolution {
+/** Dimension of the resolution level : left upper corner (x0, y0, z0) */
+  int x0, y0, z0;
+/** Dimension of the resolution level : right low corner (x1,y1,z1) */
+  int x1, y1, z1;
+/** Number of precints in each dimension for the resolution level */
+  int prctno[3];                               
+/** Number of subbands for the resolution level */
+  int numbands;                                        
+/** Subband information */
+  opj_tcd_band_t *bands;               
+} opj_tcd_resolution_t;
+
+/**
+Tile coder/decoder: component instance
+*/
+typedef struct opj_tcd_tilecomp {
+/** Dimension of the component : left upper corner (x0, y0, z0) */
+  int x0, y0, z0;
+/** Dimension of the component : right low corner (x1,y1,z1) */
+  int x1, y1, z1;
+/** Number of resolutions level if DWT transform*/
+  int numresolution[3];                                        
+/** Resolution information */
+  opj_tcd_resolution_t *resolutions;   
+/** Data of the component */
+  int *data;                                   
+/** Fixed_quality related */
+  int nbpix;                           
+/** Number of bits per voxel in component */
+  int bpp;
+} opj_tcd_tilecomp_t;
+
+/**
+Tile coder/decoder: tile instance
+*/
+typedef struct opj_tcd_tile {
+/** Dimension of the tile : left upper corner (x0, y0, z0) */
+  int x0, y0, z0;
+/** Dimension of the tile : right low corner (x1,y1,z1) */
+  int x1, y1, z1;
+/** Number of components in tile */
+  int numcomps;                                        
+/** Components information */
+  opj_tcd_tilecomp_t *comps;   
+/** Fixed_quality related : no of bytes of data*/
+  int nbpix;                                   
+/** Fixed_quality related : distortion achieved in tile */
+  double distotile;                            
+/** Fixed_quality related : distortion achieved in each layer */
+  double distolayer[100];              
+} opj_tcd_tile_t;
+
+/**
+Tile coder/decoder: volume instance
+*/
+typedef struct opj_tcd_volume {
+/** Number of tiles in width and heigth and length */
+       int tw, th, tl;                         
+/** Tiles information */
+  opj_tcd_tile_t *tiles;               
+} opj_tcd_volume_t;
+
+/**
+Tile coder/decoder
+*/
+typedef struct opj_tcd {
+/** Codec context */   
+       opj_common_ptr cinfo;                   
+/** Volume information */      
+       opj_volume_t *volume;                   
+/** Coding parameters */       
+       opj_cp_t *cp;                                   
+/** Coding/decoding parameters common to all tiles */  
+       opj_tcp_t *tcp;                                 
+/** Info on each volume tile */
+       opj_tcd_volume_t *tcd_volume;   
+/** Pointer to the current encoded/decoded tile */
+       opj_tcd_tile_t *tcd_tile;               
+/** Current encoded/decoded tile */
+       int tcd_tileno;                                 
+
+       /**@name working variables */
+       /*@{*/
+       opj_tcd_tile_t *tile;
+       opj_tcd_tilecomp_t *tilec;
+       opj_tcd_resolution_t *res;
+       opj_tcd_band_t *band;
+       opj_tcd_precinct_t *prc;
+       opj_tcd_cblk_t *cblk;
+       /*@}*/
+} opj_tcd_t;
+
+/** @name Funciones generales */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+
+/**
+Dump the content of a tcd structure
+*/
+void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_volume_t *img);
+/**
+Create a new TCD handle
+@param cinfo Codec context info
+@return Returns a new TCD handle if successful returns NULL otherwise
+*/
+opj_tcd_t* tcd_create(opj_common_ptr cinfo);
+/**
+Destroy a previously created TCD handle
+@param tcd TCD handle to destroy
+*/
+void tcd_destroy(opj_tcd_t *tcd);
+/**
+Initialize the tile coder (allocate the memory) 
+@param tcd TCD handle
+@param volume Raw volume
+@param cp Coding parameters
+@param curtileno Number that identifies the tile that will be encoded
+*/
+void tcd_malloc_encode(opj_tcd_t *tcd, opj_volume_t * volume, opj_cp_t * cp, int curtileno);
+/**
+Initialize the tile coder (reuses the memory allocated by tcd_malloc_encode)(for 3D-DWT)
+@param tcd TCD handle
+@param volume Raw volume
+@param cp Coding parameters
+@param curtileno Number that identifies the tile that will be encoded
+*/
+void tcd_init_encode(opj_tcd_t *tcd, opj_volume_t * volume, opj_cp_t * cp, int curtileno);
+/**
+Free the memory allocated for encoding
+@param tcd TCD handle
+*/
+void tcd_free_encode(opj_tcd_t *tcd);
+/**
+Initialize the tile decoder
+@param tcd TCD handle
+@param volume Raw volume
+@param cp Coding parameters
+*/
+void tcd_malloc_decode(opj_tcd_t *tcd, opj_volume_t * volume, opj_cp_t * cp);
+
+void tcd_makelayer_fixed(opj_tcd_t *tcd, int layno, int final);
+void tcd_rateallocate_fixed(opj_tcd_t *tcd);
+void tcd_makelayer(opj_tcd_t *tcd, int layno, double thresh, int final);
+bool tcd_rateallocate(opj_tcd_t *tcd, unsigned char *dest, int len, opj_volume_info_t * volume_info);
+/**
+Encode a tile from the raw volume into a buffer
+@param tcd TCD handle
+@param tileno Number that identifies one of the tiles to be encoded
+@param dest Destination buffer
+@param len Length of destination buffer
+@param volume_info Creation of index file
+@return 
+*/
+int tcd_encode_tile(opj_tcd_t *tcd, int tileno, unsigned char *dest, int len, opj_volume_info_t * volume_info);
+/**
+Decode a tile from a buffer into a raw volume
+@param tcd TCD handle
+@param src Source buffer
+@param len Length of source buffer
+@param tileno Number that identifies one of the tiles to be decoded
+*/
+bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno);
+/**
+Free the memory allocated for decoding
+@param tcd TCD handle
+*/
+void tcd_free_decode(opj_tcd_t *tcd);
+
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif /* __TCD_H */
diff --git a/src/lib/openjp3d/tgt.c b/src/lib/openjp3d/tgt.c
new file mode 100755 (executable)
index 0000000..1772afa
--- /dev/null
@@ -0,0 +1,256 @@
+/*\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
+ * 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 "opj_includes.h"\r
+\r
+/* \r
+==========================================================\r
+   Tag-tree coder interface\r
+==========================================================\r
+*/\r
+void tgt_tree_dump (FILE *fd, opj_tgt_tree_t * tree){\r
+       int nodesno;\r
+\r
+       fprintf(fd, "TGT_TREE {\n");\r
+       fprintf(fd, "  numnodes: %d \n", tree->numnodes);       \r
+       fprintf(fd, "  numleafsh: %d, numleafsv: %d, numleafsz: %d,\n", tree->numleafsh, tree->numleafsv, tree->numleafsz);\r
+\r
+       for (nodesno = 0; nodesno < tree->numnodes; nodesno++) {\r
+               fprintf(fd, "tgt_node %d {\n", nodesno);\r
+               fprintf(fd, "  value: %d \n", tree->nodes[nodesno].value);\r
+               fprintf(fd, "  low: %d \n", tree->nodes[nodesno].low);\r
+               fprintf(fd, "  known: %d \n", tree->nodes[nodesno].known);\r
+               if (tree->nodes[nodesno].parent) {\r
+                       fprintf(fd, "  parent.value: %d \n", tree->nodes[nodesno].parent->value);\r
+                       fprintf(fd, "  parent.low: %d \n", tree->nodes[nodesno].parent->low);\r
+                       fprintf(fd, "  parent.known: %d \n", tree->nodes[nodesno].parent->known);\r
+               }\r
+               fprintf(fd, "}\n");\r
+\r
+       }\r
+       fprintf(fd, "}\n");\r
+\r
+}\r
+\r
+\r
+opj_tgt_tree_t *tgt_create(int numleafsh, int numleafsv, int numleafsz) {\r
+       \r
+       int nplh[32];\r
+       int nplv[32];\r
+       int nplz[32];\r
+       opj_tgt_node_t *node = NULL;\r
+       opj_tgt_node_t *parentnode = NULL;\r
+       opj_tgt_node_t *parentnode0 = NULL;\r
+       opj_tgt_tree_t *tree = NULL;\r
+       int i, j, k, p, p0;\r
+       int numlvls;\r
+       int n, z = 0;\r
+\r
+       tree = (opj_tgt_tree_t *) opj_malloc(sizeof(opj_tgt_tree_t));\r
+       if(!tree) \r
+               return NULL;\r
+       tree->numleafsh = numleafsh;\r
+       tree->numleafsv = numleafsv;\r
+       tree->numleafsz = numleafsz;\r
+\r
+       numlvls = 0;\r
+       nplh[0] = numleafsh;\r
+       nplv[0] = numleafsv;\r
+       nplz[0] = numleafsz;\r
+       tree->numnodes = 0;\r
+       do {\r
+               n = nplh[numlvls] * nplv[numlvls] * nplz[numlvls]; \r
+               nplh[numlvls + 1] = (nplh[numlvls] + 1) / 2;\r
+               nplv[numlvls + 1] = (nplv[numlvls] + 1) / 2;\r
+               nplz[numlvls + 1] = (nplz[numlvls] + 1) / 2;\r
+               tree->numnodes += n;\r
+               ++numlvls;\r
+       } while (n > 1);\r
+\r
+       if (tree->numnodes == 0) {\r
+               opj_free(tree);\r
+               return NULL;\r
+       }\r
+\r
+       tree->nodes = (opj_tgt_node_t *) opj_malloc(tree->numnodes * sizeof(opj_tgt_node_t));\r
+       if(!tree->nodes) {\r
+               opj_free(tree);\r
+               return NULL;\r
+       }\r
+\r
+       node = tree->nodes;\r
+       parentnode = &tree->nodes[tree->numleafsh * tree->numleafsv * tree->numleafsz];\r
+       parentnode0 = parentnode;\r
+               \r
+       p = tree->numleafsh * tree->numleafsv * tree->numleafsz;\r
+       p0 = p;\r
+       n = 0;\r
+       //fprintf(stdout,"\nH %d V %d Z %d numlvls %d nodes %d\n",tree->numleafsh,tree->numleafsv,tree->numleafsz,numlvls,tree->numnodes);\r
+       for (i = 0; i < numlvls - 1; ++i) {\r
+               for (j = 0; j < nplv[i]; ++j) {\r
+                       k = nplh[i]*nplz[i];\r
+                       while (--k >= 0) {\r
+                               node->parent = parentnode;              //fprintf(stdout,"node[%d].parent = node[%d]\n",n,p);\r
+                               ++node; ++n;            \r
+                               if (--k >= 0 && n < p) {\r
+                                       node->parent = parentnode;      //fprintf(stdout,"node[%d].parent = node[%d]\n",n,p);\r
+                                       ++node; ++n;    \r
+                               }\r
+                               if (nplz[i] != 1){ //2D operation vs 3D operation\r
+                                       if (--k >= 0 && n < p) {\r
+                                               node->parent = parentnode;      //fprintf(stdout,"node[%d].parent = node[%d]\n",n,p);\r
+                                               ++node; ++n;\r
+                                       }\r
+                                       if (--k >= 0 && n < p) {\r
+                                               node->parent = parentnode;      //fprintf(stdout,"node[%d].parent = node[%d]\n",n,p);\r
+                                               ++node; ++n;\r
+                                       }\r
+                               }\r
+                               ++parentnode; ++p;\r
+                       }\r
+                       if ((j & 1) || j == nplv[i] - 1) {\r
+                               parentnode0 = parentnode;                       p0 = p;         //fprintf(stdout,"parent = node[%d] \n",p);\r
+                       } else {\r
+                               parentnode = parentnode0;                       p = p0;         //fprintf(stdout,"parent = node[%d] \n",p);\r
+                               parentnode0 += nplh[i]*nplz[i];         p0 += nplh[i]*nplz[i];\r
+                       }\r
+               }\r
+       }\r
+       node->parent = 0;\r
+\r
+       \r
+       tgt_reset(tree);\r
+\r
+       return tree;\r
+}\r
+\r
+void tgt_destroy(opj_tgt_tree_t *tree) {\r
+       opj_free(tree->nodes);\r
+       opj_free(tree);\r
+}\r
+\r
+void tgt_reset(opj_tgt_tree_t *tree) {\r
+       int i;\r
+\r
+       if (NULL == tree)\r
+               return;\r
+       \r
+       for (i = 0; i < tree->numnodes; i++) {\r
+               tree->nodes[i].value = 999;\r
+               tree->nodes[i].low = 0;\r
+               tree->nodes[i].known = 0;\r
+       }\r
+}\r
+\r
+void tgt_setvalue(opj_tgt_tree_t *tree, int leafno, int value) {\r
+       opj_tgt_node_t *node;\r
+       node = &tree->nodes[leafno];\r
+       while (node && node->value > value) {\r
+               node->value = value;\r
+               node = node->parent;\r
+       }\r
+}\r
+\r
+void tgt_encode(opj_bio_t *bio, opj_tgt_tree_t *tree, int leafno, int threshold) {\r
+       opj_tgt_node_t *stk[31];\r
+       opj_tgt_node_t **stkptr;\r
+       opj_tgt_node_t *node;\r
+       int low;\r
+\r
+       stkptr = stk;\r
+       node = &tree->nodes[leafno];\r
+       while (node->parent) {\r
+               *stkptr++ = node;\r
+               node = node->parent;\r
+       }\r
+       \r
+       low = 0;\r
+       for (;;) {\r
+               if (low > node->low) {\r
+                       node->low = low;\r
+               } else {\r
+                       low = node->low;\r
+               }\r
+               \r
+               while (low < threshold) {\r
+                       if (low >= node->value) {\r
+                               if (!node->known) {\r
+                                       bio_write(bio, 1, 1);\r
+                                       node->known = 1;\r
+                               }\r
+                               break;\r
+                       }\r
+                       bio_write(bio, 0, 1);\r
+                       ++low;\r
+               }\r
+               \r
+               node->low = low;\r
+               if (stkptr == stk)\r
+                       break;\r
+               node = *--stkptr;\r
+       }\r
+}\r
+\r
+int tgt_decode(opj_bio_t *bio, opj_tgt_tree_t *tree, int leafno, int threshold) {\r
+       opj_tgt_node_t *stk[31];\r
+       opj_tgt_node_t **stkptr;\r
+       opj_tgt_node_t *node;\r
+       int low;\r
+\r
+       stkptr = stk;\r
+       node = &tree->nodes[leafno];\r
+       while (node->parent) {\r
+               *stkptr++ = node;\r
+               node = node->parent;\r
+       }\r
+       \r
+       low = 0;\r
+       for (;;) {\r
+               if (low > node->low) {\r
+                       node->low = low;\r
+               } else {\r
+                       low = node->low;\r
+               }\r
+               while (low < threshold && low < node->value) {\r
+                       if (bio_read(bio, 1)) {\r
+                               node->value = low;\r
+                       } else {\r
+                               ++low;\r
+                       }\r
+               }\r
+               node->low = low;\r
+               if (stkptr == stk) {\r
+                       break;\r
+               }\r
+               node = *--stkptr;\r
+       }\r
+       \r
+       return (node->value < threshold) ? 1 : 0;\r
+}\r
diff --git a/src/lib/openjp3d/tgt.h b/src/lib/openjp3d/tgt.h
new file mode 100755 (executable)
index 0000000..ad8e88d
--- /dev/null
@@ -0,0 +1,124 @@
+/*\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
+ * 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 __TGT_H\r
+#define __TGT_H\r
+/**\r
+@file tgt.h\r
+@brief Implementation of a tag-tree coder (TGT)\r
+\r
+The functions in TGT.C have for goal to realize a tag-tree coder. The functions in TGT.C\r
+are used by some function in T2.C.\r
+*/\r
+\r
+/** @defgroup TGT TGT - Implementation of a tag-tree coder */\r
+/*@{*/\r
+\r
+/**\r
+Tag node\r
+*/\r
+typedef struct opj_tgt_node {\r
+/** Node parent reference */\r
+  struct opj_tgt_node *parent;\r
+/**  */\r
+  int value;\r
+/**  */\r
+  int low;\r
+/**  */\r
+  int known;\r
+} opj_tgt_node_t;\r
+\r
+/**\r
+Tag tree\r
+*/\r
+typedef struct opj_tgt_tree {\r
+/** Number of leaves from horizontal axis */\r
+  int numleafsh;\r
+/** Number of leaves from vertical axis */\r
+  int numleafsv;\r
+/** Number of leaves from axial axis */\r
+  int numleafsz;\r
+/** Number of nodes */\r
+  int numnodes;\r
+/** Reference to each node instance */\r
+  opj_tgt_node_t *nodes;\r
+} opj_tgt_tree_t;\r
+\r
+/** @name Funciones generales */\r
+/*@{*/\r
+/* ----------------------------------------------------------------------- */\r
+/**\r
+Create a tag-tree\r
+@param numleafsh Width of the array of leafs of the tree\r
+@param numleafsv Height of the array of leafs of the tree\r
+@param numleafsz Depth of the array of leafs of the tree\r
+@return Returns a new tag-tree if successful, returns NULL otherwise\r
+*/\r
+opj_tgt_tree_t *tgt_create(int numleafsh, int numleafsv, int numleafsz);\r
+/**\r
+Destroy a tag-tree, liberating memory\r
+@param tree Tag-tree to destroy\r
+*/\r
+void tgt_destroy(opj_tgt_tree_t *tree);\r
+/**\r
+Reset a tag-tree (set all leaves to 0)\r
+@param tree Tag-tree to reset\r
+*/\r
+void tgt_reset(opj_tgt_tree_t *tree);\r
+/**\r
+Set the value of a leaf of a tag-tree\r
+@param tree Tag-tree to modify\r
+@param leafno Number that identifies the leaf to modify\r
+@param value New value of the leaf\r
+*/\r
+void tgt_setvalue(opj_tgt_tree_t *tree, int leafno, int value);\r
+/**\r
+Encode the value of a leaf of the tag-tree up to a given threshold\r
+@param bio Pointer to a BIO handle\r
+@param tree Tag-tree to modify\r
+@param leafno Number that identifies the leaf to encode\r
+@param threshold Threshold to use when encoding value of the leaf\r
+*/\r
+void tgt_encode(opj_bio_t *bio, opj_tgt_tree_t *tree, int leafno, int threshold);\r
+/**\r
+Decode the value of a leaf of the tag-tree up to a given threshold\r
+@param bio Pointer to a BIO handle\r
+@param tree Tag-tree to decode\r
+@param leafno Number that identifies the leaf to decode\r
+@param threshold Threshold to use when decoding value of the leaf\r
+@return Returns 1 if the node's value < threshold, returns 0 otherwise\r
+*/\r
+int tgt_decode(opj_bio_t *bio, opj_tgt_tree_t *tree, int leafno, int threshold);\r
+\r
+/*@}*/\r
+/* ----------------------------------------------------------------------- */\r
+void tgt_tree_dump (FILE *fd, opj_tgt_tree_t * tree);\r
+\r
+#endif /* __TGT_H */\r
diff --git a/src/lib/openjp3d/volume.c b/src/lib/openjp3d/volume.c
new file mode 100755 (executable)
index 0000000..35728da
--- /dev/null
@@ -0,0 +1,89 @@
+/*\r
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team\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 "opj_includes.h"\r
+\r
+opj_volume_t* OPJ_CALLCONV opj_volume_create(int numcmpts, opj_volume_cmptparm_t *cmptparms, OPJ_COLOR_SPACE clrspc) {\r
+       int compno;\r
+       opj_volume_t *volume = NULL;\r
+\r
+       volume = (opj_volume_t*)opj_malloc(sizeof(opj_volume_t));\r
+       if(volume) {\r
+               volume->color_space = clrspc;\r
+               volume->numcomps = numcmpts;\r
+               /* allocate memory for the per-component information */\r
+               volume->comps = (opj_volume_comp_t*)opj_malloc(volume->numcomps * sizeof(opj_volume_comp_t));\r
+               if(!volume->comps) {\r
+                       opj_volume_destroy(volume);\r
+                       return NULL;\r
+               }\r
+               /* create the individual volume components */\r
+               for(compno = 0; compno < numcmpts; compno++) {\r
+                       opj_volume_comp_t *comp = &volume->comps[compno];\r
+                       comp->dx = cmptparms[compno].dx;\r
+                       comp->dy = cmptparms[compno].dy;\r
+                       comp->dz = cmptparms[compno].dz;\r
+                       comp->w = cmptparms[compno].w;\r
+                       comp->h = cmptparms[compno].h;\r
+                       comp->l = cmptparms[compno].l;\r
+                       comp->x0 = cmptparms[compno].x0;\r
+                       comp->y0 = cmptparms[compno].y0;\r
+                       comp->z0 = cmptparms[compno].z0;\r
+                       comp->prec = cmptparms[compno].prec;\r
+                       comp->bpp = cmptparms[compno].bpp;\r
+                       comp->sgnd = cmptparms[compno].sgnd;\r
+                       comp->bigendian = cmptparms[compno].bigendian;\r
+                       comp->dcoffset = cmptparms[compno].dcoffset;\r
+                       comp->data = (int*)opj_malloc(comp->w * comp->h * comp->l * sizeof(int));\r
+                       if(!comp->data) {\r
+                               fprintf(stdout,"Unable to malloc comp->data (%d x %d x %d x bytes)",comp->w,comp->h,comp->l);\r
+                               opj_volume_destroy(volume);\r
+                               return NULL;\r
+                       }\r
+                       //fprintf(stdout,"%d %d %d %d %d %d %d %d %d", comp->w,comp->h, comp->l, comp->dx, comp->dy, comp->dz, comp->prec, comp->bpp, comp->sgnd);\r
+               }\r
+       }\r
+\r
+       return volume;\r
+}\r
+\r
+void OPJ_CALLCONV opj_volume_destroy(opj_volume_t *volume) {\r
+       int i;\r
+       if(volume) {\r
+               if(volume->comps) {\r
+                       /* volume components */\r
+                       for(i = 0; i < volume->numcomps; i++) {\r
+                               opj_volume_comp_t *volume_comp = &volume->comps[i];\r
+                               if(volume_comp->data) {\r
+                                       opj_free(volume_comp->data);\r
+                               }\r
+                       }\r
+                       opj_free(volume->comps);\r
+               }\r
+               opj_free(volume);\r
+       }\r
+}\r
+\r
diff --git a/src/lib/openjp3d/volume.h b/src/lib/openjp3d/volume.h
new file mode 100755 (executable)
index 0000000..02f28d2
--- /dev/null
@@ -0,0 +1,43 @@
+/*\r
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team\r
+ * Copyright (c) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain\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
+#ifndef __VOLUME_H\r
+#define __VOLUME_H\r
+/**\r
+@file volume.h\r
+@brief Implementation of operations on volumes (VOLUME)\r
+\r
+The functions in VOLUME.C have for goal to realize operations on volumes.\r
+*/\r
+\r
+/** @defgroup VOLUME VOLUME - Implementation of operations on volumes */\r
+/*@{*/\r
+\r
+\r
+/*@}*/\r
+\r
+#endif /* __VOLUME_H */\r
+\r