Merged from trunk
authorIan Thompson <quornian@googlemail.com>
Mon, 9 Jun 2008 14:04:19 +0000 (14:04 +0000)
committerIan Thompson <quornian@googlemail.com>
Mon, 9 Jun 2008 14:04:19 +0000 (14:04 +0000)
svn merge -r14988:15170 https://svn.blender.org/svnroot/bf-blender/trunk/blender

150 files changed:
config/linux2-config.py
config/win32-vc-config.py
extern/SConscript
extern/bFTGL/SConscript
extern/libopenjpeg/SConscript [new file with mode: 0644]
extern/libopenjpeg/bio.c [new file with mode: 0644]
extern/libopenjpeg/bio.h [new file with mode: 0644]
extern/libopenjpeg/cio.c [new file with mode: 0644]
extern/libopenjpeg/cio.h [new file with mode: 0644]
extern/libopenjpeg/dwt.c [new file with mode: 0644]
extern/libopenjpeg/dwt.h [new file with mode: 0644]
extern/libopenjpeg/event.c [new file with mode: 0644]
extern/libopenjpeg/event.h [new file with mode: 0644]
extern/libopenjpeg/fix.h [new file with mode: 0644]
extern/libopenjpeg/image.c [new file with mode: 0644]
extern/libopenjpeg/image.h [new file with mode: 0644]
extern/libopenjpeg/int.h [new file with mode: 0644]
extern/libopenjpeg/j2k.c [new file with mode: 0644]
extern/libopenjpeg/j2k.h [new file with mode: 0644]
extern/libopenjpeg/j2k_lib.c [new file with mode: 0644]
extern/libopenjpeg/j2k_lib.h [new file with mode: 0644]
extern/libopenjpeg/jp2.c [new file with mode: 0644]
extern/libopenjpeg/jp2.h [new file with mode: 0644]
extern/libopenjpeg/jpt.c [new file with mode: 0644]
extern/libopenjpeg/jpt.h [new file with mode: 0644]
extern/libopenjpeg/license.txt [new file with mode: 0644]
extern/libopenjpeg/mct.c [new file with mode: 0644]
extern/libopenjpeg/mct.h [new file with mode: 0644]
extern/libopenjpeg/mqc.c [new file with mode: 0644]
extern/libopenjpeg/mqc.h [new file with mode: 0644]
extern/libopenjpeg/openjpeg.c [new file with mode: 0644]
extern/libopenjpeg/openjpeg.h [new file with mode: 0644]
extern/libopenjpeg/opj_includes.h [new file with mode: 0644]
extern/libopenjpeg/opj_malloc.h [new file with mode: 0644]
extern/libopenjpeg/pi.c [new file with mode: 0644]
extern/libopenjpeg/pi.h [new file with mode: 0644]
extern/libopenjpeg/raw.c [new file with mode: 0644]
extern/libopenjpeg/raw.h [new file with mode: 0644]
extern/libopenjpeg/t1.c [new file with mode: 0644]
extern/libopenjpeg/t1.h [new file with mode: 0644]
extern/libopenjpeg/t1_generate_luts.c [new file with mode: 0644]
extern/libopenjpeg/t1_luts.h [new file with mode: 0644]
extern/libopenjpeg/t2.c [new file with mode: 0644]
extern/libopenjpeg/t2.h [new file with mode: 0644]
extern/libopenjpeg/tcd.c [new file with mode: 0644]
extern/libopenjpeg/tcd.h [new file with mode: 0644]
extern/libopenjpeg/tgt.c [new file with mode: 0644]
extern/libopenjpeg/tgt.h [new file with mode: 0644]
extern/libredcode/AUTHOR [new file with mode: 0644]
extern/libredcode/LICENSE [new file with mode: 0644]
extern/libredcode/NOTES [new file with mode: 0644]
extern/libredcode/SConscript [new file with mode: 0644]
extern/libredcode/codec.c [new file with mode: 0644]
extern/libredcode/codec.h [new file with mode: 0644]
extern/libredcode/debayer.c [new file with mode: 0644]
extern/libredcode/debayer.h [new file with mode: 0644]
extern/libredcode/format.c [new file with mode: 0644]
extern/libredcode/format.h [new file with mode: 0644]
intern/bsp/SConscript
intern/guardedalloc/intern/mmap_win.c
release/scripts/import_dxf.py
release/scripts/uv_from_adjacent.py [deleted file]
release/scripts/uv_seams_from_islands.py
release/scripts/uvcalc_lightmap.py
release/windows/installer/00.sconsblender.nsi
source/blender/blenkernel/BKE_bmesh.h
source/blender/blenkernel/BKE_bmeshCustomData.h [new file with mode: 0644]
source/blender/blenkernel/BKE_cloth.h
source/blender/blenkernel/BKE_collision.h
source/blender/blenkernel/intern/BME_Customdata.c [new file with mode: 0644]
source/blender/blenkernel/intern/BME_conversions.c
source/blender/blenkernel/intern/BME_mesh.c
source/blender/blenkernel/intern/BME_structure.c
source/blender/blenkernel/intern/BME_tools.c
source/blender/blenkernel/intern/bmesh_private.h
source/blender/blenkernel/intern/cloth.c
source/blender/blenkernel/intern/collision.c
source/blender/blenkernel/intern/constraint.c
source/blender/blenkernel/intern/customdata.c
source/blender/blenkernel/intern/kdop.c [deleted file]
source/blender/blenkernel/intern/modifier.c
source/blender/blenkernel/intern/object.c
source/blender/blenkernel/intern/pointcache.c
source/blender/blenkernel/intern/writeffmpeg.c
source/blender/blenlib/BLI_kdopbvh.h [new file with mode: 0644]
source/blender/blenlib/intern/BLI_kdopbvh.c [new file with mode: 0644]
source/blender/blenlib/intern/bpath.c
source/blender/blenlib/intern/util.c
source/blender/blenloader/intern/readfile.c
source/blender/imbuf/SConscript
source/blender/imbuf/intern/IMB_anim.h
source/blender/imbuf/intern/anim.c
source/blender/imbuf/intern/util.c
source/blender/include/BIF_editseq.h
source/blender/include/BSE_view.h
source/blender/include/transform.h
source/blender/makesdna/DNA_modifier_types.h
source/blender/makesdna/DNA_scene_types.h
source/blender/makesdna/intern/makesdna.c
source/blender/python/BPY_interface.c
source/blender/python/api2_2x/Blender.c
source/blender/python/api2_2x/Draw.c
source/blender/python/api2_2x/Material.c
source/blender/python/api2_2x/Node.c
source/blender/python/api2_2x/Object.c
source/blender/python/api2_2x/Particle.c
source/blender/python/api2_2x/Scene.c
source/blender/python/api2_2x/Sys.c
source/blender/python/api2_2x/doc/Object.py
source/blender/python/api2_2x/sceneRender.c
source/blender/render/extern/include/RE_pipeline.h
source/blender/render/extern/include/RE_raytrace.h
source/blender/render/intern/include/render_types.h
source/blender/render/intern/source/convertblender.c
source/blender/render/intern/source/envmap.c
source/blender/render/intern/source/pipeline.c
source/blender/render/intern/source/rayshade.c
source/blender/render/intern/source/rendercore.c
source/blender/src/buttons_editing.c
source/blender/src/buttons_object.c
source/blender/src/buttons_scene.c
source/blender/src/drawipo.c
source/blender/src/drawobject.c
source/blender/src/drawseq.c
source/blender/src/drawview.c
source/blender/src/editaction.c
source/blender/src/editarmature.c
source/blender/src/editmesh_tools.c
source/blender/src/editnode.c
source/blender/src/editseq.c
source/blender/src/filesel.c
source/blender/src/fluidsim.c
source/blender/src/interface.c
source/blender/src/meshtools.c
source/blender/src/space.c
source/blender/src/toets.c
source/blender/src/transform.c
source/blender/src/transform_conversions.c
source/blender/src/transform_manipulator.c
source/blender/src/transform_orientations.c
source/blender/src/view.c
source/creator/creator.c
source/gameengine/Converter/BL_ArmatureObject.cpp
source/gameengine/Ketsji/KX_GameObject.cpp
source/gameengine/Ketsji/KX_GameObject.h
source/gameengine/Ketsji/KX_RayCast.cpp
source/gameengine/PyDoc/KX_GameObject.py
source/gameengine/Rasterizer/RAS_2DFilterManager.cpp
source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_GLExtensionManager.h
tools/btools.py

index 4d8b5c97512862b65233319a26aa52262dba0f90..6bde0664fe598475cc2e4f3a984037a1f9f3c577 100644 (file)
@@ -130,6 +130,24 @@ BF_FFMPEG_LIB = ''
 BF_FFMPEG_INC = '${BF_FFMPEG}/include'
 BF_FFMPEG_LIBPATH='${BF_FFMPEG}/lib'
 
+WITH_BF_OPENJPEG = 'true' 
+BF_OPENJPEG = '#extern/libopenjpeg'
+BF_OPENJPEG_LIB = ''
+# Uncomment the following two lines to use system's ffmpeg
+# BF_FFMPEG = '/usr'
+# BF_FFMPEG_LIB = 'avformat avcodec swscale avutil'
+BF_OPENJPEG_INC = '${BF_OPENJPEG}/include'
+BF_OPENJPEG_LIBPATH='${BF_OPENJPEG}/lib'
+
+WITH_BF_REDCODE = 'true'  
+BF_REDCODE = '#extern/libredcode'
+BF_REDCODE_LIB = ''
+# Uncomment the following two lines to use system's ffmpeg
+# BF_FFMPEG = '/usr'
+# BF_FFMPEG_LIB = 'avformat avcodec swscale avutil'
+BF_REDCODE_INC = '${BF_REDCODE}/include'
+BF_REDCODE_LIBPATH='${BF_REDCODE}/lib'
+
 # Mesa Libs should go here if your using them as well....
 WITH_BF_STATICOPENGL = 'false'
 BF_OPENGL = '/usr'
index 32b6597b5d55eda149f52615642cd376808585cf..02e5dbb7f8fa5438630388b93bdeac3c55ef9c81 100644 (file)
@@ -157,7 +157,7 @@ REL_CCFLAGS = ['-O2', '-DNDEBUG']
 C_WARN = []
 CC_WARN = []
 
-LLIBS = 'ws2_32 vfw32 winmm kernel32 user32 gdi32 comdlg32 advapi32 shell32 ole32 oleaut32 uuid'
+LLIBS = 'ws2_32 vfw32 winmm kernel32 user32 gdi32 comdlg32 advapi32 shfolder shell32 ole32 oleaut32 uuid'
 
 PLATFORM_LINKFLAGS = '''
                         /SUBSYSTEM:CONSOLE 
index 09eaf080c28df948aafe1010232a82b4976ac4a2..c94b6573eb97340c0ab94876f0ff23b7aee1484b 100644 (file)
@@ -21,5 +21,11 @@ if env['WITH_BF_FFMPEG'] and env['BF_FFMPEG_LIB'] == '':
     SConscript(['xvidcore/SConscript'])
     SConscript(['ffmpeg/SConscript'])
 
+if env['WITH_BF_OPENJPEG'] and env['BF_OPENJPEG_LIB'] == '':
+    SConscript(['libopenjpeg/SConscript'])
+
+if env['WITH_BF_REDCODE'] and env['BF_REDCODE_LIB'] == '':
+    SConscript(['libredcode/SConscript'])
+
 if env['OURPLATFORM'] == 'linux2':
     SConscript(['binreloc/SConscript']);
index bd20db5a459674fae3170a3b50a0ba5bf711c5a8..c03992631e6913f93b11e1a1e307a3bdff087989 100644 (file)
@@ -22,7 +22,7 @@ Import('env')
 
 #ftgl_env.Append (CPPDEFINES = defines)
 
-incs = 'include src ' + env['BF_FREETYPE_INC']
+incs = 'include src ' + env['BF_FREETYPE_INC'] + ' ' + env['BF_OPENGL_INC']
 defs = ''
 
 sources = env.Glob('src/*.cpp')
diff --git a/extern/libopenjpeg/SConscript b/extern/libopenjpeg/SConscript
new file mode 100644 (file)
index 0000000..f0a93f6
--- /dev/null
@@ -0,0 +1,20 @@
+#!/usr/bin/python
+
+import sys
+
+Import('env')
+
+sources = env.Glob('*.c')
+incs = '.'
+
+flags = "-Wall -O3 -ffast-math -std=c99"
+
+oj_env = env.Copy();
+oj_env.Replace(CCFLAGS = '')
+oj_env.Replace(BF_DEBUG_FLAGS = '')
+
+oj_env.BlenderLib ( libname='extern_openjpeg', 
+                    sources=sources, includes=Split(incs),
+                    defines=[],
+                    libtype=['core','intern','player'],
+                    priority=[10, 10, 300], compileflags = Split(flags))
diff --git a/extern/libopenjpeg/bio.c b/extern/libopenjpeg/bio.c
new file mode 100644 (file)
index 0000000..4c02f46
--- /dev/null
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "opj_includes.h"
+
+/** @defgroup BIO BIO - Individual bit input-output stream */
+/*@{*/
+
+/** @name Local static functions */
+/*@{*/
+
+/**
+Write a bit
+@param bio BIO handle
+@param b Bit to write (0 or 1)
+*/
+static void bio_putbit(opj_bio_t *bio, int b);
+/**
+Read a bit
+@param bio BIO handle
+@return Returns the read bit
+*/
+static int bio_getbit(opj_bio_t *bio);
+/**
+Write a byte
+@param bio BIO handle
+@return Returns 0 if successful, returns 1 otherwise
+*/
+static int bio_byteout(opj_bio_t *bio);
+/**
+Read a byte
+@param bio BIO handle
+@return Returns 0 if successful, returns 1 otherwise
+*/
+static int bio_bytein(opj_bio_t *bio);
+
+/*@}*/
+
+/*@}*/
+
+/* 
+==========================================================
+   local functions
+==========================================================
+*/
+
+static int bio_byteout(opj_bio_t *bio) {
+       bio->buf = (bio->buf << 8) & 0xffff;
+       bio->ct = bio->buf == 0xff00 ? 7 : 8;
+       if (bio->bp >= bio->end) {
+               return 1;
+       }
+       *bio->bp++ = bio->buf >> 8;
+       return 0;
+}
+
+static int bio_bytein(opj_bio_t *bio) {
+       bio->buf = (bio->buf << 8) & 0xffff;
+       bio->ct = bio->buf == 0xff00 ? 7 : 8;
+       if (bio->bp >= bio->end) {
+               return 1;
+       }
+       bio->buf |= *bio->bp++;
+       return 0;
+}
+
+static void bio_putbit(opj_bio_t *bio, int b) {
+       if (bio->ct == 0) {
+               bio_byteout(bio);
+       }
+       bio->ct--;
+       bio->buf |= b << bio->ct;
+}
+
+static int bio_getbit(opj_bio_t *bio) {
+       if (bio->ct == 0) {
+               bio_bytein(bio);
+       }
+       bio->ct--;
+       return (bio->buf >> bio->ct) & 1;
+}
+
+/* 
+==========================================================
+   Bit Input/Output interface
+==========================================================
+*/
+
+opj_bio_t* bio_create(void) {
+       opj_bio_t *bio = (opj_bio_t*)opj_malloc(sizeof(opj_bio_t));
+       return bio;
+}
+
+void bio_destroy(opj_bio_t *bio) {
+       if(bio) {
+               opj_free(bio);
+       }
+}
+
+int bio_numbytes(opj_bio_t *bio) {
+       return (bio->bp - bio->start);
+}
+
+void bio_init_enc(opj_bio_t *bio, unsigned char *bp, int len) {
+       bio->start = bp;
+       bio->end = bp + len;
+       bio->bp = bp;
+       bio->buf = 0;
+       bio->ct = 8;
+}
+
+void bio_init_dec(opj_bio_t *bio, unsigned char *bp, int len) {
+       bio->start = bp;
+       bio->end = bp + len;
+       bio->bp = bp;
+       bio->buf = 0;
+       bio->ct = 0;
+}
+
+void bio_write(opj_bio_t *bio, int v, int n) {
+       int i;
+       for (i = n - 1; i >= 0; i--) {
+               bio_putbit(bio, (v >> i) & 1);
+       }
+}
+
+int bio_read(opj_bio_t *bio, int n) {
+       int i, v;
+       v = 0;
+       for (i = n - 1; i >= 0; i--) {
+               v += bio_getbit(bio) << i;
+       }
+       return v;
+}
+
+int bio_flush(opj_bio_t *bio) {
+       bio->ct = 0;
+       if (bio_byteout(bio)) {
+               return 1;
+       }
+       if (bio->ct == 7) {
+               bio->ct = 0;
+               if (bio_byteout(bio)) {
+                       return 1;
+               }
+       }
+       return 0;
+}
+
+int bio_inalign(opj_bio_t *bio) {
+       bio->ct = 0;
+       if ((bio->buf & 0xff) == 0xff) {
+               if (bio_bytein(bio)) {
+                       return 1;
+               }
+               bio->ct = 0;
+       }
+       return 0;
+}
diff --git a/extern/libopenjpeg/bio.h b/extern/libopenjpeg/bio.h
new file mode 100644 (file)
index 0000000..764d7cb
--- /dev/null
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __BIO_H
+#define __BIO_H
+/** 
+@file bio.h
+@brief Implementation of an individual bit input-output (BIO)
+
+The functions in BIO.C have for goal to realize an individual bit input - output.
+*/
+
+/** @defgroup BIO BIO - Individual bit input-output stream */
+/*@{*/
+
+/**
+Individual bit input-output stream (BIO)
+*/
+typedef struct opj_bio {
+       /** pointer to the start of the buffer */
+       unsigned char *start;
+       /** pointer to the end of the buffer */
+       unsigned char *end;
+       /** pointer to the present position in the buffer */
+       unsigned char *bp;
+       /** temporary place where each byte is read or written */
+       unsigned int buf;
+       /** coder : number of bits free to write. decoder : number of bits read */
+       int ct;
+} opj_bio_t;
+
+/** @name Exported functions */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+/**
+Create a new BIO handle 
+@return Returns a new BIO handle if successful, returns NULL otherwise
+*/
+opj_bio_t* bio_create(void);
+/**
+Destroy a previously created BIO handle
+@param bio BIO handle to destroy
+*/
+void bio_destroy(opj_bio_t *bio);
+/**
+Number of bytes written.
+@param bio BIO handle
+@return Returns the number of bytes written
+*/
+int bio_numbytes(opj_bio_t *bio);
+/**
+Init encoder
+@param bio BIO handle
+@param bp Output buffer
+@param len Output buffer length 
+*/
+void bio_init_enc(opj_bio_t *bio, unsigned char *bp, int len);
+/**
+Init decoder
+@param bio BIO handle
+@param bp Input buffer
+@param len Input buffer length 
+*/
+void bio_init_dec(opj_bio_t *bio, unsigned char *bp, int len);
+/**
+Write bits
+@param bio BIO handle
+@param v Value of bits
+@param n Number of bits to write
+*/
+void bio_write(opj_bio_t *bio, int v, int n);
+/**
+Read bits
+@param bio BIO handle
+@param n Number of bits to read 
+@return Returns the corresponding read number
+*/
+int bio_read(opj_bio_t *bio, int n);
+/**
+Flush bits
+@param bio BIO handle
+@return Returns 1 if successful, returns 0 otherwise
+*/
+int bio_flush(opj_bio_t *bio);
+/**
+Passes the ending bits (coming from flushing)
+@param bio BIO handle
+@return Returns 1 if successful, returns 0 otherwise
+*/
+int bio_inalign(opj_bio_t *bio);
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif /* __BIO_H */
+
diff --git a/extern/libopenjpeg/cio.c b/extern/libopenjpeg/cio.c
new file mode 100644 (file)
index 0000000..2ac262a
--- /dev/null
@@ -0,0 +1,191 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "opj_includes.h"
+
+/* ----------------------------------------------------------------------- */
+
+opj_cio_t* OPJ_CALLCONV opj_cio_open(opj_common_ptr cinfo, unsigned char *buffer, int length) {
+       opj_cp_t *cp = NULL;
+       opj_cio_t *cio = (opj_cio_t*)opj_malloc(sizeof(opj_cio_t));
+       if(!cio) return NULL;
+       cio->cinfo = cinfo;
+       if(buffer && length) {
+               /* wrap a user buffer containing the encoded image */
+               cio->openmode = OPJ_STREAM_READ;
+               cio->buffer = buffer;
+               cio->length = length;
+       }
+       else if(!buffer && !length && cinfo) {
+               /* allocate a buffer for the encoded image */
+               cio->openmode = OPJ_STREAM_WRITE;
+               switch(cinfo->codec_format) {
+                       case CODEC_J2K:
+                               cp = ((opj_j2k_t*)cinfo->j2k_handle)->cp;
+                               break;
+                       case CODEC_JP2:
+                               cp = ((opj_jp2_t*)cinfo->jp2_handle)->j2k->cp;
+                               break;
+                       default:
+                               opj_free(cio);
+                               return NULL;
+               }
+               cio->length = (unsigned int) (0.1625 * cp->img_size + 2000); /* 0.1625 = 1.3/8 and 2000 bytes as a minimum for headers */
+               cio->buffer = (unsigned char *)opj_malloc(cio->length);
+               if(!cio->buffer) {
+                       opj_event_msg(cio->cinfo, EVT_ERROR, "Error allocating memory for compressed bitstream\n");
+                       opj_free(cio);
+                       return NULL;
+               }
+       }
+       else {
+               opj_free(cio);
+               return NULL;
+       }
+
+       /* Initialize byte IO */
+       cio->start = cio->buffer;
+       cio->end = cio->buffer + cio->length;
+       cio->bp = cio->buffer;
+
+       return cio;
+}
+
+void OPJ_CALLCONV opj_cio_close(opj_cio_t *cio) {
+       if(cio) {
+               if(cio->openmode == OPJ_STREAM_WRITE) {
+                       /* destroy the allocated buffer */
+                       opj_free(cio->buffer);
+               }
+               /* destroy the cio */
+               opj_free(cio);
+       }
+}
+
+
+/* ----------------------------------------------------------------------- */
+
+/*
+ * Get position in byte stream.
+ */
+int OPJ_CALLCONV cio_tell(opj_cio_t *cio) {
+       return cio->bp - cio->start;
+}
+
+/*
+ * Set position in byte stream.
+ *
+ * pos : position, in number of bytes, from the beginning of the stream
+ */
+void OPJ_CALLCONV cio_seek(opj_cio_t *cio, int pos) {
+       cio->bp = cio->start + pos;
+}
+
+/*
+ * Number of bytes left before the end of the stream.
+ */
+int cio_numbytesleft(opj_cio_t *cio) {
+       return cio->end - cio->bp;
+}
+
+/*
+ * Get pointer to the current position in the stream.
+ */
+unsigned char *cio_getbp(opj_cio_t *cio) {
+       return cio->bp;
+}
+
+/*
+ * Write a byte.
+ */
+bool cio_byteout(opj_cio_t *cio, unsigned char v) {
+       if (cio->bp >= cio->end) {
+               opj_event_msg(cio->cinfo, EVT_ERROR, "write error\n");
+               return false;
+       }
+       *cio->bp++ = v;
+       return true;
+}
+
+/*
+ * Read a byte.
+ */
+unsigned char cio_bytein(opj_cio_t *cio) {
+       if (cio->bp >= cio->end) {
+               opj_event_msg(cio->cinfo, EVT_ERROR, "read error: passed the end of the codestream (start = %d, current = %d, end = %d\n", cio->start, cio->bp, cio->end);
+               return 0;
+       }
+       return *cio->bp++;
+}
+
+/*
+ * Write some bytes.
+ *
+ * v : value to write
+ * n : number of bytes to write
+ */
+unsigned int cio_write(opj_cio_t *cio, unsigned int v, int n) {
+       int i;
+       for (i = n - 1; i >= 0; i--) {
+               if( !cio_byteout(cio, (unsigned char) ((v >> (i << 3)) & 0xff)) )
+                       return 0;
+       }
+       return n;
+}
+
+/*
+ * Read some bytes.
+ *
+ * n : number of bytes to read
+ *
+ * return : value of the n bytes read
+ */
+unsigned int cio_read(opj_cio_t *cio, int n) {
+       int i;
+       unsigned int v;
+       v = 0;
+       for (i = n - 1; i >= 0; i--) {
+               v += cio_bytein(cio) << (i << 3);
+       }
+       return v;
+}
+
+/* 
+ * Skip some bytes.
+ *
+ * n : number of bytes to skip
+ */
+void cio_skip(opj_cio_t *cio, int n) {
+       cio->bp += n;
+}
+
+
+
diff --git a/extern/libopenjpeg/cio.h b/extern/libopenjpeg/cio.h
new file mode 100644 (file)
index 0000000..580bf9c
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __CIO_H
+#define __CIO_H
+/**
+@file cio.h
+@brief Implementation of a byte input-output process (CIO)
+
+The functions in CIO.C have for goal to realize a byte input / output process.
+*/
+
+/** @defgroup CIO CIO - byte input-output stream */
+/*@{*/
+
+/** @name Exported functions (see also openjpeg.h) */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+/**
+Number of bytes left before the end of the stream
+@param cio CIO handle
+@return Returns the number of bytes before the end of the stream
+*/
+int cio_numbytesleft(opj_cio_t *cio);
+/**
+Get pointer to the current position in the stream
+@param cio CIO handle
+@return Returns a pointer to the current position
+*/
+unsigned char *cio_getbp(opj_cio_t *cio);
+/**
+Write some bytes
+@param cio CIO handle
+@param v Value to write
+@param n Number of bytes to write
+@return Returns the number of bytes written or 0 if an error occured
+*/
+unsigned int cio_write(opj_cio_t *cio, unsigned int v, int n);
+/**
+Read some bytes
+@param cio CIO handle
+@param n Number of bytes to read
+@return Returns the value of the n bytes read
+*/
+unsigned int cio_read(opj_cio_t *cio, int n);
+/**
+Skip some bytes
+@param cio CIO handle
+@param n Number of bytes to skip
+*/
+void cio_skip(opj_cio_t *cio, int n);
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif /* __CIO_H */
+
diff --git a/extern/libopenjpeg/dwt.c b/extern/libopenjpeg/dwt.c
new file mode 100644 (file)
index 0000000..78d18d1
--- /dev/null
@@ -0,0 +1,825 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * Copyright (c) 2007, Jonathan Ballard <dzonatas@dzonux.net>
+ * Copyright (c) 2007, Callum Lerwick <seg@haxxed.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifdef __SSE__
+#include <xmmintrin.h>
+#endif
+
+#include "opj_includes.h"
+
+/** @defgroup DWT DWT - Implementation of a discrete wavelet transform */
+/*@{*/
+
+#define WS(i) v->mem[(i)*2]
+#define WD(i) v->mem[(1+(i)*2)]
+
+/** @name Local data structures */
+/*@{*/
+
+typedef struct dwt_local {
+       int* mem;
+       int dn;
+       int sn;
+       int cas;
+} dwt_t;
+
+typedef union {
+       float   f[4];
+} v4;
+
+typedef struct v4dwt_local {
+       v4*     wavelet ;
+       int             dn ;
+       int             sn ;
+       int             cas ;
+} v4dwt_t ;
+
+static const float dwt_alpha =  1.586134342f; //  12994
+static const float dwt_beta  =  0.052980118f; //    434
+static const float dwt_gamma = -0.882911075f; //  -7233
+static const float dwt_delta = -0.443506852f; //  -3633
+
+static const float K      = 1.230174105f; //  10078
+/* FIXME: What is this constant? */
+static const float c13318 = 1.625732422f;
+
+/*@}*/
+
+/**
+Virtual function type for wavelet transform in 1-D 
+*/
+typedef void (*DWT1DFN)(dwt_t* v);
+
+/** @name Local static functions */
+/*@{*/
+
+/**
+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);
+/**
+Inverse lazy transform (horizontal)
+*/
+static void dwt_interleave_h(dwt_t* h, int *a);
+/**
+Inverse lazy transform (vertical)
+*/
+static void dwt_interleave_v(dwt_t* v, int *a, int x);
+/**
+Forward 5-3 wavelet transform in 1-D
+*/
+static void dwt_encode_1(int *a, int dn, int sn, int cas);
+/**
+Inverse 5-3 wavelet transform in 1-D
+*/
+static void dwt_decode_1(dwt_t *v);
+/**
+Forward 9-7 wavelet transform in 1-D
+*/
+static void dwt_encode_1_real(int *a, int dn, int sn, int cas);
+/**
+Explicit calculation of the Quantization Stepsizes 
+*/
+static void dwt_encode_stepsize(int stepsize, int numbps, opj_stepsize_t *bandno_stepsize);
+/**
+Inverse wavelet transform in 2-D.
+*/
+static void dwt_decode_tile(opj_tcd_tilecomp_t* tilec, int i, DWT1DFN fn);
+
+/*@}*/
+
+/*@}*/
+
+#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 const double dwt_norms[4][10] = {
+       {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}
+};
+
+/* <summary>                                                              */
+/* This table contains the norms of the 9-7 wavelets for different bands. */
+/* </summary>                                                             */
+static const double dwt_norms_real[4][10] = {
+       {1.000, 1.965, 4.177, 8.403, 16.90, 33.84, 67.69, 135.3, 270.6, 540.9},
+       {2.022, 3.989, 8.355, 17.04, 34.27, 68.63, 137.3, 274.6, 549.0},
+       {2.022, 3.989, 8.355, 17.04, 34.27, 68.63, 137.3, 274.6, 549.0},
+       {2.080, 3.865, 8.307, 17.18, 34.71, 69.59, 139.3, 278.6, 557.2}
+};
+
+/* 
+==========================================================
+   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>                             */
+/* Inverse lazy transform (horizontal).  */
+/* </summary>                            */
+static void dwt_interleave_h(dwt_t* h, int *a) {
+    int *ai = a;
+    int *bi = h->mem + h->cas;
+    int  i     = h->sn;
+    while( i-- ) {
+      *bi = *(ai++);
+         bi += 2;
+    }
+    ai = a + h->sn;
+    bi = h->mem + 1 - h->cas;
+    i  = h->dn ;
+    while( i-- ) {
+      *bi = *(ai++);
+         bi += 2;
+    }
+}
+
+/* <summary>                             */  
+/* Inverse lazy transform (vertical).    */
+/* </summary>                            */ 
+static void dwt_interleave_v(dwt_t* v, int *a, int x) {
+    int *ai = a;
+    int *bi = v->mem + v->cas;
+    int  i = v->sn;
+    while( i-- ) {
+      *bi = *ai;
+         bi += 2;
+         ai += x;
+    }
+    ai = a + (v->sn * x);
+    bi = v->mem + 1 - v->cas;
+    i = v->dn ;
+    while( i-- ) {
+      *bi = *ai;
+         bi += 2;  
+         ai += x;
+    }
+}
+
+
+/* <summary>                            */
+/* Forward 5-3 wavelet transform in 1-D. */
+/* </summary>                           */
+static void dwt_encode_1(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;
+               }
+       } else {
+               if (!sn && dn == 1)                 /* NEW :  CASE ONE ELEMENT */
+                       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;
+               }
+       }
+}
+
+/* <summary>                            */
+/* Inverse 5-3 wavelet transform in 1-D. */
+/* </summary>                           */ 
+static void dwt_decode_1_(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;
+               }
+       }
+}
+
+/* <summary>                            */
+/* Inverse 5-3 wavelet transform in 1-D. */
+/* </summary>                           */ 
+static void dwt_decode_1(dwt_t *v) {
+       dwt_decode_1_(v->mem, v->dn, v->sn, v->cas);
+}
+
+/* <summary>                             */
+/* Forward 9-7 wavelet transform in 1-D. */
+/* </summary>                            */
+static void dwt_encode_1_real(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 */
+               }
+       }
+}
+
+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;
+}
+
+/* 
+==========================================================
+   DWT interface
+==========================================================
+*/
+
+/* <summary>                            */
+/* Forward 5-3 wavelet transform in 2-D. */
+/* </summary>                           */
+void dwt_encode(opj_tcd_tilecomp_t * tilec) {
+       int i, j, k;
+       int *a = NULL;
+       int *aj = NULL;
+       int *bj = NULL;
+       int w, l;
+       
+       w = tilec->x1-tilec->x0;
+       l = tilec->numresolutions-1;
+       a = tilec->data;
+       
+       for (i = 0; i < l; i++) {
+               int rw;                 /* width of the resolution level computed                                                           */
+               int rh;                 /* height 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 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 dn, sn;
+               
+               rw = tilec->resolutions[l - i].x1 - tilec->resolutions[l - i].x0;
+               rh = tilec->resolutions[l - i].y1 - tilec->resolutions[l - i].y0;
+               rw1= tilec->resolutions[l - i - 1].x1 - tilec->resolutions[l - i - 1].x0;
+               rh1= tilec->resolutions[l - i - 1].y1 - tilec->resolutions[l - i - 1].y0;
+               
+               cas_row = tilec->resolutions[l - i].x0 % 2;
+               cas_col = tilec->resolutions[l - i].y0 % 2;
+        
+               sn = rh1;
+               dn = rh - rh1;
+               bj = (int*)opj_malloc(rh * sizeof(int));
+               for (j = 0; j < rw; j++) {
+                       aj = a + j;
+                       for (k = 0; k < rh; k++)  bj[k] = aj[k*w];
+                       dwt_encode_1(bj, dn, sn, cas_col);
+                       dwt_deinterleave_v(bj, aj, dn, sn, w, cas_col);
+               }
+               opj_free(bj);
+               
+               sn = rw1;
+               dn = rw - rw1;
+               bj = (int*)opj_malloc(rw * sizeof(int));
+               for (j = 0; j < rh; j++) {
+                       aj = a + j * w;
+                       for (k = 0; k < rw; k++)  bj[k] = aj[k];
+                       dwt_encode_1(bj, dn, sn, cas_row);
+                       dwt_deinterleave_h(bj, aj, dn, sn, cas_row);
+               }
+               opj_free(bj);
+       }
+}
+
+
+/* <summary>                            */
+/* Inverse 5-3 wavelet transform in 2-D. */
+/* </summary>                           */
+void dwt_decode(opj_tcd_tilecomp_t* tilec, int numres) {
+       dwt_decode_tile(tilec, numres, &dwt_decode_1);
+}
+
+
+/* <summary>                          */
+/* Get gain of 5-3 wavelet transform. */
+/* </summary>                         */
+int dwt_getgain(int orient) {
+       if (orient == 0)
+               return 0;
+       if (orient == 1 || orient == 2)
+               return 1;
+       return 2;
+}
+
+/* <summary>                */
+/* Get norm of 5-3 wavelet. */
+/* </summary>               */
+double dwt_getnorm(int level, int orient) {
+       return dwt_norms[orient][level];
+}
+
+/* <summary>                             */
+/* Forward 9-7 wavelet transform in 2-D. */
+/* </summary>                            */
+
+void dwt_encode_real(opj_tcd_tilecomp_t * tilec) {
+       int i, j, k;
+       int *a = NULL;
+       int *aj = NULL;
+       int *bj = NULL;
+       int w, l;
+       
+       w = tilec->x1-tilec->x0;
+       l = tilec->numresolutions-1;
+       a = tilec->data;
+       
+       for (i = 0; i < l; i++) {
+               int rw;                 /* width of the resolution level computed                                                     */
+               int rh;                 /* height 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 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 dn, sn;
+               
+               rw = tilec->resolutions[l - i].x1 - tilec->resolutions[l - i].x0;
+               rh = tilec->resolutions[l - i].y1 - tilec->resolutions[l - i].y0;
+               rw1= tilec->resolutions[l - i - 1].x1 - tilec->resolutions[l - i - 1].x0;
+               rh1= tilec->resolutions[l - i - 1].y1 - tilec->resolutions[l - i - 1].y0;
+               
+               cas_row = tilec->resolutions[l - i].x0 % 2;
+               cas_col = tilec->resolutions[l - i].y0 % 2;
+               
+               sn = rh1;
+               dn = rh - rh1;
+               bj = (int*)opj_malloc(rh * sizeof(int));
+               for (j = 0; j < rw; j++) {
+                       aj = a + j;
+                       for (k = 0; k < rh; k++)  bj[k] = aj[k*w];
+                       dwt_encode_1_real(bj, dn, sn, cas_col);
+                       dwt_deinterleave_v(bj, aj, dn, sn, w, cas_col);
+               }
+               opj_free(bj);
+               
+               sn = rw1;
+               dn = rw - rw1;
+               bj = (int*)opj_malloc(rw * sizeof(int));
+               for (j = 0; j < rh; j++) {
+                       aj = a + j * w;
+                       for (k = 0; k < rw; k++)  bj[k] = aj[k];
+                       dwt_encode_1_real(bj, dn, sn, cas_row);
+                       dwt_deinterleave_h(bj, aj, dn, sn, cas_row);
+               }
+               opj_free(bj);
+       }
+}
+
+
+/* <summary>                          */
+/* Get gain of 9-7 wavelet transform. */
+/* </summary>                         */
+int dwt_getgain_real(int orient) {
+       (void)orient;
+       return 0;
+}
+
+/* <summary>                */
+/* Get norm of 9-7 wavelet. */
+/* </summary>               */
+double dwt_getnorm_real(int level, int orient) {
+       return dwt_norms_real[orient][level];
+}
+
+void dwt_calc_explicit_stepsizes(opj_tccp_t * tccp, int prec) {
+       int numbands, bandno;
+       numbands = 3 * tccp->numresolutions - 2;
+       for (bandno = 0; bandno < numbands; bandno++) {
+               double stepsize;
+               int resno, level, orient, gain;
+
+               resno = (bandno == 0) ? 0 : ((bandno - 1) / 3 + 1);
+               orient = (bandno == 0) ? 0 : ((bandno - 1) % 3 + 1);
+               level = tccp->numresolutions - 1 - resno;
+               gain = (tccp->qmfbid == 0) ? 0 : ((orient == 0) ? 0 : (((orient == 1) || (orient == 2)) ? 1 : 2));
+               if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
+                       stepsize = 1.0;
+               } else {
+                       double norm = dwt_norms_real[orient][level];
+                       stepsize = (1 << (gain)) / norm;
+               }
+               dwt_encode_stepsize((int) floor(stepsize * 8192.0), prec + gain, &tccp->stepsizes[bandno]);
+       }
+}
+
+
+/* <summary>                             */
+/* Determine maximum computed resolution level for inverse wavelet transform */
+/* </summary>                            */
+static int dwt_decode_max_resolution(opj_tcd_resolution_t* restrict r, int i) {
+       int mr  = 1;
+       int w;
+       while( --i ) {
+               r++;
+               if( mr < ( w = r->x1 - r->x0 ) )
+                       mr = w ;
+               if( mr < ( w = r->y1 - r->y0 ) )
+                       mr = w ;
+       }
+       return mr ;
+}
+
+
+/* <summary>                            */
+/* Inverse wavelet transform in 2-D.     */
+/* </summary>                           */
+static void dwt_decode_tile(opj_tcd_tilecomp_t* tilec, int numres, DWT1DFN dwt_1D) {
+       dwt_t h;
+       dwt_t v;
+
+       opj_tcd_resolution_t* tr = tilec->resolutions;
+
+       int rw = tr->x1 - tr->x0;       /* width of the resolution level computed */
+       int rh = tr->y1 - tr->y0;       /* height of the resolution level computed */
+
+       int w = tilec->x1 - tilec->x0;
+
+       h.mem = opj_aligned_malloc(dwt_decode_max_resolution(tr, numres) * sizeof(int));
+       v.mem = h.mem;
+
+       while( --numres) {
+               int * restrict tiledp = tilec->data;
+               int j;
+
+               ++tr;
+               h.sn = rw;
+               v.sn = rh;
+
+               rw = tr->x1 - tr->x0;
+               rh = tr->y1 - tr->y0;
+
+               h.dn = rw - h.sn;
+               h.cas = tr->x0 % 2;
+
+               for(j = 0; j < rh; ++j) {
+                       dwt_interleave_h(&h, &tiledp[j*w]);
+                       (dwt_1D)(&h);
+                       memcpy(&tiledp[j*w], h.mem, rw * sizeof(int));
+               }
+
+               v.dn = rh - v.sn;
+               v.cas = tr->y0 % 2;
+
+               for(j = 0; j < rw; ++j){
+                       int k;
+                       dwt_interleave_v(&v, &tiledp[j], w);
+                       (dwt_1D)(&v);
+                       for(k = 0; k < rh; ++k) {
+                               tiledp[k * w + j] = v.mem[k];
+                       }
+               }
+       }
+       opj_aligned_free(h.mem);
+}
+
+static void v4dwt_interleave_h(v4dwt_t* restrict w, float* restrict a, int x, int size){
+       float* restrict bi = (float*) (w->wavelet + w->cas);
+       int count = w->sn;
+       int i, k;
+       for(k = 0; k < 2; ++k){
+               for(i = 0; i < count; ++i){
+                       int j = i;
+                       bi[i*8    ] = a[j];
+                       j += x;
+                       if(j > size) continue;
+                       bi[i*8 + 1] = a[j];
+                       j += x;
+                       if(j > size) continue;
+                       bi[i*8 + 2] = a[j];
+                       j += x;
+                       if(j > size) continue;
+                       bi[i*8 + 3] = a[j];
+               }
+               bi = (float*) (w->wavelet + 1 - w->cas);
+               a += w->sn;
+               size -= w->sn;
+               count = w->dn;
+       }
+}
+
+static void v4dwt_interleave_v(v4dwt_t* restrict v , float* restrict a , int x){
+       v4* restrict bi = v->wavelet + v->cas;
+       int i;
+       for(i = 0; i < v->sn; ++i){
+               memcpy(&bi[i*2], &a[i*x], 4 * sizeof(float));
+       }
+       a += v->sn * x;
+       bi = v->wavelet + 1 - v->cas;
+       for(i = 0; i < v->dn; ++i){
+               memcpy(&bi[i*2], &a[i*x], 4 * sizeof(float));
+       }
+}
+
+#ifdef __SSE__
+
+static void v4dwt_decode_step1_sse(v4* w, int count, const __m128 c){
+       __m128* restrict vw = (__m128*) w;
+       int i;
+       for(i = 0; i < count; ++i){
+               __m128 tmp = vw[i*2];
+               vw[i*2] = tmp * c;
+       }
+}
+
+static void v4dwt_decode_step2_sse(v4* l, v4* w, int k, int m, __m128 c){
+       __m128* restrict vl = (__m128*) l;
+       __m128* restrict vw = (__m128*) w;
+       int i;
+       for(i = 0; i < m; ++i){
+               __m128 tmp1 = vl[ 0];
+               __m128 tmp2 = vw[-1];
+               __m128 tmp3 = vw[ 0];
+               vw[-1] = tmp2 + ((tmp1 + tmp3) * c);
+               vl = vw;
+               vw += 2;
+       }
+       if(m >= k){
+               return;
+       }
+       c += c;
+       c *= vl[0];
+       for(; m < k; ++m){
+               __m128 tmp = vw[-1];
+               vw[-1] = tmp + c;
+               vw += 2;
+       }
+}
+
+#else
+
+static void v4dwt_decode_step1(v4* w, int count, const float c){
+       float* restrict fw = (float*) w;
+       int i;
+       for(i = 0; i < count; ++i){
+               float tmp1 = fw[i*8    ];
+               float tmp2 = fw[i*8 + 1];
+               float tmp3 = fw[i*8 + 2];
+               float tmp4 = fw[i*8 + 3];
+               fw[i*8    ] = tmp1 * c;
+               fw[i*8 + 1] = tmp2 * c;
+               fw[i*8 + 2] = tmp3 * c;
+               fw[i*8 + 3] = tmp4 * c;
+       }
+}
+
+static void v4dwt_decode_step2(v4* l, v4* w, int k, int m, float c){
+       float* restrict fl = (float*) l;
+       float* restrict fw = (float*) w;
+       int i;
+       for(i = 0; i < m; ++i){
+               float tmp1_1 = fl[0];
+               float tmp1_2 = fl[1];
+               float tmp1_3 = fl[2];
+               float tmp1_4 = fl[3];
+               float tmp2_1 = fw[-4];
+               float tmp2_2 = fw[-3];
+               float tmp2_3 = fw[-2];
+               float tmp2_4 = fw[-1];
+               float tmp3_1 = fw[0];
+               float tmp3_2 = fw[1];
+               float tmp3_3 = fw[2];
+               float tmp3_4 = fw[3];
+               fw[-4] = tmp2_1 + ((tmp1_1 + tmp3_1) * c);
+               fw[-3] = tmp2_2 + ((tmp1_2 + tmp3_2) * c);
+               fw[-2] = tmp2_3 + ((tmp1_3 + tmp3_3) * c);
+               fw[-1] = tmp2_4 + ((tmp1_4 + tmp3_4) * c);
+               fl = fw;
+               fw += 8;
+       }
+       if(m < k){
+               float c1;
+               float c2;
+               float c3;
+               float c4;
+               c += c;
+               c1 = fl[0] * c;
+               c2 = fl[1] * c;
+               c3 = fl[2] * c;
+               c4 = fl[3] * c;
+               for(; m < k; ++m){
+                       float tmp1 = fw[-4];
+                       float tmp2 = fw[-3];
+                       float tmp3 = fw[-2];
+                       float tmp4 = fw[-1];
+                       fw[-4] = tmp1 + c1;
+                       fw[-3] = tmp2 + c2;
+                       fw[-2] = tmp3 + c3;
+                       fw[-1] = tmp4 + c4;
+                       fw += 8;
+               }
+       }
+}
+
+#endif
+
+/* <summary>                             */
+/* Inverse 9-7 wavelet transform in 1-D. */
+/* </summary>                            */
+static void v4dwt_decode(v4dwt_t* restrict dwt){
+       int a, b;
+       if(dwt->cas == 0) {
+               if(!((dwt->dn > 0) || (dwt->sn > 1))){
+                       return;
+               }
+               a = 0;
+               b = 1;
+       }else{
+               if(!((dwt->sn > 0) || (dwt->dn > 1))) {
+                       return;
+               }
+               a = 1;
+               b = 0;
+       }
+#ifdef __SSE__
+       v4dwt_decode_step1_sse(dwt->wavelet+a, dwt->sn, _mm_set1_ps(K));
+       v4dwt_decode_step1_sse(dwt->wavelet+b, dwt->dn, _mm_set1_ps(c13318));
+       v4dwt_decode_step2_sse(dwt->wavelet+b, dwt->wavelet+a+1, dwt->sn, int_min(dwt->sn, dwt->dn-a), _mm_set1_ps(dwt_delta));
+       v4dwt_decode_step2_sse(dwt->wavelet+a, dwt->wavelet+b+1, dwt->dn, int_min(dwt->dn, dwt->sn-b), _mm_set1_ps(dwt_gamma));
+       v4dwt_decode_step2_sse(dwt->wavelet+b, dwt->wavelet+a+1, dwt->sn, int_min(dwt->sn, dwt->dn-a), _mm_set1_ps(dwt_beta));
+       v4dwt_decode_step2_sse(dwt->wavelet+a, dwt->wavelet+b+1, dwt->dn, int_min(dwt->dn, dwt->sn-b), _mm_set1_ps(dwt_alpha));
+#else
+       v4dwt_decode_step1(dwt->wavelet+a, dwt->sn, K);
+       v4dwt_decode_step1(dwt->wavelet+b, dwt->dn, c13318);
+       v4dwt_decode_step2(dwt->wavelet+b, dwt->wavelet+a+1, dwt->sn, int_min(dwt->sn, dwt->dn-a), dwt_delta);
+       v4dwt_decode_step2(dwt->wavelet+a, dwt->wavelet+b+1, dwt->dn, int_min(dwt->dn, dwt->sn-b), dwt_gamma);
+       v4dwt_decode_step2(dwt->wavelet+b, dwt->wavelet+a+1, dwt->sn, int_min(dwt->sn, dwt->dn-a), dwt_beta);
+       v4dwt_decode_step2(dwt->wavelet+a, dwt->wavelet+b+1, dwt->dn, int_min(dwt->dn, dwt->sn-b), dwt_alpha);
+#endif
+}
+
+/* <summary>                             */
+/* Inverse 9-7 wavelet transform in 2-D. */
+/* </summary>                            */
+void dwt_decode_real(opj_tcd_tilecomp_t* restrict tilec, int numres){
+       v4dwt_t h;
+       v4dwt_t v;
+
+       opj_tcd_resolution_t* res = tilec->resolutions;
+
+       int rw = res->x1 - res->x0;     /* width of the resolution level computed */
+       int rh = res->y1 - res->y0;     /* height of the resolution level computed */
+
+       int w = tilec->x1 - tilec->x0;
+
+       h.wavelet = (v4*) opj_aligned_malloc((dwt_decode_max_resolution(res, numres)+5) * sizeof(v4));
+       v.wavelet = h.wavelet;
+
+       while( --numres) {
+               float * restrict aj = (float*) tilec->data;
+               int bufsize = (tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0);
+               int j;
+
+               h.sn = rw;
+               v.sn = rh;
+
+               ++res;
+
+               rw = res->x1 - res->x0; /* width of the resolution level computed */
+               rh = res->y1 - res->y0; /* height of the resolution level computed */
+
+               h.dn = rw - h.sn;
+               h.cas = res->x0 % 2;
+
+               for(j = rh; j > 0; j -= 4){
+                       v4dwt_interleave_h(&h, aj, w, bufsize);
+                       v4dwt_decode(&h);
+                       if(j >= 4){
+                               int k;
+                               for(k = rw; --k >= 0;){
+                                       aj[k    ] = h.wavelet[k].f[0];
+                                       aj[k+w  ] = h.wavelet[k].f[1];
+                                       aj[k+w*2] = h.wavelet[k].f[2];
+                                       aj[k+w*3] = h.wavelet[k].f[3];
+                               }
+                       }else{
+                               int k;
+                               for(k = rw; --k >= 0;){
+                                       switch(j) {
+                                               case 3: aj[k+w*2] = h.wavelet[k].f[2];
+                                               case 2: aj[k+w  ] = h.wavelet[k].f[1];
+                                               case 1: aj[k    ] = h.wavelet[k].f[0];
+                                       }
+                               }
+                       }
+                       aj += w*4;
+                       bufsize -= w*4;
+               }
+
+               v.dn = rh - v.sn;
+               v.cas = res->y0 % 2;
+
+               aj = (float*) tilec->data;
+               for(j = rw; j > 0; j -= 4){
+                       v4dwt_interleave_v(&v, aj, w);
+                       v4dwt_decode(&v);
+                       if(j >= 4){
+                               int k;
+                               for(k = 0; k < rh; ++k){
+                                       memcpy(&aj[k*w], &v.wavelet[k], 4 * sizeof(float));
+                               }
+                       }else{
+                               int k;
+                               for(k = 0; k < rh; ++k){
+                                       memcpy(&aj[k*w], &v.wavelet[k], j * sizeof(float));
+                               }
+                       }
+                       aj += 4;
+               }
+       }
+
+       opj_aligned_free(h.wavelet);
+}
+
diff --git a/extern/libopenjpeg/dwt.h b/extern/libopenjpeg/dwt.h
new file mode 100644 (file)
index 0000000..adf73e5
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __DWT_H
+#define __DWT_H
+/**
+@file dwt.h
+@brief Implementation of a discrete wavelet transform (DWT)
+
+The functions in DWT.C have for goal to realize forward and inverse discret wavelet
+transform with filter 5-3 (reversible) and filter 9-7 (irreversible). The functions in
+DWT.C are used by some function in TCD.C.
+*/
+
+/** @defgroup DWT DWT - Implementation of a discrete wavelet transform */
+/*@{*/
+
+
+/** @name Exported functions */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+/**
+Forward 5-3 wavelet tranform in 2-D. 
+Apply a reversible DWT transform to a component of an image.
+@param tilec Tile component information (current tile)
+*/
+void dwt_encode(opj_tcd_tilecomp_t * tilec);
+/**
+Inverse 5-3 wavelet tranform in 2-D.
+Apply a reversible inverse DWT transform to a component of an image.
+@param tilec Tile component information (current tile)
+@param numres Number of resolution levels to decode
+*/
+void dwt_decode(opj_tcd_tilecomp_t* tilec, int numres);
+/**
+Get the gain of a subband for the reversible 5-3 DWT.
+@param orient Number that identifies the subband (0->LL, 1->HL, 2->LH, 3->HH)
+@return Returns 0 if orient = 0, returns 1 if orient = 1 or 2, returns 2 otherwise
+*/
+int dwt_getgain(int orient);
+/**
+Get the norm of a wavelet function of a subband at a specified level for the reversible 5-3 DWT.
+@param level Level of the wavelet function
+@param orient Band of the wavelet function
+@return Returns the norm of the wavelet function
+*/
+double dwt_getnorm(int level, int orient);
+/**
+Forward 9-7 wavelet transform in 2-D. 
+Apply an irreversible DWT transform to a component of an image.
+@param tilec Tile component information (current tile)
+*/
+void dwt_encode_real(opj_tcd_tilecomp_t * tilec);
+/**
+Inverse 9-7 wavelet transform in 2-D. 
+Apply an irreversible inverse DWT transform to a component of an image.
+@param tilec Tile component information (current tile)
+@param numres Number of resolution levels to decode
+*/
+void dwt_decode_real(opj_tcd_tilecomp_t* tilec, int numres);
+/**
+Get the gain of a subband for the irreversible 9-7 DWT.
+@param orient Number that identifies the subband (0->LL, 1->HL, 2->LH, 3->HH)
+@return Returns the gain of the 9-7 wavelet transform
+*/
+int dwt_getgain_real(int orient);
+/**
+Get the norm of a wavelet function of a subband at a specified level for the irreversible 9-7 DWT
+@param level Level of the wavelet function
+@param orient Band of the wavelet function
+@return Returns the norm of the 9-7 wavelet
+*/
+double dwt_getnorm_real(int level, int orient);
+/**
+Explicit calculation of the Quantization Stepsizes 
+@param tccp Tile-component coding parameters
+@param prec Precint analyzed
+*/
+void dwt_calc_explicit_stepsizes(opj_tccp_t * tccp, int prec);
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif /* __DWT_H */
diff --git a/extern/libopenjpeg/event.c b/extern/libopenjpeg/event.c
new file mode 100644 (file)
index 0000000..291ff58
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2005, Hervé Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "opj_includes.h"
+
+/* ==========================================================
+     Utility functions
+   ==========================================================*/
+
+#if !defined(_MSC_VER) && !defined(__MINGW32__)
+static char*
+i2a(unsigned i, char *a, unsigned r) {
+       if (i/r > 0) a = i2a(i/r,a,r);
+       *a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i%r];
+       return a+1;
+}
+
+/** 
+ Transforms integer i into an ascii string and stores the result in a; 
+ string is encoded in the base indicated by r.
+ @param i Number to be converted
+ @param a String result
+ @param r Base of value; must be in the range 2 - 36
+ @return Returns a
+*/
+static char *
+_itoa(int i, char *a, int r) {
+       r = ((r < 2) || (r > 36)) ? 10 : r;
+       if(i < 0) {
+               *a = '-';
+               *i2a(-i, a+1, r) = 0;
+       }
+       else *i2a(i, a, r) = 0;
+       return a;
+}
+
+#endif /* !WIN32 */
+
+/* ----------------------------------------------------------------------- */
+
+opj_event_mgr_t* OPJ_CALLCONV opj_set_event_mgr(opj_common_ptr cinfo, opj_event_mgr_t *event_mgr, void *context) {
+       if(cinfo) {
+               opj_event_mgr_t *previous = cinfo->event_mgr;
+               cinfo->event_mgr = event_mgr;
+               cinfo->client_data = context;
+               return previous;
+       }
+
+       return NULL;
+}
+
+bool opj_event_msg(opj_common_ptr cinfo, int event_type, const char *fmt, ...) {
+#define MSG_SIZE 512 /* 512 bytes should be more than enough for a short message */
+       opj_msg_callback msg_handler = NULL;
+
+       opj_event_mgr_t *event_mgr = cinfo->event_mgr;
+       if(event_mgr != NULL) {
+               switch(event_type) {
+                       case EVT_ERROR:
+                               msg_handler = event_mgr->error_handler;
+                               break;
+                       case EVT_WARNING:
+                               msg_handler = event_mgr->warning_handler;
+                               break;
+                       case EVT_INFO:
+                               msg_handler = event_mgr->info_handler;
+                               break;
+                       default:
+                               break;
+               }
+               if(msg_handler == NULL) {
+                       return false;
+               }
+       } else {
+               return false;
+       }
+
+       if ((fmt != NULL) && (event_mgr != NULL)) {
+               va_list arg;
+               int str_length/*, i, j*/; /* UniPG */
+               char message[MSG_SIZE];
+               memset(message, 0, MSG_SIZE);
+               /* initialize the optional parameter list */
+               va_start(arg, fmt);
+               /* check the length of the format string */
+               str_length = (strlen(fmt) > MSG_SIZE) ? MSG_SIZE : strlen(fmt);
+               /* parse the format string and put the result in 'message' */
+               vsprintf(message, fmt, arg); /* UniPG */
+               /* deinitialize the optional parameter list */
+               va_end(arg);
+
+               /* output the message to the user program */
+               msg_handler(message, cinfo->client_data);
+       }
+
+       return true;
+}
+
diff --git a/extern/libopenjpeg/event.h b/extern/libopenjpeg/event.h
new file mode 100644 (file)
index 0000000..11910b0
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2005, Hervé 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 __EVENT_H
+#define __EVENT_H
+/**
+@file event.h
+@brief Implementation of a event callback system
+
+The functions in EVENT.C have for goal to send output messages (errors, warnings, debug) to the user.
+*/
+
+#define EVT_ERROR      1       /**< Error event type */
+#define EVT_WARNING    2       /**< Warning event type */
+#define EVT_INFO       4       /**< Debug event type */
+
+/** @defgroup EVENT EVENT - Implementation of a event callback system */
+/*@{*/
+
+/** @name Exported functions (see also openjpeg.h) */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+/**
+Write formatted data to a string and send the string to a user callback. 
+@param cinfo Codec context info
+@param event_type Event type or callback to use to send the message
+@param fmt Format-control string (plus optionnal arguments)
+@return Returns true if successful, returns false otherwise
+*/
+bool opj_event_msg(opj_common_ptr cinfo, int event_type, const char *fmt, ...);
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif /* __EVENT_H */
diff --git a/extern/libopenjpeg/fix.h b/extern/libopenjpeg/fix.h
new file mode 100644 (file)
index 0000000..bcb2acb
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef __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 INLINE int fix_mul(int a, int b) {
+    int64 temp = (int64) a * (int64) b ;
+    temp += temp & 4096;
+    return (int) (temp >> 13) ;
+}
+
+/*@}*/
+
+#endif /* __FIX_H */
diff --git a/extern/libopenjpeg/image.c b/extern/libopenjpeg/image.c
new file mode 100644 (file)
index 0000000..ea8e59e
--- /dev/null
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2005, Hervé Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "opj_includes.h"
+
+opj_image_t* opj_image_create0(void) {
+       opj_image_t *image = (opj_image_t*)opj_malloc(sizeof(opj_image_t));
+       return image;
+}
+
+opj_image_t* OPJ_CALLCONV opj_image_create(int numcmpts, opj_image_cmptparm_t *cmptparms, OPJ_COLOR_SPACE clrspc) {
+       int compno;
+       opj_image_t *image = NULL;
+
+       image = (opj_image_t*) opj_calloc(1, sizeof(opj_image_t));
+       if(image) {
+               image->color_space = clrspc;
+               image->numcomps = numcmpts;
+               /* allocate memory for the per-component information */
+               image->comps = (opj_image_comp_t*)opj_malloc(image->numcomps * sizeof(opj_image_comp_t));
+               if(!image->comps) {
+                       fprintf(stderr,"Unable to allocate memory for image.\n");
+                       opj_image_destroy(image);
+                       return NULL;
+               }
+               /* create the individual image components */
+               for(compno = 0; compno < numcmpts; compno++) {
+                       opj_image_comp_t *comp = &image->comps[compno];
+                       comp->dx = cmptparms[compno].dx;
+                       comp->dy = cmptparms[compno].dy;
+                       comp->w = cmptparms[compno].w;
+                       comp->h = cmptparms[compno].h;
+                       comp->x0 = cmptparms[compno].x0;
+                       comp->y0 = cmptparms[compno].y0;
+                       comp->prec = cmptparms[compno].prec;
+                       comp->bpp = cmptparms[compno].bpp;
+                       comp->sgnd = cmptparms[compno].sgnd;
+                       comp->data = (int*) opj_calloc(comp->w * comp->h, sizeof(int));
+                       if(!comp->data) {
+                               fprintf(stderr,"Unable to allocate memory for image.\n");
+                               opj_image_destroy(image);
+                               return NULL;
+                       }
+               }
+       }
+
+       return image;
+}
+
+void OPJ_CALLCONV opj_image_destroy(opj_image_t *image) {
+       int i;
+       if(image) {
+               if(image->comps) {
+                       /* image components */
+                       for(i = 0; i < image->numcomps; i++) {
+                               opj_image_comp_t *image_comp = &image->comps[i];
+                               if(image_comp->data) {
+                                       opj_free(image_comp->data);
+                               }
+                       }
+                       opj_free(image->comps);
+               }
+               opj_free(image);
+       }
+}
+
diff --git a/extern/libopenjpeg/image.h b/extern/libopenjpeg/image.h
new file mode 100644 (file)
index 0000000..04c362e
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2005, Hervé 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 __IMAGE_H
+#define __IMAGE_H
+/**
+@file image.h
+@brief Implementation of operations on images (IMAGE)
+
+The functions in IMAGE.C have for goal to realize operations on images.
+*/
+
+/** @defgroup IMAGE IMAGE - Implementation of operations on images */
+/*@{*/
+
+/**
+Create an empty image
+@todo this function should be removed
+@return returns an empty image if successful, returns NULL otherwise
+*/
+opj_image_t* opj_image_create0(void);
+
+/*@}*/
+
+#endif /* __IMAGE_H */
+
diff --git a/extern/libopenjpeg/int.h b/extern/libopenjpeg/int.h
new file mode 100644 (file)
index 0000000..4e5fe08
--- /dev/null
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef __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 Exported functions (see also openjpeg.h) */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+/**
+Get the minimum of two integers
+@return Returns a if a < b else b
+*/
+static INLINE 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 INLINE 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 INLINE 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 INLINE int int_abs(int a) {
+       return a < 0 ? -a : a;
+}
+/**
+Divide an integer and round upwards
+@return Returns a divided by b
+*/
+static INLINE 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 INLINE 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 INLINE int int_floordivpow2(int a, int b) {
+       return a >> b;
+}
+/**
+Get logarithm of an integer and round downwards
+@return Returns log2(a)
+*/
+static INLINE int int_floorlog2(int a) {
+       int l;
+       for (l = 0; a > 1; l++) {
+               a >>= 1;
+       }
+       return l;
+}
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif
diff --git a/extern/libopenjpeg/j2k.c b/extern/libopenjpeg/j2k.c
new file mode 100644 (file)
index 0000000..8e7b1ce
--- /dev/null
@@ -0,0 +1,2498 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * Copyright (c) 2006-2007, Parvatha Elangovan
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "opj_includes.h"
+
+/** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
+/*@{*/
+
+/** @name Local static functions */
+/*@{*/
+
+/**
+Write the SOC marker (Start Of Codestream)
+@param j2k J2K handle
+*/
+static void j2k_write_soc(opj_j2k_t *j2k);
+/**
+Read the SOC marker (Start of Codestream)
+@param j2k J2K handle
+*/
+static void j2k_read_soc(opj_j2k_t *j2k);
+/**
+Write the SIZ marker (image and tile size)
+@param j2k J2K handle
+*/
+static void j2k_write_siz(opj_j2k_t *j2k);
+/**
+Read the SIZ marker (image and tile size)
+@param j2k J2K handle
+*/
+static void j2k_read_siz(opj_j2k_t *j2k);
+/**
+Write the COM marker (comment)
+@param j2k J2K handle
+*/
+static void j2k_write_com(opj_j2k_t *j2k);
+/**
+Read the COM marker (comment)
+@param j2k J2K handle
+*/
+static void j2k_read_com(opj_j2k_t *j2k);
+/**
+Write the value concerning the specified component in the marker COD and COC
+@param j2k J2K handle
+@param compno Number of the component concerned by the information written
+*/
+static void j2k_write_cox(opj_j2k_t *j2k, int compno);
+/**
+Read the value concerning the specified component in the marker COD and COC
+@param j2k J2K handle
+@param compno Number of the component concerned by the information read
+*/
+static void j2k_read_cox(opj_j2k_t *j2k, int compno);
+/**
+Write the COD marker (coding style default)
+@param j2k J2K handle
+*/
+static void j2k_write_cod(opj_j2k_t *j2k);
+/**
+Read the COD marker (coding style default)
+@param j2k J2K handle
+*/
+static void j2k_read_cod(opj_j2k_t *j2k);
+/**
+Write the COC marker (coding style component)
+@param j2k J2K handle
+@param compno Number of the component concerned by the information written
+*/
+static void j2k_write_coc(opj_j2k_t *j2k, int compno);
+/**
+Read the COC marker (coding style component)
+@param j2k J2K handle
+*/
+static void j2k_read_coc(opj_j2k_t *j2k);
+/**
+Write the value concerning the specified component in the marker QCD and QCC
+@param j2k J2K handle
+@param compno Number of the component concerned by the information written
+*/
+static void j2k_write_qcx(opj_j2k_t *j2k, int compno);
+/**
+Read the value concerning the specified component in the marker QCD and QCC
+@param j2k J2K handle
+@param compno Number of the component concern by the information read
+@param len Length of the information in the QCX part of the marker QCD/QCC
+*/
+static void j2k_read_qcx(opj_j2k_t *j2k, int compno, int len);
+/**
+Write the QCD marker (quantization default)
+@param j2k J2K handle
+*/
+static void j2k_write_qcd(opj_j2k_t *j2k);
+/**
+Read the QCD marker (quantization default)
+@param j2k J2K handle
+*/
+static void j2k_read_qcd(opj_j2k_t *j2k);
+/**
+Write the QCC marker (quantization component)
+@param j2k J2K handle
+@param compno Number of the component concerned by the information written
+*/
+static void j2k_write_qcc(opj_j2k_t *j2k, int compno);
+/**
+Read the QCC marker (quantization component)
+@param j2k J2K handle
+*/
+static void j2k_read_qcc(opj_j2k_t *j2k);
+/**
+Write the POC marker (progression order change)
+@param j2k J2K handle
+*/
+static void j2k_write_poc(opj_j2k_t *j2k);
+/**
+Read the POC marker (progression order change)
+@param j2k J2K handle
+*/
+static void j2k_read_poc(opj_j2k_t *j2k);
+/**
+Read the CRG marker (component registration)
+@param j2k J2K handle
+*/
+static void j2k_read_crg(opj_j2k_t *j2k);
+/**
+Read the TLM marker (tile-part lengths)
+@param j2k J2K handle
+*/
+static void j2k_read_tlm(opj_j2k_t *j2k);
+/**
+Read the PLM marker (packet length, main header)
+@param j2k J2K handle
+*/
+static void j2k_read_plm(opj_j2k_t *j2k);
+/**
+Read the PLT marker (packet length, tile-part header)
+@param j2k J2K handle
+*/
+static void j2k_read_plt(opj_j2k_t *j2k);
+/**
+Read the PPM marker (packet packet headers, main header)
+@param j2k J2K handle
+*/
+static void j2k_read_ppm(opj_j2k_t *j2k);
+/**
+Read the PPT marker (packet packet headers, tile-part header)
+@param j2k J2K handle
+*/
+static void j2k_read_ppt(opj_j2k_t *j2k);
+/**
+Write the TLM marker (Mainheader)
+@param j2k J2K handle
+*/
+static void j2k_write_tlm(opj_j2k_t *j2k);
+/**
+Write the SOT marker (start of tile-part)
+@param j2k J2K handle
+*/
+static void j2k_write_sot(opj_j2k_t *j2k);
+/**
+Read the SOT marker (start of tile-part)
+@param j2k J2K handle
+*/
+static void j2k_read_sot(opj_j2k_t *j2k);
+/**
+Write the SOD marker (start of data)
+@param j2k J2K handle
+@param tile_coder Pointer to a TCD handle
+*/
+static void j2k_write_sod(opj_j2k_t *j2k, void *tile_coder);
+/**
+Read the SOD marker (start of data)
+@param j2k J2K handle
+*/
+static void j2k_read_sod(opj_j2k_t *j2k);
+/**
+Write the RGN marker (region-of-interest)
+@param j2k J2K handle
+@param compno Number of the component concerned by the information written
+@param tileno Number of the tile concerned by the information written
+*/
+static void j2k_write_rgn(opj_j2k_t *j2k, int compno, int tileno);
+/**
+Read the RGN marker (region-of-interest)
+@param j2k J2K handle
+*/
+static void j2k_read_rgn(opj_j2k_t *j2k);
+/**
+Write the EOC marker (end of codestream)
+@param j2k J2K handle
+*/
+static void j2k_write_eoc(opj_j2k_t *j2k);
+/**
+Read the EOC marker (end of codestream)
+@param j2k J2K handle
+*/
+static void j2k_read_eoc(opj_j2k_t *j2k);
+/**
+Read an unknown marker
+@param j2k J2K handle
+*/
+static void j2k_read_unk(opj_j2k_t *j2k);
+
+/*@}*/
+
+/*@}*/
+
+/* ----------------------------------------------------------------------- */
+typedef struct j2k_prog_order{
+       OPJ_PROG_ORDER enum_prog;
+       char str_prog[4];
+}j2k_prog_order_t;
+
+j2k_prog_order_t j2k_prog_order_list[] = {
+       {CPRL, "CPRL"},
+       {LRCP, "LRCP"},
+       {PCRL, "PCRL"},
+       {RLCP, "RLCP"},
+       {RPCL, "RPCL"},
+       {-1, ""}
+};
+
+char *j2k_convert_progression_order(OPJ_PROG_ORDER prg_order){
+       j2k_prog_order_t *po;
+       for(po = j2k_prog_order_list; po->enum_prog != -1; po++ ){
+               if(po->enum_prog == prg_order){
+                       break;
+               }
+       }
+       return po->str_prog;
+}
+
+void j2k_dump_image(FILE *fd, opj_image_t * img) {
+       int compno;
+       fprintf(fd, "image {\n");
+       fprintf(fd, "  x0=%d, y0=%d, x1=%d, y1=%d\n", img->x0, img->y0, img->x1, img->y1);
+       fprintf(fd, "  numcomps=%d\n", img->numcomps);
+       for (compno = 0; compno < img->numcomps; compno++) {
+               opj_image_comp_t *comp = &img->comps[compno];
+               fprintf(fd, "  comp %d {\n", compno);
+               fprintf(fd, "    dx=%d, dy=%d\n", comp->dx, comp->dy);
+               fprintf(fd, "    prec=%d\n", comp->prec);
+               fprintf(fd, "    sgnd=%d\n", comp->sgnd);
+               fprintf(fd, "  }\n");
+       }
+       fprintf(fd, "}\n");
+}
+
+void j2k_dump_cp(FILE *fd, opj_image_t * img, opj_cp_t * cp) {
+       int tileno, compno, layno, bandno, resno, numbands;
+       fprintf(fd, "coding parameters {\n");
+       fprintf(fd, "  tx0=%d, ty0=%d\n", cp->tx0, cp->ty0);
+       fprintf(fd, "  tdx=%d, tdy=%d\n", cp->tdx, cp->tdy);
+       fprintf(fd, "  tw=%d, th=%d\n", cp->tw, cp->th);
+       for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
+               opj_tcp_t *tcp = &cp->tcps[tileno];
+               fprintf(fd, "  tile %d {\n", tileno);
+               fprintf(fd, "    csty=%x\n", tcp->csty);
+               fprintf(fd, "    prg=%d\n", tcp->prg);
+               fprintf(fd, "    numlayers=%d\n", tcp->numlayers);
+               fprintf(fd, "    mct=%d\n", tcp->mct);
+               fprintf(fd, "    rates=");
+               for (layno = 0; layno < tcp->numlayers; layno++) {
+                       fprintf(fd, "%.1f ", tcp->rates[layno]);
+               }
+               fprintf(fd, "\n");
+               for (compno = 0; compno < img->numcomps; compno++) {
+                       opj_tccp_t *tccp = &tcp->tccps[compno];
+                       fprintf(fd, "    comp %d {\n", compno);
+                       fprintf(fd, "      csty=%x\n", tccp->csty);
+                       fprintf(fd, "      numresolutions=%d\n", tccp->numresolutions);
+                       fprintf(fd, "      cblkw=%d\n", tccp->cblkw);
+                       fprintf(fd, "      cblkh=%d\n", tccp->cblkh);
+                       fprintf(fd, "      cblksty=%x\n", tccp->cblksty);
+                       fprintf(fd, "      qmfbid=%d\n", tccp->qmfbid);
+                       fprintf(fd, "      qntsty=%d\n", tccp->qntsty);
+                       fprintf(fd, "      numgbits=%d\n", tccp->numgbits);
+                       fprintf(fd, "      roishift=%d\n", tccp->roishift);
+                       fprintf(fd, "      stepsizes=");
+                       numbands = tccp->qntsty == J2K_CCP_QNTSTY_SIQNT ? 1 : tccp->numresolutions * 3 - 2;
+                       for (bandno = 0; bandno < numbands; bandno++) {
+                               fprintf(fd, "(%d,%d) ", tccp->stepsizes[bandno].mant,
+                                       tccp->stepsizes[bandno].expn);
+                       }
+                       fprintf(fd, "\n");
+                       
+                       if (tccp->csty & J2K_CCP_CSTY_PRT) {
+                               fprintf(fd, "      prcw=");
+                               for (resno = 0; resno < tccp->numresolutions; resno++) {
+                                       fprintf(fd, "%d ", tccp->prcw[resno]);
+                               }
+                               fprintf(fd, "\n");
+                               fprintf(fd, "      prch=");
+                               for (resno = 0; resno < tccp->numresolutions; resno++) {
+                                       fprintf(fd, "%d ", tccp->prch[resno]);
+                               }
+                               fprintf(fd, "\n");
+                       }
+                       fprintf(fd, "    }\n");
+               }
+               fprintf(fd, "  }\n");
+       }
+       fprintf(fd, "}\n");
+}
+
+/* ----------------------------------------------------------------------- */
+static int j2k_get_num_tp(opj_cp_t *cp,int pino,int tileno){
+       char *prog;
+       int i;
+       int tpnum=1,tpend=0;
+       opj_tcp_t *tcp = &cp->tcps[tileno];
+       prog = j2k_convert_progression_order(tcp->prg);
+       
+       if(cp->tp_on == 1){
+               for(i=0;i<4;i++){
+                       if(tpend!=1){
+                               if( cp->tp_flag == prog[i] ){
+                                       tpend=1;cp->tp_pos=i;
+                               }
+                               switch(prog[i]){
+                               case 'C':
+                                       tpnum= tpnum * tcp->pocs[pino].compE;
+                                       break;
+                               case 'R':
+                                       tpnum= tpnum * tcp->pocs[pino].resE;
+                                       break;
+                               case 'P':
+                                       tpnum= tpnum * tcp->pocs[pino].prcE;
+                                       break;
+                               case 'L':
+                                       tpnum= tpnum * tcp->pocs[pino].layE;
+                                       break;
+                               }
+                       }
+               }
+       }else{
+               tpnum=1;
+       }
+       return tpnum;
+}
+
+/**    mem allocation for TLM marker*/
+int j2k_calculate_tp(opj_cp_t *cp,int img_numcomp,opj_image_t *image,opj_j2k_t *j2k ){
+       int pino,tileno,totnum_tp=0;
+       j2k->cur_totnum_tp = (int *) opj_malloc(cp->tw * cp->th * sizeof(int));
+       for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
+               int cur_totnum_tp = 0;
+               opj_tcp_t *tcp = &cp->tcps[tileno];
+               for(pino = 0; pino <= tcp->numpocs; pino++) {
+                       int tp_num=0;
+                       opj_pi_iterator_t *pi = pi_initialise_encode(image, cp, tileno,FINAL_PASS);
+                       if(!pi) { return -1;}
+                       tp_num = j2k_get_num_tp(cp,pino,tileno);
+                       totnum_tp = totnum_tp + tp_num;
+                       cur_totnum_tp = cur_totnum_tp + tp_num;
+                       pi_destroy(pi, cp, tileno);
+               }
+               j2k->cur_totnum_tp[tileno] = cur_totnum_tp;
+               /* INDEX >> */
+               if (j2k->cstr_info) {
+                       j2k->cstr_info->tile[tileno].num_tps = cur_totnum_tp;
+                       j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t));
+               }
+               /* << INDEX */
+       }
+       return totnum_tp;
+}
+
+static void j2k_write_soc(opj_j2k_t *j2k) {
+       opj_cio_t *cio = j2k->cio;
+       cio_write(cio, J2K_MS_SOC, 2);
+
+/* UniPG>> */
+#ifdef USE_JPWL
+
+       /* update markers struct */
+       j2k_add_marker(j2k->cstr_info, J2K_MS_SOC, cio_tell(cio) - 2, 2);
+
+#endif /* USE_JPWL */
+/* <<UniPG */
+}
+
+static void j2k_read_soc(opj_j2k_t *j2k) {     
+       j2k->state = J2K_STATE_MHSIZ;
+       /* Index */
+       if (j2k->cstr_info) {
+               j2k->cstr_info->main_head_start = cio_tell(j2k->cio) - 2;
+               j2k->cstr_info->codestream_size = cio_numbytesleft(j2k->cio) + 2 - j2k->cstr_info->main_head_start;
+       }
+}
+
+static void j2k_write_siz(opj_j2k_t *j2k) {
+       int i;
+       int lenp, len;
+
+       opj_cio_t *cio = j2k->cio;
+       opj_image_t *image = j2k->image;
+       opj_cp_t *cp = j2k->cp;
+       
+       cio_write(cio, J2K_MS_SIZ, 2);  /* SIZ */
+       lenp = cio_tell(cio);
+       cio_skip(cio, 2);
+       cio_write(cio, cp->rsiz, 2);                    /* Rsiz (capabilities) */
+       cio_write(cio, image->x1, 4);   /* Xsiz */
+       cio_write(cio, image->y1, 4);   /* Ysiz */
+       cio_write(cio, image->x0, 4);   /* X0siz */
+       cio_write(cio, image->y0, 4);   /* Y0siz */
+       cio_write(cio, cp->tdx, 4);             /* XTsiz */
+       cio_write(cio, cp->tdy, 4);             /* YTsiz */
+       cio_write(cio, cp->tx0, 4);             /* XT0siz */
+       cio_write(cio, cp->ty0, 4);             /* YT0siz */
+       cio_write(cio, image->numcomps, 2);     /* Csiz */
+       for (i = 0; i < image->numcomps; i++) {
+               cio_write(cio, image->comps[i].prec - 1 + (image->comps[i].sgnd << 7), 1);      /* Ssiz_i */
+               cio_write(cio, image->comps[i].dx, 1);  /* XRsiz_i */
+               cio_write(cio, image->comps[i].dy, 1);  /* YRsiz_i */
+       }
+       len = cio_tell(cio) - lenp;
+       cio_seek(cio, lenp);
+       cio_write(cio, len, 2);         /* Lsiz */
+       cio_seek(cio, lenp + len);
+}
+
+static void j2k_read_siz(opj_j2k_t *j2k) {
+       int len, i;
+       
+       opj_cio_t *cio = j2k->cio;
+       opj_image_t *image = j2k->image;
+       opj_cp_t *cp = j2k->cp;
+       
+       len = cio_read(cio, 2);                 /* Lsiz */
+       cio_read(cio, 2);                               /* Rsiz (capabilities) */
+       image->x1 = cio_read(cio, 4);   /* Xsiz */
+       image->y1 = cio_read(cio, 4);   /* Ysiz */
+       image->x0 = cio_read(cio, 4);   /* X0siz */
+       image->y0 = cio_read(cio, 4);   /* Y0siz */
+       cp->tdx = cio_read(cio, 4);             /* XTsiz */
+       cp->tdy = cio_read(cio, 4);             /* YTsiz */
+       cp->tx0 = cio_read(cio, 4);             /* XT0siz */
+       cp->ty0 = cio_read(cio, 4);             /* YT0siz */
+       
+       image->numcomps = cio_read(cio, 2);     /* Csiz */
+
+#ifdef USE_JPWL
+       if (j2k->cp->correct) {
+               /* if JPWL is on, we check whether TX errors have damaged
+                 too much the SIZ parameters */
+               if (!(image->x1 * image->y1)) {
+                       opj_event_msg(j2k->cinfo, EVT_ERROR,
+                               "JPWL: bad image size (%d x %d)\n",
+                               image->x1, image->y1);
+                       if (!JPWL_ASSUME || JPWL_ASSUME) {
+                               opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+                               return;
+                       }
+               }
+               if (image->numcomps != ((len - 38) / 3)) {
+                       opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
+                               "JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n",
+                               image->numcomps, ((len - 38) / 3));
+                       if (!JPWL_ASSUME) {
+                               opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+                               return;
+                       }
+                       /* we try to correct */
+                       opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n");
+                       if (image->numcomps < ((len - 38) / 3)) {
+                               len = 38 + 3 * image->numcomps;
+                               opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n",
+                                       len);                           
+                       } else {
+                               image->numcomps = ((len - 38) / 3);
+                               opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n",
+                                       image->numcomps);                               
+                       }
+               }
+
+               /* update components number in the jpwl_exp_comps filed */
+               cp->exp_comps = image->numcomps;
+       }
+#endif /* USE_JPWL */
+
+       image->comps = (opj_image_comp_t*) opj_calloc(image->numcomps, sizeof(opj_image_comp_t));
+       for (i = 0; i < image->numcomps; i++) {
+               int tmp, w, h;
+               tmp = cio_read(cio, 1);         /* Ssiz_i */
+               image->comps[i].prec = (tmp & 0x7f) + 1;
+               image->comps[i].sgnd = tmp >> 7;
+               image->comps[i].dx = cio_read(cio, 1);  /* XRsiz_i */
+               image->comps[i].dy = cio_read(cio, 1);  /* YRsiz_i */
+               
+#ifdef USE_JPWL
+               if (j2k->cp->correct) {
+               /* if JPWL is on, we check whether TX errors have damaged
+                       too much the SIZ parameters, again */
+                       if (!(image->comps[i].dx * image->comps[i].dy)) {
+                               opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
+                                       "JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n",
+                                       i, i, image->comps[i].dx, image->comps[i].dy);
+                               if (!JPWL_ASSUME) {
+                                       opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+                                       return;
+                               }
+                               /* we try to correct */
+                               opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n");
+                               if (!image->comps[i].dx) {
+                                       image->comps[i].dx = 1;
+                                       opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting XRsiz_%d to %d => HYPOTHESIS!!!\n",
+                                               i, image->comps[i].dx);
+                               }
+                               if (!image->comps[i].dy) {
+                                       image->comps[i].dy = 1;
+                                       opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting YRsiz_%d to %d => HYPOTHESIS!!!\n",
+                                               i, image->comps[i].dy);
+                               }
+                       }
+                       
+               }
+#endif /* USE_JPWL */
+
+               /* TODO: unused ? */
+               w = int_ceildiv(image->x1 - image->x0, image->comps[i].dx);
+               h = int_ceildiv(image->y1 - image->y0, image->comps[i].dy);
+
+               image->comps[i].resno_decoded = 0;      /* number of resolution decoded */
+               image->comps[i].factor = cp->reduce; /* reducing factor per component */
+       }
+       
+       cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx);
+       cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy);
+
+#ifdef USE_JPWL
+       if (j2k->cp->correct) {
+               /* if JPWL is on, we check whether TX errors have damaged
+                 too much the SIZ parameters */
+               if ((cp->tw < 1) || (cp->th < 1) || (cp->tw > cp->max_tiles) || (cp->th > cp->max_tiles)) {
+                       opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
+                               "JPWL: bad number of tiles (%d x %d)\n",
+                               cp->tw, cp->th);
+                       if (!JPWL_ASSUME) {
+                               opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+                               return;
+                       }
+                       /* we try to correct */
+                       opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n");
+                       if (cp->tw < 1) {
+                               cp->tw= 1;
+                               opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting %d tiles in x => HYPOTHESIS!!!\n",
+                                       cp->tw);
+                       }
+                       if (cp->tw > cp->max_tiles) {
+                               cp->tw= 1;
+                               opj_event_msg(j2k->cinfo, EVT_WARNING, "- too large x, increase expectance of %d\n"
+                                       "- setting %d tiles in x => HYPOTHESIS!!!\n",
+                                       cp->max_tiles, cp->tw);
+                       }
+                       if (cp->th < 1) {
+                               cp->th= 1;
+                               opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting %d tiles in y => HYPOTHESIS!!!\n",
+                                       cp->th);
+                       }
+                       if (cp->th > cp->max_tiles) {
+                               cp->th= 1;
+                               opj_event_msg(j2k->cinfo, EVT_WARNING, "- too large y, increase expectance of %d to continue\n",
+                                       "- setting %d tiles in y => HYPOTHESIS!!!\n",
+                                       cp->max_tiles, cp->th);
+                       }
+               }
+       }
+#endif /* USE_JPWL */
+
+       cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
+       cp->tileno = (int*) opj_malloc(cp->tw * cp->th * sizeof(int));
+       cp->tileno_size = 0;
+       
+#ifdef USE_JPWL
+       if (j2k->cp->correct) {
+               if (!cp->tcps) {
+                       opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
+                               "JPWL: could not alloc tcps field of cp\n");
+                       if (!JPWL_ASSUME || JPWL_ASSUME) {
+                               opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+                               return;
+                       }
+               }
+       }
+#endif /* USE_JPWL */
+
+       for (i = 0; i < cp->tw * cp->th; i++) {
+               cp->tcps[i].POC = 0;
+               cp->tcps[i].numpocs = 0;
+               cp->tcps[i].first = 1;
+       }
+       
+       /* Initialization for PPM marker */
+       cp->ppm = 0;
+       cp->ppm_data = NULL;
+       cp->ppm_data_first = NULL;
+       cp->ppm_previous = 0;
+       cp->ppm_store = 0;
+
+       j2k->default_tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
+       for (i = 0; i < cp->tw * cp->th; i++) {
+               cp->tcps[i].tccps = (opj_tccp_t*) opj_malloc(image->numcomps * sizeof(opj_tccp_t));
+       }       
+       j2k->tile_data = (unsigned char**) opj_calloc(cp->tw * cp->th, sizeof(unsigned char*));
+       j2k->tile_len = (int*) opj_calloc(cp->tw * cp->th, sizeof(int));
+       j2k->state = J2K_STATE_MH;
+
+       /* Index */
+       if (j2k->cstr_info) {
+               opj_codestream_info_t *cstr_info = j2k->cstr_info;
+               cstr_info->image_w = image->x1 - image->x0;
+               cstr_info->image_h = image->y1 - image->y0;
+               cstr_info->numcomps = image->numcomps;
+               cstr_info->tw = cp->tw;
+               cstr_info->th = cp->th;
+               cstr_info->tile_x = cp->tdx;    
+               cstr_info->tile_y = cp->tdy;    
+               cstr_info->tile_Ox = cp->tx0;   
+               cstr_info->tile_Oy = cp->ty0;                   
+               cstr_info->tile = (opj_tile_info_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tile_info_t));              
+       }
+}
+
+static void j2k_write_com(opj_j2k_t *j2k) {
+       unsigned int i;
+       int lenp, len;
+
+       if(j2k->cp->comment) {
+               opj_cio_t *cio = j2k->cio;
+               char *comment = j2k->cp->comment;
+
+               cio_write(cio, J2K_MS_COM, 2);
+               lenp = cio_tell(cio);
+               cio_skip(cio, 2);
+               cio_write(cio, 1, 2);           /* General use (IS 8859-15:1999 (Latin) values) */
+               for (i = 0; i < strlen(comment); i++) {
+                       cio_write(cio, comment[i], 1);
+               }
+               len = cio_tell(cio) - lenp;
+               cio_seek(cio, lenp);
+               cio_write(cio, len, 2);
+               cio_seek(cio, lenp + len);
+       }
+}
+
+static void j2k_read_com(opj_j2k_t *j2k) {
+       int len;
+       
+       opj_cio_t *cio = j2k->cio;
+
+       len = cio_read(cio, 2);
+       cio_skip(cio, len - 2);  
+}
+
+static void j2k_write_cox(opj_j2k_t *j2k, int compno) {
+       int i;
+
+       opj_cp_t *cp = j2k->cp;
+       opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
+       opj_tccp_t *tccp = &tcp->tccps[compno];
+       opj_cio_t *cio = j2k->cio;
+       
+       cio_write(cio, tccp->numresolutions - 1, 1);    /* SPcox (D) */
+       cio_write(cio, tccp->cblkw - 2, 1);                             /* SPcox (E) */
+       cio_write(cio, tccp->cblkh - 2, 1);                             /* SPcox (F) */
+       cio_write(cio, tccp->cblksty, 1);                               /* SPcox (G) */
+       cio_write(cio, tccp->qmfbid, 1);                                /* SPcox (H) */
+       
+       if (tccp->csty & J2K_CCP_CSTY_PRT) {
+               for (i = 0; i < tccp->numresolutions; i++) {
+                       cio_write(cio, tccp->prcw[i] + (tccp->prch[i] << 4), 1);        /* SPcox (I_i) */
+               }
+       }
+}
+
+static void j2k_read_cox(opj_j2k_t *j2k, int compno) {
+       int i;
+
+       opj_cp_t *cp = j2k->cp;
+       opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
+       opj_tccp_t *tccp = &tcp->tccps[compno];
+       opj_cio_t *cio = j2k->cio;
+
+       tccp->numresolutions = cio_read(cio, 1) + 1;    /* SPcox (D) */
+
+       // If user wants to remove more resolutions than the codestream contains, return error
+       if (cp->reduce >= tccp->numresolutions) {
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions to remove is higher than the number "
+                                       "of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno);
+               j2k->state |= J2K_STATE_ERR;
+       }
+
+       tccp->cblkw = cio_read(cio, 1) + 2;     /* SPcox (E) */
+       tccp->cblkh = cio_read(cio, 1) + 2;     /* SPcox (F) */
+       tccp->cblksty = cio_read(cio, 1);       /* SPcox (G) */
+       tccp->qmfbid = cio_read(cio, 1);        /* SPcox (H) */
+       if (tccp->csty & J2K_CP_CSTY_PRT) {
+               for (i = 0; i < tccp->numresolutions; i++) {
+                       int tmp = cio_read(cio, 1);     /* SPcox (I_i) */
+                       tccp->prcw[i] = tmp & 0xf;
+                       tccp->prch[i] = tmp >> 4;
+               }
+       }
+
+       /* INDEX >> */
+       if(j2k->cstr_info && compno == 0) {
+               for (i = 0; i < tccp->numresolutions; i++) {
+                       if (tccp->csty & J2K_CP_CSTY_PRT) {
+                               j2k->cstr_info->tile[j2k->curtileno].pdx[i] = tccp->prcw[i];
+                               j2k->cstr_info->tile[j2k->curtileno].pdy[i] = tccp->prch[i];
+                       }
+                       else {
+                               j2k->cstr_info->tile[j2k->curtileno].pdx[i] = 15;
+                               j2k->cstr_info->tile[j2k->curtileno].pdx[i] = 15;
+                       }
+               }
+       }
+       /* << INDEX */
+}
+
+static void j2k_write_cod(opj_j2k_t *j2k) {
+       opj_cp_t *cp = NULL;
+       opj_tcp_t *tcp = NULL;
+       int lenp, len;
+
+       opj_cio_t *cio = j2k->cio;
+       
+       cio_write(cio, J2K_MS_COD, 2);  /* COD */
+       
+       lenp = cio_tell(cio);
+       cio_skip(cio, 2);
+       
+       cp = j2k->cp;
+       tcp = &cp->tcps[j2k->curtileno];
+
+       cio_write(cio, tcp->csty, 1);           /* Scod */
+       cio_write(cio, tcp->prg, 1);            /* SGcod (A) */
+       cio_write(cio, tcp->numlayers, 2);      /* SGcod (B) */
+       cio_write(cio, tcp->mct, 1);            /* SGcod (C) */
+       
+       j2k_write_cox(j2k, 0);
+       len = cio_tell(cio) - lenp;
+       cio_seek(cio, lenp);
+       cio_write(cio, len, 2);         /* Lcod */
+       cio_seek(cio, lenp + len);
+}
+
+static void j2k_read_cod(opj_j2k_t *j2k) {
+       int len, i, pos;
+       
+       opj_cio_t *cio = j2k->cio;
+       opj_cp_t *cp = j2k->cp;
+       opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
+       opj_image_t *image = j2k->image;
+       
+       len = cio_read(cio, 2);                         /* Lcod */
+       tcp->csty = cio_read(cio, 1);           /* Scod */
+       tcp->prg = (OPJ_PROG_ORDER)cio_read(cio, 1);            /* SGcod (A) */
+       tcp->numlayers = cio_read(cio, 2);      /* SGcod (B) */
+       tcp->mct = cio_read(cio, 1);            /* SGcod (C) */
+       
+       pos = cio_tell(cio);
+       for (i = 0; i < image->numcomps; i++) {
+               tcp->tccps[i].csty = tcp->csty & J2K_CP_CSTY_PRT;
+               cio_seek(cio, pos);
+               j2k_read_cox(j2k, i);
+       }
+
+       /* Index */
+       if (j2k->cstr_info) {
+               opj_codestream_info_t *cstr_info = j2k->cstr_info;
+               cstr_info->prog = tcp->prg;
+               cstr_info->numlayers = tcp->numlayers;
+               cstr_info->numdecompos = (int*) opj_malloc(image->numcomps * sizeof(int));
+               for (i = 0; i < image->numcomps; i++) {
+                       cstr_info->numdecompos[i] = tcp->tccps[i].numresolutions - 1;
+               }
+       }
+}
+
+static void j2k_write_coc(opj_j2k_t *j2k, int compno) {
+       int lenp, len;
+
+       opj_cp_t *cp = j2k->cp;
+       opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
+       opj_image_t *image = j2k->image;
+       opj_cio_t *cio = j2k->cio;
+       
+       cio_write(cio, J2K_MS_COC, 2);  /* COC */
+       lenp = cio_tell(cio);
+       cio_skip(cio, 2);
+       cio_write(cio, compno, image->numcomps <= 256 ? 1 : 2); /* Ccoc */
+       cio_write(cio, tcp->tccps[compno].csty, 1);     /* Scoc */
+       j2k_write_cox(j2k, compno);
+       len = cio_tell(cio) - lenp;
+       cio_seek(cio, lenp);
+       cio_write(cio, len, 2);                 /* Lcoc */
+       cio_seek(cio, lenp + len);
+}
+
+static void j2k_read_coc(opj_j2k_t *j2k) {
+       int len, compno;
+
+       opj_cp_t *cp = j2k->cp;
+       opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
+       opj_image_t *image = j2k->image;
+       opj_cio_t *cio = j2k->cio;
+       
+       len = cio_read(cio, 2);         /* Lcoc */
+       compno = cio_read(cio, image->numcomps <= 256 ? 1 : 2); /* Ccoc */
+       tcp->tccps[compno].csty = cio_read(cio, 1);     /* Scoc */
+       j2k_read_cox(j2k, compno);
+}
+
+static void j2k_write_qcx(opj_j2k_t *j2k, int compno) {
+       int bandno, numbands;
+       int expn, mant;
+       
+       opj_cp_t *cp = j2k->cp;
+       opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
+       opj_tccp_t *tccp = &tcp->tccps[compno];
+       opj_cio_t *cio = j2k->cio;
+       
+       cio_write(cio, tccp->qntsty + (tccp->numgbits << 5), 1);        /* Sqcx */
+       numbands = tccp->qntsty == J2K_CCP_QNTSTY_SIQNT ? 1 : tccp->numresolutions * 3 - 2;
+       
+       for (bandno = 0; bandno < numbands; bandno++) {
+               expn = tccp->stepsizes[bandno].expn;
+               mant = tccp->stepsizes[bandno].mant;
+               
+               if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
+                       cio_write(cio, expn << 3, 1);   /* SPqcx_i */
+               } else {
+                       cio_write(cio, (expn << 11) + mant, 2); /* SPqcx_i */
+               }
+       }
+}
+
+static void j2k_read_qcx(opj_j2k_t *j2k, int compno, int len) {
+       int tmp;
+       int bandno, numbands;
+
+       opj_cp_t *cp = j2k->cp;
+       opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
+       opj_tccp_t *tccp = &tcp->tccps[compno];
+       opj_cio_t *cio = j2k->cio;
+
+       tmp = cio_read(cio, 1);         /* Sqcx */
+       tccp->qntsty = tmp & 0x1f;
+       tccp->numgbits = tmp >> 5;
+       numbands = (tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 
+               1 : ((tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ? len - 1 : (len - 1) / 2);
+
+#ifdef USE_JPWL
+       if (j2k->cp->correct) {
+
+               /* if JPWL is on, we check whether there are too many subbands */
+               if ((numbands < 0) || (numbands >= J2K_MAXBANDS)) {
+                       opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
+                               "JPWL: bad number of subbands in Sqcx (%d)\n",
+                               numbands);
+                       if (!JPWL_ASSUME) {
+                               opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+                               return;
+                       }
+                       /* we try to correct */
+                       numbands = 1;
+                       opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n"
+                               "- setting number of bands to %d => HYPOTHESIS!!!\n",
+                               numbands);
+               };
+
+       };
+#endif /* USE_JPWL */
+
+       for (bandno = 0; bandno < numbands; bandno++) {
+               int expn, mant;
+               if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
+                       expn = cio_read(cio, 1) >> 3;   /* SPqcx_i */
+                       mant = 0;
+               } else {
+                       tmp = cio_read(cio, 2); /* SPqcx_i */
+                       expn = tmp >> 11;
+                       mant = tmp & 0x7ff;
+               }
+               tccp->stepsizes[bandno].expn = expn;
+               tccp->stepsizes[bandno].mant = mant;
+       }
+       
+       /* Add Antonin : if scalar_derived -> compute other stepsizes */
+       if (tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
+               for (bandno = 1; bandno < J2K_MAXBANDS; bandno++) {
+                       tccp->stepsizes[bandno].expn = 
+                               ((tccp->stepsizes[0].expn) - ((bandno - 1) / 3) > 0) ? 
+                                       (tccp->stepsizes[0].expn) - ((bandno - 1) / 3) : 0;
+                       tccp->stepsizes[bandno].mant = tccp->stepsizes[0].mant;
+               }
+       }
+       /* ddA */
+}
+
+static void j2k_write_qcd(opj_j2k_t *j2k) {
+       int lenp, len;
+
+       opj_cio_t *cio = j2k->cio;
+       
+       cio_write(cio, J2K_MS_QCD, 2);  /* QCD */
+       lenp = cio_tell(cio);
+       cio_skip(cio, 2);
+       j2k_write_qcx(j2k, 0);
+       len = cio_tell(cio) - lenp;
+       cio_seek(cio, lenp);
+       cio_write(cio, len, 2);                 /* Lqcd */
+       cio_seek(cio, lenp + len);
+}
+
+static void j2k_read_qcd(opj_j2k_t *j2k) {
+       int len, i, pos;
+
+       opj_cio_t *cio = j2k->cio;
+       opj_image_t *image = j2k->image;
+       
+       len = cio_read(cio, 2);         /* Lqcd */
+       pos = cio_tell(cio);
+       for (i = 0; i < image->numcomps; i++) {
+               cio_seek(cio, pos);
+               j2k_read_qcx(j2k, i, len - 2);
+       }
+}
+
+static void j2k_write_qcc(opj_j2k_t *j2k, int compno) {
+       int lenp, len;
+
+       opj_cio_t *cio = j2k->cio;
+       
+       cio_write(cio, J2K_MS_QCC, 2);  /* QCC */
+       lenp = cio_tell(cio);
+       cio_skip(cio, 2);
+       cio_write(cio, compno, j2k->image->numcomps <= 256 ? 1 : 2);    /* Cqcc */
+       j2k_write_qcx(j2k, compno);
+       len = cio_tell(cio) - lenp;
+       cio_seek(cio, lenp);
+       cio_write(cio, len, 2);                 /* Lqcc */
+       cio_seek(cio, lenp + len);
+}
+
+static void j2k_read_qcc(opj_j2k_t *j2k) {
+       int len, compno;
+       int numcomp = j2k->image->numcomps;
+       opj_cio_t *cio = j2k->cio;
+       
+       len = cio_read(cio, 2); /* Lqcc */
+       compno = cio_read(cio, numcomp <= 256 ? 1 : 2); /* Cqcc */
+
+#ifdef USE_JPWL
+       if (j2k->cp->correct) {
+
+               static int backup_compno = 0;
+
+               /* compno is negative or larger than the number of components!!! */
+               if ((compno < 0) || (compno >= numcomp)) {
+                       opj_event_msg(j2k->cinfo, EVT_ERROR,
+                               "JPWL: bad component number in QCC (%d out of a maximum of %d)\n",
+                               compno, numcomp);
+                       if (!JPWL_ASSUME) {
+                               opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+                               return;
+                       }
+                       /* we try to correct */
+                       compno = backup_compno % numcomp;
+                       opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
+                               "- setting component number to %d\n",
+                               compno);
+               }
+
+               /* keep your private count of tiles */
+               backup_compno++;
+       };
+#endif /* USE_JPWL */
+
+       j2k_read_qcx(j2k, compno, len - 2 - (numcomp <= 256 ? 1 : 2));
+}
+
+static void j2k_write_poc(opj_j2k_t *j2k) {
+       int len, numpchgs, i;
+
+       int numcomps = j2k->image->numcomps;
+       
+       opj_cp_t *cp = j2k->cp;
+       opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
+       opj_tccp_t *tccp = &tcp->tccps[0];
+       opj_cio_t *cio = j2k->cio;
+
+       numpchgs = 1 + tcp->numpocs;
+       cio_write(cio, J2K_MS_POC, 2);  /* POC  */
+       len = 2 + (5 + 2 * (numcomps <= 256 ? 1 : 2)) * numpchgs;
+       cio_write(cio, len, 2);         /* Lpoc */
+       for (i = 0; i < numpchgs; i++) {
+               opj_poc_t *poc = &tcp->pocs[i];
+               cio_write(cio, poc->resno0, 1); /* RSpoc_i */
+               cio_write(cio, poc->compno0, (numcomps <= 256 ? 1 : 2));        /* CSpoc_i */
+               cio_write(cio, poc->layno1, 2); /* LYEpoc_i */
+               poc->layno1 = int_min(poc->layno1, tcp->numlayers);
+               cio_write(cio, poc->resno1, 1); /* REpoc_i */
+               poc->resno1 = int_min(poc->resno1, tccp->numresolutions);
+               cio_write(cio, poc->compno1, (numcomps <= 256 ? 1 : 2));        /* CEpoc_i */
+               poc->compno1 = int_min(poc->compno1, numcomps);
+               cio_write(cio, poc->prg, 1);    /* Ppoc_i */
+       }
+}
+
+static void j2k_read_poc(opj_j2k_t *j2k) {
+       int len, numpchgs, i, old_poc;
+
+       int numcomps = j2k->image->numcomps;
+       
+       opj_cp_t *cp = j2k->cp;
+       opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
+       opj_cio_t *cio = j2k->cio;
+       
+       old_poc = tcp->POC ? tcp->numpocs + 1 : 0;
+       tcp->POC = 1;
+       len = cio_read(cio, 2);         /* Lpoc */
+       numpchgs = (len - 2) / (5 + 2 * (numcomps <= 256 ? 1 : 2));
+       
+       for (i = old_poc; i < numpchgs + old_poc; i++) {
+               opj_poc_t *poc;
+               poc = &tcp->pocs[i];
+               poc->resno0 = cio_read(cio, 1); /* RSpoc_i */
+               poc->compno0 = cio_read(cio, numcomps <= 256 ? 1 : 2);  /* CSpoc_i */
+               poc->layno1 = cio_read(cio, 2);    /* LYEpoc_i */
+               poc->resno1 = cio_read(cio, 1);    /* REpoc_i */
+               poc->compno1 = int_min(
+                       cio_read(cio, numcomps <= 256 ? 1 : 2), (unsigned int) numcomps);       /* CEpoc_i */
+               poc->prg = (OPJ_PROG_ORDER)cio_read(cio, 1);    /* Ppoc_i */
+       }
+       
+       tcp->numpocs = numpchgs + old_poc - 1;
+}
+
+static void j2k_read_crg(opj_j2k_t *j2k) {
+       int len, i, Xcrg_i, Ycrg_i;
+       
+       opj_cio_t *cio = j2k->cio;
+       int numcomps = j2k->image->numcomps;
+       
+       len = cio_read(cio, 2);                 /* Lcrg */
+       for (i = 0; i < numcomps; i++) {
+               Xcrg_i = cio_read(cio, 2);      /* Xcrg_i */
+               Ycrg_i = cio_read(cio, 2);      /* Ycrg_i */
+       }
+}
+
+static void j2k_read_tlm(opj_j2k_t *j2k) {
+       int len, Ztlm, Stlm, ST, SP, tile_tlm, i;
+       long int Ttlm_i, Ptlm_i;
+
+       opj_cio_t *cio = j2k->cio;
+       
+       len = cio_read(cio, 2);         /* Ltlm */
+       Ztlm = cio_read(cio, 1);        /* Ztlm */
+       Stlm = cio_read(cio, 1);        /* Stlm */
+       ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
+       SP = (Stlm >> 6) & 0x01;
+       tile_tlm = (len - 4) / ((SP + 1) * 2 + ST);
+       for (i = 0; i < tile_tlm; i++) {
+               Ttlm_i = cio_read(cio, ST);     /* Ttlm_i */
+               Ptlm_i = cio_read(cio, SP ? 4 : 2);     /* Ptlm_i */
+       }
+}
+
+static void j2k_read_plm(opj_j2k_t *j2k) {
+       int len, i, Zplm, Nplm, add, packet_len = 0;
+       
+       opj_cio_t *cio = j2k->cio;
+
+       len = cio_read(cio, 2);         /* Lplm */
+       Zplm = cio_read(cio, 1);        /* Zplm */
+       len -= 3;
+       while (len > 0) {
+               Nplm = cio_read(cio, 4);                /* Nplm */
+               len -= 4;
+               for (i = Nplm; i > 0; i--) {
+                       add = cio_read(cio, 1);
+                       len--;
+                       packet_len = (packet_len << 7) + add;   /* Iplm_ij */
+                       if ((add & 0x80) == 0) {
+                               /* New packet */
+                               packet_len = 0;
+                       }
+                       if (len <= 0)
+                               break;
+               }
+       }
+}
+
+static void j2k_read_plt(opj_j2k_t *j2k) {
+       int len, i, Zplt, packet_len = 0, add;
+       
+       opj_cio_t *cio = j2k->cio;
+       
+       len = cio_read(cio, 2);         /* Lplt */
+       Zplt = cio_read(cio, 1);        /* Zplt */
+       for (i = len - 3; i > 0; i--) {
+               add = cio_read(cio, 1);
+               packet_len = (packet_len << 7) + add;   /* Iplt_i */
+               if ((add & 0x80) == 0) {
+                       /* New packet */
+                       packet_len = 0;
+               }
+       }
+}
+
+static void j2k_read_ppm(opj_j2k_t *j2k) {
+       int len, Z_ppm, i, j;
+       int N_ppm;
+
+       opj_cp_t *cp = j2k->cp;
+       opj_cio_t *cio = j2k->cio;
+       
+       len = cio_read(cio, 2);
+       cp->ppm = 1;
+       
+       Z_ppm = cio_read(cio, 1);       /* Z_ppm */
+       len -= 3;
+       while (len > 0) {
+               if (cp->ppm_previous == 0) {
+                       N_ppm = cio_read(cio, 4);       /* N_ppm */
+                       len -= 4;
+               } else {
+                       N_ppm = cp->ppm_previous;
+               }
+               j = cp->ppm_store;
+               if (Z_ppm == 0) {       /* First PPM marker */
+                       cp->ppm_data = (unsigned char *) opj_malloc(N_ppm * sizeof(unsigned char));
+                       cp->ppm_data_first = cp->ppm_data;
+                       cp->ppm_len = N_ppm;
+               } else {                        /* NON-first PPM marker */
+                       cp->ppm_data = (unsigned char *) opj_realloc(cp->ppm_data, (N_ppm +     cp->ppm_store) * sizeof(unsigned char));
+
+#ifdef USE_JPWL
+                       /* this memory allocation check could be done even in non-JPWL cases */
+                       if (cp->correct) {
+                               if (!cp->ppm_data) {
+                                       opj_event_msg(j2k->cinfo, EVT_ERROR,
+                                               "JPWL: failed memory allocation during PPM marker parsing (pos. %x)\n",
+                                               cio_tell(cio));
+                                       if (!JPWL_ASSUME || JPWL_ASSUME) {
+                                               opj_free(cp->ppm_data);
+                                               opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+                                               return;
+                                       }
+                               }
+                       }
+#endif
+
+                       cp->ppm_data_first = cp->ppm_data;
+                       cp->ppm_len = N_ppm + cp->ppm_store;
+               }
+               for (i = N_ppm; i > 0; i--) {   /* Read packet header */
+                       cp->ppm_data[j] = cio_read(cio, 1);
+                       j++;
+                       len--;
+                       if (len == 0)
+                               break;                  /* Case of non-finished packet header in present marker but finished in next one */
+               }
+               cp->ppm_previous = i - 1;
+               cp->ppm_store = j;
+       }
+}
+
+static void j2k_read_ppt(opj_j2k_t *j2k) {
+       int len, Z_ppt, i, j = 0;
+
+       opj_cp_t *cp = j2k->cp;
+       opj_tcp_t *tcp = cp->tcps + j2k->curtileno;
+       opj_cio_t *cio = j2k->cio;
+
+       len = cio_read(cio, 2);
+       Z_ppt = cio_read(cio, 1);
+       tcp->ppt = 1;
+       if (Z_ppt == 0) {               /* First PPT marker */
+               tcp->ppt_data = (unsigned char *) opj_malloc((len - 3) * sizeof(unsigned char));
+               tcp->ppt_data_first = tcp->ppt_data;
+               tcp->ppt_store = 0;
+               tcp->ppt_len = len - 3;
+       } else {                        /* NON-first PPT marker */
+               tcp->ppt_data = (unsigned char *) opj_realloc(tcp->ppt_data, (len - 3 + tcp->ppt_store) * sizeof(unsigned char));
+               tcp->ppt_data_first = tcp->ppt_data;
+               tcp->ppt_len = len - 3 + tcp->ppt_store;
+       }
+       j = tcp->ppt_store;
+       for (i = len - 3; i > 0; i--) {
+               tcp->ppt_data[j] = cio_read(cio, 1);
+               j++;
+       }
+       tcp->ppt_store = j;
+}
+
+static void j2k_write_tlm(opj_j2k_t *j2k){
+       int lenp;
+       opj_cio_t *cio = j2k->cio;
+       j2k->tlm_start = cio_tell(cio);
+       cio_write(cio, J2K_MS_TLM, 2);/* TLM */
+       lenp = 4 + (5*j2k->totnum_tp);
+       cio_write(cio,lenp,2);                          /* Ltlm */
+       cio_write(cio, 0,1);                                    /* Ztlm=0*/
+       cio_write(cio,80,1);                                    /* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */
+       cio_skip(cio,5*j2k->totnum_tp);
+}
+
+static void j2k_write_sot(opj_j2k_t *j2k) {
+       int lenp, len;
+
+       opj_cio_t *cio = j2k->cio;
+
+       j2k->sot_start = cio_tell(cio);
+       cio_write(cio, J2K_MS_SOT, 2);          /* SOT */
+       lenp = cio_tell(cio);
+       cio_skip(cio, 2);                                       /* Lsot (further) */
+       cio_write(cio, j2k->curtileno, 2);      /* Isot */
+       cio_skip(cio, 4);                                       /* Psot (further in j2k_write_sod) */
+       cio_write(cio, j2k->cur_tp_num , 1);    /* TPsot */
+       cio_write(cio, j2k->cur_totnum_tp[j2k->curtileno], 1);          /* TNsot */
+       len = cio_tell(cio) - lenp;
+       cio_seek(cio, lenp);
+       cio_write(cio, len, 2);                         /* Lsot */
+       cio_seek(cio, lenp + len);
+
+       /* UniPG>> */
+#ifdef USE_JPWL
+       /* update markers struct */
+       j2k_add_marker(j2k->cstr_info, J2K_MS_SOT, j2k->sot_start, len + 2);
+#endif /* USE_JPWL */
+       /* <<UniPG */
+}
+
+static void j2k_read_sot(opj_j2k_t *j2k) {
+       int len, tileno, totlen, partno, numparts, i;
+       opj_tcp_t *tcp = NULL;
+       char status = 0;
+
+       opj_cp_t *cp = j2k->cp;
+       opj_cio_t *cio = j2k->cio;
+
+       len = cio_read(cio, 2);
+       tileno = cio_read(cio, 2);
+
+#ifdef USE_JPWL
+       if (j2k->cp->correct) {
+
+               static int backup_tileno = 0;
+
+               /* tileno is negative or larger than the number of tiles!!! */
+               if ((tileno < 0) || (tileno > (cp->tw * cp->th))) {
+                       opj_event_msg(j2k->cinfo, EVT_ERROR,
+                               "JPWL: bad tile number (%d out of a maximum of %d)\n",
+                               tileno, (cp->tw * cp->th));
+                       if (!JPWL_ASSUME) {
+                               opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+                               return;
+                       }
+                       /* we try to correct */
+                       tileno = backup_tileno;
+                       opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
+                               "- setting tile number to %d\n",
+                               tileno);
+               }
+
+               /* keep your private count of tiles */
+               backup_tileno++;
+       };
+#endif /* USE_JPWL */
+       
+       if (cp->tileno_size == 0) {
+               cp->tileno[cp->tileno_size] = tileno;
+               cp->tileno_size++;
+       } else {
+               i = 0;
+               while (i < cp->tileno_size && status == 0) {
+                       status = cp->tileno[i] == tileno ? 1 : 0;
+                       i++;
+               }
+               if (status == 0) {
+                       cp->tileno[cp->tileno_size] = tileno;
+                       cp->tileno_size++;
+               }
+       }
+       
+       totlen = cio_read(cio, 4);
+
+#ifdef USE_JPWL
+       if (j2k->cp->correct) {
+
+               /* totlen is negative or larger than the bytes left!!! */
+               if ((totlen < 0) || (totlen > (cio_numbytesleft(cio) + 8))) {
+                       opj_event_msg(j2k->cinfo, EVT_ERROR,
+                               "JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
+                               totlen, cio_numbytesleft(cio) + 8);
+                       if (!JPWL_ASSUME) {
+                               opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+                               return;
+                       }
+                       /* we try to correct */
+                       totlen = 0;
+                       opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
+                               "- setting Psot to %d => assuming it is the last tile\n",
+                               totlen);
+               }
+
+       };
+#endif /* USE_JPWL */
+
+       if (!totlen)
+               totlen = cio_numbytesleft(cio) + 8;
+       
+       partno = cio_read(cio, 1);
+       numparts = cio_read(cio, 1);
+       
+       j2k->curtileno = tileno;
+       j2k->cur_tp_num = partno;
+       j2k->eot = cio_getbp(cio) - 12 + totlen;
+       j2k->state = J2K_STATE_TPH;
+       tcp = &cp->tcps[j2k->curtileno];
+
+       /* Index */
+       if (j2k->cstr_info) {
+               if (tcp->first) {
+                       if (tileno == 0) 
+                               j2k->cstr_info->main_head_end = cio_tell(cio) - 13;
+                       j2k->cstr_info->tile[tileno].tileno = tileno;
+                       j2k->cstr_info->tile[tileno].start_pos = cio_tell(cio) - 12;
+                       j2k->cstr_info->tile[tileno].end_pos = j2k->cstr_info->tile[tileno].start_pos + totlen - 1;                             
+                       j2k->cstr_info->tile[tileno].num_tps = numparts;
+                       if (numparts)
+                               j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(numparts * sizeof(opj_tp_info_t));
+                       else
+                               j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(10 * sizeof(opj_tp_info_t)); // Fixme (10)
+               }
+               else {
+                       j2k->cstr_info->tile[tileno].end_pos += totlen;
+               }               
+               j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = cio_tell(cio) - 12;
+               j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos = 
+                       j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
+       }
+       
+       if (tcp->first == 1) {          
+               /* Initialization PPT */
+               opj_tccp_t *tmp = tcp->tccps;
+               memcpy(tcp, j2k->default_tcp, sizeof(opj_tcp_t));
+               tcp->ppt = 0;
+               tcp->ppt_data = NULL;
+               tcp->ppt_data_first = NULL;
+               tcp->tccps = tmp;
+
+               for (i = 0; i < j2k->image->numcomps; i++) {
+                       tcp->tccps[i] = j2k->default_tcp->tccps[i];
+               }
+               cp->tcps[j2k->curtileno].first = 0;
+       }
+}
+
+static void j2k_write_sod(opj_j2k_t *j2k, void *tile_coder) {
+       int l, layno;
+       int totlen;
+       opj_tcp_t *tcp = NULL;
+       opj_codestream_info_t *cstr_info = NULL;
+       
+       opj_tcd_t *tcd = (opj_tcd_t*)tile_coder;        /* cast is needed because of conflicts in header inclusions */
+       opj_cp_t *cp = j2k->cp;
+       opj_cio_t *cio = j2k->cio;
+
+       tcd->tp_num = j2k->tp_num ;
+       tcd->cur_tp_num = j2k->cur_tp_num;
+       
+       cio_write(cio, J2K_MS_SOD, 2);
+       if (j2k->curtileno == 0) {
+               j2k->sod_start = cio_tell(cio) + j2k->pos_correction;
+       }
+
+       /* INDEX >> */
+       cstr_info = j2k->cstr_info;
+       if (cstr_info) {
+               if (!j2k->cur_tp_num ) {
+                       cstr_info->tile[j2k->curtileno].end_header = cio_tell(cio) + j2k->pos_correction - 1;
+                       j2k->cstr_info->tile[j2k->curtileno].tileno = j2k->curtileno;
+               }
+               else{
+                       if(cstr_info->tile[j2k->curtileno].packet[cstr_info->packno - 1].end_pos < cio_tell(cio))
+                               cstr_info->tile[j2k->curtileno].packet[cstr_info->packno].start_pos = cio_tell(cio);
+               }
+               /* UniPG>> */
+#ifdef USE_JPWL
+               /* update markers struct */
+               j2k_add_marker(j2k->cstr_info, J2K_MS_SOD, j2k->sod_start, 2);
+#endif /* USE_JPWL */
+               /* <<UniPG */
+       }
+       /* << INDEX */
+       
+       tcp = &cp->tcps[j2k->curtileno];
+       for (layno = 0; layno < tcp->numlayers; layno++) {
+               tcp->rates[layno] -= tcp->rates[layno] ? (j2k->sod_start / (cp->th * cp->tw)) : 0;
+       }
+       if(j2k->cur_tp_num == 0){
+               tcd->tcd_image->tiles->packno = 0;
+               if(cstr_info)
+                       cstr_info->packno = 0;
+       }
+       
+       l = tcd_encode_tile(tcd, j2k->curtileno, cio_getbp(cio), cio_numbytesleft(cio) - 2, cstr_info);
+       
+       /* Writing Psot in SOT marker */
+       totlen = cio_tell(cio) + l - j2k->sot_start;
+       cio_seek(cio, j2k->sot_start + 6);
+       cio_write(cio, totlen, 4);
+       cio_seek(cio, j2k->sot_start + totlen);
+       /* Writing Ttlm and Ptlm in TLM marker */
+       if(cp->cinema){
+               cio_seek(cio, j2k->tlm_start + 6 + (5*j2k->cur_tp_num));
+               cio_write(cio, j2k->curtileno, 1);
+               cio_write(cio, totlen, 4);
+       }
+       cio_seek(cio, j2k->sot_start + totlen);
+}
+
+static void j2k_read_sod(opj_j2k_t *j2k) {
+       int len, truncate = 0, i;
+       unsigned char *data = NULL, *data_ptr = NULL;
+
+       opj_cio_t *cio = j2k->cio;
+       int curtileno = j2k->curtileno;
+
+       /* Index */
+       if (j2k->cstr_info) {
+               j2k->cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_header =
+                       cio_tell(cio) + j2k->pos_correction - 1;
+               if (j2k->cur_tp_num == 0)
+                       j2k->cstr_info->tile[j2k->curtileno].end_header = cio_tell(cio) + j2k->pos_correction - 1;
+               j2k->cstr_info->packno = 0;
+       }
+       
+       len = int_min(j2k->eot - cio_getbp(cio), cio_numbytesleft(cio) + 1);
+
+       if (len == cio_numbytesleft(cio) + 1) {
+               truncate = 1;           /* Case of a truncate codestream */
+       }       
+
+       data = j2k->tile_data[curtileno];
+       data = (unsigned char*) opj_realloc(data, (j2k->tile_len[curtileno] + len) * sizeof(unsigned char));
+
+       data_ptr = data + j2k->tile_len[curtileno];
+       for (i = 0; i < len; i++) {
+               data_ptr[i] = cio_read(cio, 1);
+       }
+
+       j2k->tile_len[curtileno] += len;
+       j2k->tile_data[curtileno] = data;
+       
+       if (!truncate) {
+               j2k->state = J2K_STATE_TPHSOT;
+       } else {
+               j2k->state = J2K_STATE_NEOC;    /* RAJOUTE !! */
+       }
+       j2k->cur_tp_num++;
+}
+
+static void j2k_write_rgn(opj_j2k_t *j2k, int compno, int tileno) {
+       opj_cp_t *cp = j2k->cp;
+       opj_tcp_t *tcp = &cp->tcps[tileno];
+       opj_cio_t *cio = j2k->cio;
+       int numcomps = j2k->image->numcomps;
+       
+       cio_write(cio, J2K_MS_RGN, 2);                                          /* RGN  */
+       cio_write(cio, numcomps <= 256 ? 5 : 6, 2);                     /* Lrgn */
+       cio_write(cio, compno, numcomps <= 256 ? 1 : 2);        /* Crgn */
+       cio_write(cio, 0, 1);                                                           /* Srgn */
+       cio_write(cio, tcp->tccps[compno].roishift, 1);         /* SPrgn */
+}
+
+static void j2k_read_rgn(opj_j2k_t *j2k) {
+       int len, compno, roisty;
+
+       opj_cp_t *cp = j2k->cp;
+       opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
+       opj_cio_t *cio = j2k->cio;
+       int numcomps = j2k->image->numcomps;
+
+       len = cio_read(cio, 2);                                                                         /* Lrgn */
+       compno = cio_read(cio, numcomps <= 256 ? 1 : 2);                        /* Crgn */
+       roisty = cio_read(cio, 1);                                                                      /* Srgn */
+
+#ifdef USE_JPWL
+       if (j2k->cp->correct) {
+               /* totlen is negative or larger than the bytes left!!! */
+               if (compno >= numcomps) {
+                       opj_event_msg(j2k->cinfo, EVT_ERROR,
+                               "JPWL: bad component number in RGN (%d when there are only %d)\n",
+                               compno, numcomps);
+                       if (!JPWL_ASSUME || JPWL_ASSUME) {
+                               opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+                               return;
+                       }
+               }
+       };
+#endif /* USE_JPWL */
+
+       tcp->tccps[compno].roishift = cio_read(cio, 1);                         /* SPrgn */
+}
+
+static void j2k_write_eoc(opj_j2k_t *j2k) {
+       opj_cio_t *cio = j2k->cio;
+       /* opj_event_msg(j2k->cinfo, "%.8x: EOC\n", cio_tell(cio) + j2k->pos_correction); */
+       cio_write(cio, J2K_MS_EOC, 2);
+
+/* UniPG>> */
+#ifdef USE_JPWL
+       /* update markers struct */
+       j2k_add_marker(j2k->cstr_info, J2K_MS_EOC, cio_tell(cio) - 2, 2);
+#endif /* USE_JPWL */
+/* <<UniPG */
+}
+
+static void j2k_read_eoc(opj_j2k_t *j2k) {
+       int i, tileno;
+       bool success;
+
+       /* if packets should be decoded */
+       if (j2k->cp->limit_decoding != DECODE_ALL_BUT_PACKETS) {
+               opj_tcd_t *tcd = tcd_create(j2k->cinfo);
+               tcd_malloc_decode(tcd, j2k->image, j2k->cp);
+               for (i = 0; i < j2k->cp->tileno_size; i++) {
+                       tcd_malloc_decode_tile(tcd, j2k->image, j2k->cp, i, j2k->cstr_info);
+                       tileno = j2k->cp->tileno[i];
+                       success = tcd_decode_tile(tcd, j2k->tile_data[tileno], j2k->tile_len[tileno], tileno, j2k->cstr_info);
+                       opj_free(j2k->tile_data[tileno]);
+                       j2k->tile_data[tileno] = NULL;
+                       tcd_free_decode_tile(tcd, i);
+                       if (success == false) {
+                               j2k->state |= J2K_STATE_ERR;
+                               break;
+                       }
+               }
+               tcd_free_decode(tcd);
+               tcd_destroy(tcd);
+       }
+       /* if packets should not be decoded  */
+       else {
+               for (i = 0; i < j2k->cp->tileno_size; i++) {
+                       tileno = j2k->cp->tileno[i];
+                       opj_free(j2k->tile_data[tileno]);
+                       j2k->tile_data[tileno] = NULL;
+               }
+       }       
+       if (j2k->state & J2K_STATE_ERR)
+               j2k->state = J2K_STATE_MT + J2K_STATE_ERR;
+       else
+               j2k->state = J2K_STATE_MT; 
+}
+
+typedef struct opj_dec_mstabent {
+       /** marker value */
+       int id;
+       /** value of the state when the marker can appear */
+       int states;
+       /** action linked to the marker */
+       void (*handler) (opj_j2k_t *j2k);
+} opj_dec_mstabent_t;
+
+opj_dec_mstabent_t j2k_dec_mstab[] = {
+  {J2K_MS_SOC, J2K_STATE_MHSOC, j2k_read_soc},
+  {J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, j2k_read_sot},
+  {J2K_MS_SOD, J2K_STATE_TPH, j2k_read_sod},
+  {J2K_MS_EOC, J2K_STATE_TPHSOT, j2k_read_eoc},
+  {J2K_MS_SIZ, J2K_STATE_MHSIZ, j2k_read_siz},
+  {J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_cod},
+  {J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_coc},
+  {J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_rgn},
+  {J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_qcd},
+  {J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_qcc},
+  {J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_poc},
+  {J2K_MS_TLM, J2K_STATE_MH, j2k_read_tlm},
+  {J2K_MS_PLM, J2K_STATE_MH, j2k_read_plm},
+  {J2K_MS_PLT, J2K_STATE_TPH, j2k_read_plt},
+  {J2K_MS_PPM, J2K_STATE_MH, j2k_read_ppm},
+  {J2K_MS_PPT, J2K_STATE_TPH, j2k_read_ppt},
+  {J2K_MS_SOP, 0, 0},
+  {J2K_MS_CRG, J2K_STATE_MH, j2k_read_crg},
+  {J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_com},
+
+#ifdef USE_JPWL
+  {J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc},
+  {J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb},
+  {J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd},
+  {J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red},
+#endif /* USE_JPWL */
+#ifdef USE_JPSEC
+  {J2K_MS_SEC, J2K_STATE_MH, j2k_read_sec},
+  {J2K_MS_INSEC, 0, j2k_read_insec},
+#endif /* USE_JPSEC */
+
+  {0, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_unk}
+};
+
+static void j2k_read_unk(opj_j2k_t *j2k) {
+       opj_event_msg(j2k->cinfo, EVT_WARNING, "Unknown marker\n");
+
+#ifdef USE_JPWL
+       if (j2k->cp->correct) {
+               int m = 0, id, i;
+               int min_id = 0, min_dist = 17, cur_dist = 0, tmp_id;
+               cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
+               id = cio_read(j2k->cio, 2);
+               opj_event_msg(j2k->cinfo, EVT_ERROR,
+                       "JPWL: really don't know this marker %x\n",
+                       id);
+               if (!JPWL_ASSUME) {
+                       opj_event_msg(j2k->cinfo, EVT_ERROR,
+                               "- possible synch loss due to uncorrectable codestream errors => giving up\n");
+                       return;
+               }
+               /* OK, activate this at your own risk!!! */
+               /* we look for the marker at the minimum hamming distance from this */
+               while (j2k_dec_mstab[m].id) {
+                       
+                       /* 1's where they differ */
+                       tmp_id = j2k_dec_mstab[m].id ^ id;
+
+                       /* compute the hamming distance between our id and the current */
+                       cur_dist = 0;
+                       for (i = 0; i < 16; i++) {
+                               if ((tmp_id >> i) & 0x0001) {
+                                       cur_dist++;
+                               }
+                       }
+
+                       /* if current distance is smaller, set the minimum */
+                       if (cur_dist < min_dist) {
+                               min_dist = cur_dist;
+                               min_id = j2k_dec_mstab[m].id;
+                       }
+                       
+                       /* jump to the next marker */
+                       m++;
+               }
+
+               /* do we substitute the marker? */
+               if (min_dist < JPWL_MAXIMUM_HAMMING) {
+                       opj_event_msg(j2k->cinfo, EVT_ERROR,
+                               "- marker %x is at distance %d from the read %x\n",
+                               min_id, min_dist, id);
+                       opj_event_msg(j2k->cinfo, EVT_ERROR,
+                               "- trying to substitute in place and crossing fingers!\n");
+                       cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
+                       cio_write(j2k->cio, min_id, 2);
+
+                       /* rewind */
+                       cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
+
+               }
+
+       };
+#endif /* USE_JPWL */
+
+}
+
+/**
+Read the lookup table containing all the marker, status and action
+@param id Marker value
+*/
+static opj_dec_mstabent_t *j2k_dec_mstab_lookup(int id) {
+       opj_dec_mstabent_t *e;
+       for (e = j2k_dec_mstab; e->id != 0; e++) {
+               if (e->id == id) {
+                       break;
+               }
+       }
+       return e;
+}
+
+/* ----------------------------------------------------------------------- */
+/* J2K / JPT decoder interface                                             */
+/* ----------------------------------------------------------------------- */
+
+opj_j2k_t* j2k_create_decompress(opj_common_ptr cinfo) {
+       opj_j2k_t *j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
+       if(!j2k)
+               return NULL;
+
+       j2k->default_tcp = (opj_tcp_t*) opj_calloc(1, sizeof(opj_tcp_t));
+       if(!j2k->default_tcp) {
+               opj_free(j2k);
+               return NULL;
+       }
+
+       j2k->cinfo = cinfo;
+       j2k->tile_data = NULL;
+
+       return j2k;
+}
+
+void j2k_destroy_decompress(opj_j2k_t *j2k) {
+       int i = 0;
+
+       if(j2k->tile_len != NULL) {
+               opj_free(j2k->tile_len);
+       }
+       if(j2k->tile_data != NULL) {
+               opj_free(j2k->tile_data);
+       }
+       if(j2k->default_tcp != NULL) {
+               opj_tcp_t *default_tcp = j2k->default_tcp;
+               if(default_tcp->ppt_data_first != NULL) {
+                       opj_free(default_tcp->ppt_data_first);
+               }
+               if(j2k->default_tcp->tccps != NULL) {
+                       opj_free(j2k->default_tcp->tccps);
+               }
+               opj_free(j2k->default_tcp);
+       }
+       if(j2k->cp != NULL) {
+               opj_cp_t *cp = j2k->cp;
+               if(cp->tcps != NULL) {
+                       for(i = 0; i < cp->tw * cp->th; i++) {
+                               if(cp->tcps[i].ppt_data_first != NULL) {
+                                       opj_free(cp->tcps[i].ppt_data_first);
+                               }
+                               if(cp->tcps[i].tccps != NULL) {
+                                       opj_free(cp->tcps[i].tccps);
+                               }
+                       }
+                       opj_free(cp->tcps);
+               }
+               if(cp->ppm_data_first != NULL) {
+                       opj_free(cp->ppm_data_first);
+               }
+               if(cp->tileno != NULL) {
+                       opj_free(cp->tileno);  
+               }
+               if(cp->comment != NULL) {
+                       opj_free(cp->comment);
+               }
+
+               opj_free(cp);
+       }
+       opj_free(j2k);
+}
+
+void j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters) {
+       if(j2k && parameters) {
+               /* create and initialize the coding parameters structure */
+               opj_cp_t *cp = (opj_cp_t*) opj_calloc(1, sizeof(opj_cp_t));
+               cp->reduce = parameters->cp_reduce;     
+               cp->layer = parameters->cp_layer;
+               cp->limit_decoding = parameters->cp_limit_decoding;
+
+#ifdef USE_JPWL
+               cp->correct = parameters->jpwl_correct;
+               cp->exp_comps = parameters->jpwl_exp_comps;
+               cp->max_tiles = parameters->jpwl_max_tiles;
+#endif /* USE_JPWL */
+
+
+               /* keep a link to cp so that we can destroy it later in j2k_destroy_decompress */
+               j2k->cp = cp;
+       }
+}
+
+opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *cstr_info) {
+       opj_image_t *image = NULL;
+
+       opj_common_ptr cinfo = j2k->cinfo;      
+
+       j2k->cio = cio;
+       j2k->cstr_info = cstr_info;
+       if (cstr_info)
+               memset(cstr_info, 0, sizeof(opj_codestream_info_t));
+
+       /* create an empty image */
+       image = opj_image_create0();
+       j2k->image = image;
+
+       j2k->state = J2K_STATE_MHSOC;
+
+       for (;;) {
+               opj_dec_mstabent_t *e;
+               int id = cio_read(cio, 2);
+
+#ifdef USE_JPWL
+               /* we try to honor JPWL correction power */
+               if (j2k->cp->correct) {
+
+                       int orig_pos = cio_tell(cio);
+                       bool status;
+
+                       /* call the corrector */
+                       status = jpwl_correct(j2k);
+
+                       /* go back to where you were */
+                       cio_seek(cio, orig_pos - 2);
+
+                       /* re-read the marker */
+                       id = cio_read(cio, 2);
+
+                       /* check whether it begins with ff */
+                       if (id >> 8 != 0xff) {
+                               opj_event_msg(cinfo, EVT_ERROR,
+                                       "JPWL: possible bad marker %x at %d\n",
+                                       id, cio_tell(cio) - 2);
+                               if (!JPWL_ASSUME) {
+                                       opj_image_destroy(image);
+                                       opj_event_msg(cinfo, EVT_ERROR, "JPWL: giving up\n");
+                                       return 0;
+                               }
+                               /* we try to correct */
+                               id = id | 0xff00;
+                               cio_seek(cio, cio_tell(cio) - 2);
+                               cio_write(cio, id, 2);
+                               opj_event_msg(cinfo, EVT_WARNING, "- trying to adjust this\n"
+                                       "- setting marker to %x\n",
+                                       id);
+                       }
+
+               }
+#endif /* USE_JPWL */
+
+               if (id >> 8 != 0xff) {
+                       opj_image_destroy(image);
+                       opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
+                       return 0;
+               }
+               e = j2k_dec_mstab_lookup(id);
+               // Check if the marker is known
+               if (!(j2k->state & e->states)) {
+                       opj_image_destroy(image);
+                       opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id);
+                       return 0;
+               }
+               // Check if the decoding is limited to the main header
+               if (e->id == J2K_MS_SOT && j2k->cp->limit_decoding == LIMIT_TO_MAIN_HEADER) {
+                       opj_event_msg(cinfo, EVT_INFO, "Main Header decoded.\n");
+                       return image;
+               }               
+
+               if (e->handler) {
+                       (*e->handler)(j2k);
+               }
+               if (j2k->state & J2K_STATE_ERR) 
+                       return NULL;    
+
+               if (j2k->state == J2K_STATE_MT) {
+                       break;
+               }
+               if (j2k->state == J2K_STATE_NEOC) {
+                       break;
+               }
+       }
+       if (j2k->state == J2K_STATE_NEOC) {
+               j2k_read_eoc(j2k);
+       }
+
+       if (j2k->state != J2K_STATE_MT) {
+               opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n");
+       }
+
+       return image;
+}
+
+/*
+* Read a JPT-stream and decode file
+*
+*/
+opj_image_t* j2k_decode_jpt_stream(opj_j2k_t *j2k, opj_cio_t *cio,  opj_codestream_info_t *cstr_info) {
+       opj_image_t *image = NULL;
+       opj_jpt_msg_header_t header;
+       int position;
+
+       opj_common_ptr cinfo = j2k->cinfo;
+       
+       j2k->cio = cio;
+
+       /* create an empty image */
+       image = opj_image_create0();
+       j2k->image = image;
+
+       j2k->state = J2K_STATE_MHSOC;
+       
+       /* Initialize the header */
+       jpt_init_msg_header(&header);
+       /* Read the first header of the message */
+       jpt_read_msg_header(cinfo, cio, &header);
+       
+       position = cio_tell(cio);
+       if (header.Class_Id != 6) {     /* 6 : Main header data-bin message */
+               opj_image_destroy(image);
+               opj_event_msg(cinfo, EVT_ERROR, "[JPT-stream] : Expecting Main header first [class_Id %d] !\n", header.Class_Id);
+               return 0;
+       }
+       
+       for (;;) {
+               opj_dec_mstabent_t *e = NULL;
+               int id;
+               
+               if (!cio_numbytesleft(cio)) {
+                       j2k_read_eoc(j2k);
+                       return image;
+               }
+               /* data-bin read -> need to read a new header */
+               if ((unsigned int) (cio_tell(cio) - position) == header.Msg_length) {
+                       jpt_read_msg_header(cinfo, cio, &header);
+                       position = cio_tell(cio);
+                       if (header.Class_Id != 4) {     /* 4 : Tile data-bin message */
+                               opj_image_destroy(image);
+                               opj_event_msg(cinfo, EVT_ERROR, "[JPT-stream] : Expecting Tile info !\n");
+                               return 0;
+                       }
+               }
+               
+               id = cio_read(cio, 2);
+               if (id >> 8 != 0xff) {
+                       opj_image_destroy(image);
+                       opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
+                       return 0;
+               }
+               e = j2k_dec_mstab_lookup(id);
+               if (!(j2k->state & e->states)) {
+                       opj_image_destroy(image);
+                       opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id);
+                       return 0;
+               }
+               if (e->handler) {
+                       (*e->handler)(j2k);
+               }
+               if (j2k->state == J2K_STATE_MT) {
+                       break;
+               }
+               if (j2k->state == J2K_STATE_NEOC) {
+                       break;
+               }
+       }
+       if (j2k->state == J2K_STATE_NEOC) {
+               j2k_read_eoc(j2k);
+       }
+       
+       if (j2k->state != J2K_STATE_MT) {
+               opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n");
+       }
+
+       return image;
+}
+
+/* ----------------------------------------------------------------------- */
+/* J2K encoder interface                                                       */
+/* ----------------------------------------------------------------------- */
+
+opj_j2k_t* j2k_create_compress(opj_common_ptr cinfo) {
+       opj_j2k_t *j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
+       if(j2k) {
+               j2k->cinfo = cinfo;
+       }
+       return j2k;
+}
+
+void j2k_destroy_compress(opj_j2k_t *j2k) {
+       int tileno;
+
+       if(!j2k) return;
+       if(j2k->cp != NULL) {
+               opj_cp_t *cp = j2k->cp;
+
+               if(cp->comment) {
+                       opj_free(cp->comment);
+               }
+               if(cp->matrice) {
+                       opj_free(cp->matrice);
+               }
+               for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
+                       opj_free(cp->tcps[tileno].tccps);
+               }
+               opj_free(cp->tcps);
+               opj_free(cp);
+       }
+
+       opj_free(j2k);
+}
+
+void j2k_setup_encoder(opj_j2k_t *j2k, opj_cparameters_t *parameters, opj_image_t *image) {
+       int i, j, tileno, numpocs_tile;
+       opj_cp_t *cp = NULL;
+
+       if(!j2k || !parameters || ! image) {
+               return;
+       }
+
+       /* create and initialize the coding parameters structure */
+       cp = (opj_cp_t*) opj_calloc(1, sizeof(opj_cp_t));
+
+       /* keep a link to cp so that we can destroy it later in j2k_destroy_compress */
+       j2k->cp = cp;
+
+       /* set default values for cp */
+       cp->tw = 1;
+       cp->th = 1;
+
+       /* 
+       copy user encoding parameters 
+       */
+       cp->cinema = parameters->cp_cinema;
+       cp->max_comp_size =     parameters->max_comp_size;
+       cp->rsiz   = parameters->cp_rsiz;
+       cp->disto_alloc = parameters->cp_disto_alloc;
+       cp->fixed_alloc = parameters->cp_fixed_alloc;
+       cp->fixed_quality = parameters->cp_fixed_quality;
+
+       /* mod fixed_quality */
+       if(parameters->cp_matrice) {
+               size_t array_size = parameters->tcp_numlayers * parameters->numresolution * 3 * sizeof(int);
+               cp->matrice = (int *) opj_malloc(array_size);
+               memcpy(cp->matrice, parameters->cp_matrice, array_size);
+       }
+
+       /* tiles */
+       cp->tdx = parameters->cp_tdx;
+       cp->tdy = parameters->cp_tdy;
+
+       /* tile offset */
+       cp->tx0 = parameters->cp_tx0;
+       cp->ty0 = parameters->cp_ty0;
+
+       /* comment string */
+       if(parameters->cp_comment) {
+               cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1);
+               if(cp->comment) {
+                       strcpy(cp->comment, parameters->cp_comment);
+               }
+       }
+
+       /*
+       calculate other encoding parameters
+       */
+
+       if (parameters->tile_size_on) {
+               cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx);
+               cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy);
+       } else {
+               cp->tdx = image->x1 - cp->tx0;
+               cp->tdy = image->y1 - cp->ty0;
+       }
+
+       if(parameters->tp_on){
+               cp->tp_flag = parameters->tp_flag;
+               cp->tp_on = 1;
+       }
+       
+       cp->img_size = 0;
+       for(i=0;i<image->numcomps ;i++){
+       cp->img_size += (image->comps[i].w *image->comps[i].h * image->comps[i].prec);
+       }
+
+
+#ifdef USE_JPWL
+       /*
+       calculate JPWL encoding parameters
+       */
+
+       if (parameters->jpwl_epc_on) {
+               int i;
+
+               /* set JPWL on */
+               cp->epc_on = true;
+               cp->info_on = false; /* no informative technique */
+
+               /* set EPB on */
+               if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) {
+                       cp->epb_on = true;
+                       
+                       cp->hprot_MH = parameters->jpwl_hprot_MH;
+                       for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
+                               cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i];
+                               cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i];
+                       }
+                       /* if tile specs are not specified, copy MH specs */
+                       if (cp->hprot_TPH[0] == -1) {
+                               cp->hprot_TPH_tileno[0] = 0;
+                               cp->hprot_TPH[0] = parameters->jpwl_hprot_MH;
+                       }
+                       for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) {
+                               cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i];
+                               cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i];
+                               cp->pprot[i] = parameters->jpwl_pprot[i];
+                       }
+               }
+
+               /* set ESD writing */
+               if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) {
+                       cp->esd_on = true;
+
+                       cp->sens_size = parameters->jpwl_sens_size;
+                       cp->sens_addr = parameters->jpwl_sens_addr;
+                       cp->sens_range = parameters->jpwl_sens_range;
+
+                       cp->sens_MH = parameters->jpwl_sens_MH;
+                       for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
+                               cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i];
+                               cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i];
+                       }
+               }
+
+               /* always set RED writing to false: we are at the encoder */
+               cp->red_on = false;
+
+       } else {
+               cp->epc_on = false;
+       }
+#endif /* USE_JPWL */
+
+
+       /* initialize the mutiple tiles */
+       /* ---------------------------- */
+       cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
+
+       for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
+               opj_tcp_t *tcp = &cp->tcps[tileno];
+               tcp->numlayers = parameters->tcp_numlayers;
+               for (j = 0; j < tcp->numlayers; j++) {
+                       if(cp->cinema){
+                               if (cp->fixed_quality) {
+                                       tcp->distoratio[j] = parameters->tcp_distoratio[j];
+                               }
+                               tcp->rates[j] = parameters->tcp_rates[j];
+                       }else{
+                               if (cp->fixed_quality) {        /* add fixed_quality */
+                                       tcp->distoratio[j] = parameters->tcp_distoratio[j];
+                               } else {
+                                       tcp->rates[j] = parameters->tcp_rates[j];
+                               }
+                       }
+               }
+               tcp->csty = parameters->csty;
+               tcp->prg = parameters->prog_order;
+               tcp->mct = parameters->tcp_mct; 
+
+               numpocs_tile = 0;
+               tcp->POC = 0;
+               if (parameters->numpocs) {
+                       /* initialisation of POC */
+                       tcp->POC = 1;
+                       for (i = 0; i < parameters->numpocs; i++) {
+                               if((tileno == parameters->POC[i].tile - 1) || (parameters->POC[i].tile == -1)) {
+                                       opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];
+                                       tcp_poc->resno0         = parameters->POC[numpocs_tile].resno0;
+                                       tcp_poc->compno0        = parameters->POC[numpocs_tile].compno0;
+                                       tcp_poc->layno1         = parameters->POC[numpocs_tile].layno1;
+                                       tcp_poc->resno1         = parameters->POC[numpocs_tile].resno1;
+                                       tcp_poc->compno1        = parameters->POC[numpocs_tile].compno1;
+                                       tcp_poc->prg1           = parameters->POC[numpocs_tile].prg1;
+                                       tcp_poc->tile           = parameters->POC[numpocs_tile].tile;
+                                       numpocs_tile++;
+                               }
+                       }
+                       tcp->numpocs = numpocs_tile -1 ;
+               }else{ 
+                       tcp->numpocs = 0;
+               }
+
+               tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
+
+               for (i = 0; i < image->numcomps; i++) {
+                       opj_tccp_t *tccp = &tcp->tccps[i];
+                       tccp->csty = parameters->csty & 0x01;   /* 0 => one precinct || 1 => custom precinct  */
+                       tccp->numresolutions = parameters->numresolution;
+                       tccp->cblkw = int_floorlog2(parameters->cblockw_init);
+                       tccp->cblkh = int_floorlog2(parameters->cblockh_init);
+                       tccp->cblksty = parameters->mode;
+                       tccp->qmfbid = parameters->irreversible ? 0 : 1;
+                       tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT : J2K_CCP_QNTSTY_NOQNT;
+                       tccp->numgbits = 2;
+                       if (i == parameters->roi_compno) {
+                               tccp->roishift = parameters->roi_shift;
+                       } else {
+                               tccp->roishift = 0;
+                       }
+
+                       if(parameters->cp_cinema)
+                       {
+                               //Precinct size for lowest frequency subband=128
+                               tccp->prcw[0] = 7;
+                               tccp->prch[0] = 7;
+                               //Precinct size at all other resolutions = 256
+                               for (j = 1; j < tccp->numresolutions; j++) {
+                                       tccp->prcw[j] = 8;
+                                       tccp->prch[j] = 8;
+                               }
+                       }else{
+                               if (parameters->csty & J2K_CCP_CSTY_PRT) {
+                                       int p = 0;
+                                       for (j = tccp->numresolutions - 1; j >= 0; j--) {
+                                               if (p < parameters->res_spec) {
+                                                       
+                                                       if (parameters->prcw_init[p] < 1) {
+                                                               tccp->prcw[j] = 1;
+                                                       } else {
+                                                               tccp->prcw[j] = int_floorlog2(parameters->prcw_init[p]);
+                                                       }
+                                                       
+                                                       if (parameters->prch_init[p] < 1) {
+                                                               tccp->prch[j] = 1;
+                                                       }else {
+                                                               tccp->prch[j] = int_floorlog2(parameters->prch_init[p]);
+                                                       }
+
+                                               } else {
+                                                       int res_spec = parameters->res_spec;
+                                                       int size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1));
+                                                       int size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1));
+                                                       
+                                                       if (size_prcw < 1) {
+                                                               tccp->prcw[j] = 1;
+                                                       } else {
+                                                               tccp->prcw[j] = int_floorlog2(size_prcw);
+                                                       }
+                                                       
+                                                       if (size_prch < 1) {
+                                                               tccp->prch[j] = 1;
+                                                       } else {
+                                                               tccp->prch[j] = int_floorlog2(size_prch);
+                                                       }
+                                               }
+                                               p++;
+                                               /*printf("\nsize precinct for level %d : %d,%d\n", j,tccp->prcw[j], tccp->prch[j]); */
+                                       }       //end for
+                               } else {
+                                       for (j = 0; j < tccp->numresolutions; j++) {
+                                               tccp->prcw[j] = 15;
+                                               tccp->prch[j] = 15;
+                                       }
+                               }
+                       }
+
+                       dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec);
+               }
+       }
+}
+
+bool j2k_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
+       int tileno, compno;
+       opj_cp_t *cp = NULL;
+
+       opj_tcd_t *tcd = NULL;  /* TCD component */
+
+       j2k->cio = cio; 
+       j2k->image = image;
+
+       cp = j2k->cp;
+
+       /* j2k_dump_cp(stdout, image, cp); */
+
+       /* INDEX >> */
+       j2k->cstr_info = cstr_info;
+       if (cstr_info) {
+               int compno;
+               cstr_info->tile = (opj_tile_info_t *) opj_malloc(cp->tw * cp->th * sizeof(opj_tile_info_t));
+               cstr_info->image_w = image->x1 - image->x0;
+               cstr_info->image_h = image->y1 - image->y0;
+               cstr_info->prog = (&cp->tcps[0])->prg;
+               cstr_info->tw = cp->tw;
+               cstr_info->th = cp->th;
+               cstr_info->tile_x = cp->tdx;    /* new version parser */
+               cstr_info->tile_y = cp->tdy;    /* new version parser */
+               cstr_info->tile_Ox = cp->tx0;   /* new version parser */
+               cstr_info->tile_Oy = cp->ty0;   /* new version parser */
+               cstr_info->numcomps = image->numcomps;
+               cstr_info->numlayers = (&cp->tcps[0])->numlayers;
+               cstr_info->numdecompos = (int*) opj_malloc(image->numcomps * sizeof(int));
+               for (compno=0; compno < image->numcomps; compno++) {
+                       cstr_info->numdecompos[compno] = (&cp->tcps[0])->tccps->numresolutions - 1;
+               }
+               cstr_info->D_max = 0.0;         /* ADD Marcela */
+               cstr_info->main_head_start = cio_tell(cio); /* position of SOC */
+               cstr_info->maxmarknum = 100;
+               cstr_info->marker = (opj_marker_info_t *) opj_malloc(cstr_info->maxmarknum * sizeof(opj_marker_info_t));
+               cstr_info->marknum = 0;
+       }
+       /* << INDEX */
+
+       j2k_write_soc(j2k);
+       j2k_write_siz(j2k);
+       j2k_write_cod(j2k);
+       j2k_write_qcd(j2k);
+
+       if(cp->cinema){
+               for (compno = 1; compno < image->numcomps; compno++) {
+                       j2k_write_coc(j2k, compno);
+                       j2k_write_qcc(j2k, compno);
+               }
+       }
+
+       for (compno = 0; compno < image->numcomps; compno++) {
+               opj_tcp_t *tcp = &cp->tcps[0];
+               if (tcp->tccps[compno].roishift)
+                       j2k_write_rgn(j2k, compno, 0);
+       }
+       if (cp->comment != NULL) {
+               j2k_write_com(j2k);
+       }
+
+       j2k->totnum_tp = j2k_calculate_tp(cp,image->numcomps,image,j2k);
+       /* TLM Marker*/
+       if(cp->cinema){
+               j2k_write_tlm(j2k);
+               if (cp->cinema == CINEMA4K_24) {
+                       j2k_write_poc(j2k);
+               }
+       }
+
+       /* uncomment only for testing JPSEC marker writing */
+       /* j2k_write_sec(j2k); */
+
+       /* INDEX >> */
+       if(cstr_info) {
+               cstr_info->main_head_end = cio_tell(cio) - 1;
+       }
+       /* << INDEX */
+       /**** Main Header ENDS here ***/
+
+       /* create the tile encoder */
+       tcd = tcd_create(j2k->cinfo);
+
+       /* encode each tile */
+       for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
+               int pino;
+               int tilepartno=0;
+               /* UniPG>> */
+               int acc_pack_num = 0;
+               /* <<UniPG */
+
+
+               opj_tcp_t *tcp = &cp->tcps[tileno];
+               opj_event_msg(j2k->cinfo, EVT_INFO, "tile number %d / %d\n", tileno + 1, cp->tw * cp->th);
+
+               j2k->curtileno = tileno;
+               j2k->cur_tp_num = 0;
+               tcd->cur_totnum_tp = j2k->cur_totnum_tp[j2k->curtileno];
+               /* initialisation before tile encoding  */
+               if (tileno == 0) {
+                       tcd_malloc_encode(tcd, image, cp, j2k->curtileno);
+               } else {
+                       tcd_init_encode(tcd, image, cp, j2k->curtileno);
+               }
+
+               /* INDEX >> */
+               if(cstr_info) {
+                       cstr_info->tile[j2k->curtileno].start_pos = cio_tell(cio) + j2k->pos_correction;
+               }
+               /* << INDEX */
+
+               for(pino = 0; pino <= tcp->numpocs; pino++) {
+                       int tot_num_tp;
+                       tcd->cur_pino=pino;
+
+                       /*Get number of tile parts*/
+                       tot_num_tp = j2k_get_num_tp(cp,pino,tileno);
+                       tcd->tp_pos = cp->tp_pos;
+
+                       for(tilepartno = 0; tilepartno < tot_num_tp ; tilepartno++){
+                               j2k->tp_num = tilepartno;
+                               /* INDEX >> */
+                               if(cstr_info)
+                                       cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_start_pos =
+                                       cio_tell(cio) + j2k->pos_correction;
+                               /* << INDEX */
+                               j2k_write_sot(j2k);
+
+                               if(j2k->cur_tp_num == 0 && cp->cinema == 0){
+                                       for (compno = 1; compno < image->numcomps; compno++) {
+                                               j2k_write_coc(j2k, compno);
+                                               j2k_write_qcc(j2k, compno);
+                                       }
+                                       if (cp->tcps[tileno].numpocs) {
+                                               j2k_write_poc(j2k);
+                                       }
+                               }
+
+                               /* INDEX >> */
+                               if(cstr_info)
+                                       cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_header =
+                                       cio_tell(cio) + j2k->pos_correction + 1;
+                               /* << INDEX */
+
+                               j2k_write_sod(j2k, tcd);
+
+                               /* INDEX >> */
+                               if(cstr_info) {
+                                       cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_pos =
+                                               cio_tell(cio) + j2k->pos_correction - 1;
+                                       cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_start_pack =
+                                               acc_pack_num;
+                                       cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_numpacks =
+                                               cstr_info->packno - acc_pack_num;
+                                       acc_pack_num = cstr_info->packno;
+                               }
+                               /* << INDEX */
+
+                               j2k->cur_tp_num++;
+                       }                       
+               }
+               if(cstr_info) {
+                       cstr_info->tile[j2k->curtileno].end_pos = cio_tell(cio) + j2k->pos_correction - 1;
+               }
+
+
+               /*
+               if (tile->PPT) { // BAD PPT !!! 
+               FILE *PPT_file;
+               int i;
+               PPT_file=fopen("PPT","rb");
+               fprintf(stderr,"%c%c%c%c",255,97,tile->len_ppt/256,tile->len_ppt%256);
+               for (i=0;i<tile->len_ppt;i++) {
+               unsigned char elmt;
+               fread(&elmt, 1, 1, PPT_file);
+               fwrite(&elmt,1,1,f);
+               }
+               fclose(PPT_file);
+               unlink("PPT");
+               }
+               */
+
+       }
+
+       /* destroy the tile encoder */
+       tcd_free_encode(tcd);
+       tcd_destroy(tcd);
+
+       opj_free(j2k->cur_totnum_tp);
+
+       j2k_write_eoc(j2k);
+
+       if(cstr_info) {
+               cstr_info->codestream_size = cio_tell(cio) + j2k->pos_correction;
+               /* UniPG>> */
+               /* The following adjustment is done to adjust the codestream size */
+               /* if SOD is not at 0 in the buffer. Useful in case of JP2, where */
+               /* the first bunch of bytes is not in the codestream              */
+               cstr_info->codestream_size -= cstr_info->main_head_start;
+               /* <<UniPG */
+       }
+
+#ifdef USE_JPWL
+       /*
+       preparation of JPWL marker segments
+       */
+       if(cp->epc_on) {
+
+               /* encode according to JPWL */
+               jpwl_encode(j2k, cio, image);
+
+       }
+#endif /* USE_JPWL */
+
+       return true;
+}
+
+
+
+
+
+
diff --git a/extern/libopenjpeg/j2k.h b/extern/libopenjpeg/j2k.h
new file mode 100644 (file)
index 0000000..5599be4
--- /dev/null
@@ -0,0 +1,446 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * Copyright (c) 2006-2007, Parvatha Elangovan
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef __J2K_H
+#define __J2K_H
+/**
+@file j2k.h
+@brief The JPEG-2000 Codestream Reader/Writer (J2K)
+
+The functions in J2K.C have for goal to read/write the several parts of the codestream: markers and data.
+*/
+
+/** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
+/*@{*/
+
+#define J2K_CP_CSTY_PRT 0x01
+#define J2K_CP_CSTY_SOP 0x02
+#define J2K_CP_CSTY_EPH 0x04
+#define J2K_CCP_CSTY_PRT 0x01
+#define J2K_CCP_CBLKSTY_LAZY 0x01
+#define J2K_CCP_CBLKSTY_RESET 0x02
+#define J2K_CCP_CBLKSTY_TERMALL 0x04
+#define J2K_CCP_CBLKSTY_VSC 0x08
+#define J2K_CCP_CBLKSTY_PTERM 0x10
+#define J2K_CCP_CBLKSTY_SEGSYM 0x20
+#define J2K_CCP_QNTSTY_NOQNT 0
+#define J2K_CCP_QNTSTY_SIQNT 1
+#define J2K_CCP_QNTSTY_SEQNT 2
+
+/* ----------------------------------------------------------------------- */
+
+#define J2K_MS_SOC 0xff4f      /**< SOC marker value */
+#define J2K_MS_SOT 0xff90      /**< SOT marker value */
+#define J2K_MS_SOD 0xff93      /**< SOD marker value */
+#define J2K_MS_EOC 0xffd9      /**< EOC marker value */
+#define J2K_MS_SIZ 0xff51      /**< SIZ marker value */
+#define J2K_MS_COD 0xff52      /**< COD marker value */
+#define J2K_MS_COC 0xff53      /**< COC marker value */
+#define J2K_MS_RGN 0xff5e      /**< RGN marker value */
+#define J2K_MS_QCD 0xff5c      /**< QCD marker value */
+#define J2K_MS_QCC 0xff5d      /**< QCC marker value */
+#define J2K_MS_POC 0xff5f      /**< POC marker value */
+#define J2K_MS_TLM 0xff55      /**< TLM marker value */
+#define J2K_MS_PLM 0xff57      /**< PLM marker value */
+#define J2K_MS_PLT 0xff58      /**< PLT marker value */
+#define J2K_MS_PPM 0xff60      /**< PPM marker value */
+#define J2K_MS_PPT 0xff61      /**< PPT marker value */
+#define J2K_MS_SOP 0xff91      /**< SOP marker value */
+#define J2K_MS_EPH 0xff92      /**< EPH marker value */
+#define J2K_MS_CRG 0xff63      /**< CRG marker value */
+#define J2K_MS_COM 0xff64      /**< COM marker value */
+/* UniPG>> */
+#ifdef USE_JPWL
+#define J2K_MS_EPC 0xff68      /**< EPC marker value (Part 11: JPEG 2000 for Wireless) */
+#define J2K_MS_EPB 0xff66      /**< EPB marker value (Part 11: JPEG 2000 for Wireless) */ 
+#define J2K_MS_ESD 0xff67      /**< ESD marker value (Part 11: JPEG 2000 for Wireless) */ 
+#define J2K_MS_RED 0xff69      /**< RED marker value (Part 11: JPEG 2000 for Wireless) */
+#endif /* USE_JPWL */
+#ifdef USE_JPSEC
+#define J2K_MS_SEC 0xff65    /**< SEC marker value (Part 8: Secure JPEG 2000) */
+#define J2K_MS_INSEC 0xff94  /**< INSEC marker value (Part 8: Secure JPEG 2000) */
+#endif /* USE_JPSEC */
+/* <<UniPG */
+
+
+/* ----------------------------------------------------------------------- */
+
+/**
+Values that specify the status of the decoding process when decoding the main header. 
+These values may be combined with a | operator. 
+*/
+typedef enum J2K_STATUS {
+       J2K_STATE_MHSOC  = 0x0001, /**< a SOC marker is expected */
+       J2K_STATE_MHSIZ  = 0x0002, /**< a SIZ marker is expected */
+       J2K_STATE_MH     = 0x0004, /**< the decoding process is in the main header */
+       J2K_STATE_TPHSOT = 0x0008, /**< the decoding process is in a tile part header and expects a SOT marker */
+       J2K_STATE_TPH    = 0x0010, /**< the decoding process is in a tile part header */
+       J2K_STATE_MT     = 0x0020, /**< the EOC marker has just been read */
+       J2K_STATE_NEOC   = 0x0040, /**< the decoding process must not expect a EOC marker because the codestream is truncated */
+       J2K_STATE_ERR    = 0x0080  /**< the decoding process has encountered an error */
+} J2K_STATUS;
+
+/* ----------------------------------------------------------------------- */
+
+/** 
+T2 encoding mode 
+*/
+typedef enum T2_MODE {
+       THRESH_CALC = 0,        /** Function called in Rate allocation process*/
+       FINAL_PASS = 1          /** Function called in Tier 2 process*/
+}J2K_T2_MODE;
+
+/**
+Quantization stepsize
+*/
+typedef struct opj_stepsize {
+       /** exponent */
+       int expn;
+       /** mantissa */
+       int mant;
+} opj_stepsize_t;
+
+/**
+Tile-component coding parameters
+*/
+typedef struct opj_tccp {
+       /** coding style */
+       int csty;
+       /** number of resolutions */
+       int numresolutions;
+       /** code-blocks width */
+       int cblkw;
+       /** code-blocks height */
+       int cblkh;
+       /** code-block coding style */
+       int cblksty;
+       /** discrete wavelet transform identifier */
+       int qmfbid;
+       /** quantisation style */
+       int qntsty;
+       /** stepsizes used for quantization */
+       opj_stepsize_t stepsizes[J2K_MAXBANDS];
+       /** number of guard bits */
+       int numgbits;
+       /** Region Of Interest shift */
+       int roishift;
+       /** precinct width */
+       int prcw[J2K_MAXRLVLS];
+       /** precinct height */
+       int prch[J2K_MAXRLVLS]; 
+} opj_tccp_t;
+
+/**
+Tile coding parameters : 
+this structure is used to store coding/decoding parameters common to all
+tiles (information like COD, COC in main header)
+*/
+typedef struct opj_tcp {
+       /** 1 : first part-tile of a tile */
+       int first;
+       /** coding style */
+       int csty;
+       /** progression order */
+       OPJ_PROG_ORDER prg;
+       /** number of layers */
+       int numlayers;
+       /** multi-component transform identifier */
+       int mct;
+       /** rates of layers */
+       float rates[100];
+       /** number of progression order changes */
+       int numpocs;
+       /** indicates if a POC marker has been used O:NO, 1:YES */
+       int POC;
+       /** progression order changes */
+       opj_poc_t pocs[32];
+       /** packet header store there for futur use in t2_decode_packet */
+       unsigned char *ppt_data;
+       /** pointer remaining on the first byte of the first header if ppt is used */
+       unsigned char *ppt_data_first;
+       /** If ppt == 1 --> there was a PPT marker for the present tile */
+       int ppt;
+       /** used in case of multiple marker PPT (number of info already stored) */
+       int ppt_store;
+       /** ppmbug1 */
+       int ppt_len;
+       /** add fixed_quality */
+       float distoratio[100];
+       /** tile-component coding parameters */
+       opj_tccp_t *tccps;
+} opj_tcp_t;
+
+/**
+Coding parameters
+*/
+typedef struct opj_cp {
+       /** Digital cinema profile*/
+       OPJ_CINEMA_MODE cinema;
+       /** Maximum rate for each component. If == 0, component size limitation is not considered */
+       int max_comp_size;
+       /** Size of the image in bits*/
+       int img_size;
+       /** Rsiz*/
+       OPJ_RSIZ_CAPABILITIES rsiz;
+       /** Enabling Tile part generation*/
+       char tp_on;
+       /** Flag determining tile part generation*/
+       char tp_flag;
+       /** Position of tile part flag in progression order*/
+       int tp_pos;
+       /** allocation by rate/distortion */
+       int disto_alloc;
+       /** allocation by fixed layer */
+       int fixed_alloc;
+       /** add fixed_quality */
+       int fixed_quality;
+       /** if != 0, then original dimension divided by 2^(reduce); if == 0 or not used, image is decoded to the full resolution */
+       int reduce;
+       /** if != 0, then only the first "layer" layers are decoded; if == 0 or not used, all the quality layers are decoded */
+       int layer;
+       /** if == NO_LIMITATION, decode entire codestream; if == LIMIT_TO_MAIN_HEADER then only decode the main header */
+       OPJ_LIMIT_DECODING limit_decoding;
+       /** XTOsiz */
+       int tx0;
+       /** YTOsiz */
+       int ty0;
+       /** XTsiz */
+       int tdx;
+       /** YTsiz */
+       int tdy;
+       /** comment for coding */
+       char *comment;
+       /** number of tiles in width */
+       int tw;
+       /** number of tiles in heigth */
+       int th;
+       /** ID number of the tiles present in the codestream */
+       int *tileno;
+       /** size of the vector tileno */
+       int tileno_size;
+       /** packet header store there for futur use in t2_decode_packet */
+       unsigned char *ppm_data;
+       /** pointer remaining on the first byte of the first header if ppm is used */
+       unsigned char *ppm_data_first;
+       /** if ppm == 1 --> there was a PPM marker for the present tile */
+       int ppm;
+       /** use in case of multiple marker PPM (number of info already store) */
+       int ppm_store;
+       /** use in case of multiple marker PPM (case on non-finished previous info) */
+       int ppm_previous;
+       /** ppmbug1 */
+       int ppm_len;
+       /** tile coding parameters */
+       opj_tcp_t *tcps;
+       /** fixed layer */
+       int *matrice;
+/* UniPG>> */
+#ifdef USE_JPWL
+       /** enables writing of EPC in MH, thus activating JPWL */
+       bool epc_on;
+       /** enables writing of EPB, in case of activated JPWL */
+       bool epb_on;
+       /** enables writing of ESD, in case of activated JPWL */
+       bool esd_on;
+       /** enables writing of informative techniques of ESD, in case of activated JPWL */
+       bool info_on;
+       /** enables writing of RED, in case of activated JPWL */
+       bool red_on;
+       /** error protection method for MH (0,1,16,32,37-128) */
+       int hprot_MH;
+       /** tile number of header protection specification (>=0) */
+       int hprot_TPH_tileno[JPWL_MAX_NO_TILESPECS];
+       /** error protection methods for TPHs (0,1,16,32,37-128) */
+       int hprot_TPH[JPWL_MAX_NO_TILESPECS];
+       /** tile number of packet protection specification (>=0) */
+       int pprot_tileno[JPWL_MAX_NO_PACKSPECS];
+       /** packet number of packet protection specification (>=0) */
+       int pprot_packno[JPWL_MAX_NO_PACKSPECS];
+       /** error protection methods for packets (0,1,16,32,37-128) */
+       int pprot[JPWL_MAX_NO_PACKSPECS];
+       /** enables writing of ESD, (0/2/4 bytes) */
+       int sens_size;
+       /** sensitivity addressing size (0=auto/2/4 bytes) */
+       int sens_addr;
+       /** sensitivity range (0-3) */
+       int sens_range;
+       /** sensitivity method for MH (-1,0-7) */
+       int sens_MH;
+       /** tile number of sensitivity specification (>=0) */
+       int sens_TPH_tileno[JPWL_MAX_NO_TILESPECS];
+       /** sensitivity methods for TPHs (-1,0-7) */
+       int sens_TPH[JPWL_MAX_NO_TILESPECS];
+       /** enables JPWL correction at the decoder */
+       bool correct;
+       /** expected number of components at the decoder */
+       int exp_comps;
+       /** maximum number of tiles at the decoder */
+       int max_tiles;
+#endif /* USE_JPWL */
+/* <<UniPG */
+} opj_cp_t;
+
+/**
+JPEG-2000 codestream reader/writer
+*/
+typedef struct opj_j2k {
+       /** codec context */
+       opj_common_ptr cinfo;
+
+       /** locate in which part of the codestream the decoder is (main header, tile header, end) */
+       int state;
+       /** number of the tile curently concern by coding/decoding */
+       int curtileno;
+       /** Tile part number*/
+       int tp_num;
+       /** Tilepart number currently coding*/
+       int cur_tp_num;
+       /** Total number of tileparts of the current tile*/
+       int *cur_totnum_tp;
+       /**
+       locate the start position of the TLM marker  
+       after encoding the tilepart, a jump (in j2k_write_sod) is done to the TLM marker to store the value of its length. 
+       */
+       int tlm_start;
+       /** Total num of tile parts in whole image = num tiles* num tileparts in each tile*/
+       /** used in TLMmarker*/
+       int totnum_tp;  
+       /** 
+       locate the position of the end of the tile in the codestream, 
+       used to detect a truncated codestream (in j2k_read_sod)
+       */
+       unsigned char *eot;
+       /**
+       locate the start position of the SOT marker of the current coded tile:  
+       after encoding the tile, a jump (in j2k_write_sod) is done to the SOT marker to store the value of its length. 
+       */
+       int sot_start;
+       int sod_start;
+       /**
+       as the J2K-file is written in several parts during encoding, 
+       it enables to make the right correction in position return by cio_tell
+       */
+       int pos_correction;
+       /** array used to store the data of each tile */
+       unsigned char **tile_data;
+       /** array used to store the length of each tile */
+       int *tile_len;
+       /** 
+       decompression only : 
+       store decoding parameters common to all tiles (information like COD, COC in main header)
+       */
+       opj_tcp_t *default_tcp;
+       /** pointer to the encoded / decoded image */
+       opj_image_t *image;
+       /** pointer to the coding parameters */
+       opj_cp_t *cp;
+       /** helper used to write the index file */
+       opj_codestream_info_t *cstr_info;
+       /** pointer to the byte i/o stream */
+       opj_cio_t *cio;
+} opj_j2k_t;
+
+/** @name Exported functions */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+/**
+Creates a J2K decompression structure
+@param cinfo Codec context info
+@return Returns a handle to a J2K decompressor if successful, returns NULL otherwise
+*/
+opj_j2k_t* j2k_create_decompress(opj_common_ptr cinfo);
+/**
+Destroy a J2K decompressor handle
+@param j2k J2K decompressor handle to destroy
+*/
+void j2k_destroy_decompress(opj_j2k_t *j2k);
+/**
+Setup the decoder decoding parameters using user parameters.
+Decoding parameters are returned in j2k->cp. 
+@param j2k J2K decompressor handle
+@param parameters decompression parameters
+*/
+void j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters);
+/**
+Decode an image from a JPEG-2000 codestream
+@param j2k J2K decompressor handle
+@param cio Input buffer stream
+@param cstr_info Codestream information structure if required, NULL otherwise
+@return Returns a decoded image if successful, returns NULL otherwise
+*/
+opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *cstr_info);
+/**
+Decode an image form a JPT-stream (JPEG 2000, JPIP)
+@param j2k J2K decompressor handle
+@param cio Input buffer stream
+@param cstr_info Codestream information structure if required, NULL otherwise
+@return Returns a decoded image if successful, returns NULL otherwise
+*/
+opj_image_t* j2k_decode_jpt_stream(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *cstr_info);
+/**
+Creates a J2K compression structure
+@param cinfo Codec context info
+@return Returns a handle to a J2K compressor if successful, returns NULL otherwise
+*/
+opj_j2k_t* j2k_create_compress(opj_common_ptr cinfo);
+/**
+Destroy a J2K compressor handle
+@param j2k J2K compressor handle to destroy
+*/
+void j2k_destroy_compress(opj_j2k_t *j2k);
+/**
+Setup the encoder parameters using the current image and using user parameters. 
+Coding parameters are returned in j2k->cp. 
+@param j2k J2K compressor handle
+@param parameters compression parameters
+@param image input filled image
+*/
+void j2k_setup_encoder(opj_j2k_t *j2k, opj_cparameters_t *parameters, opj_image_t *image);
+/**
+Converts an enum type progression order to string type
+*/
+char *j2k_convert_progression_order(OPJ_PROG_ORDER prg_order);
+/**
+Encode an image into a JPEG-2000 codestream
+@param j2k J2K compressor handle
+@param cio Output buffer stream
+@param image Image to encode
+@param cstr_info Codestream information structure if required, NULL otherwise
+@return Returns true if successful, returns false otherwise
+*/
+bool j2k_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info);
+
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif /* __J2K_H */
diff --git a/extern/libopenjpeg/j2k_lib.c b/extern/libopenjpeg/j2k_lib.c
new file mode 100644 (file)
index 0000000..91aee00
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2005, Hervé 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.
+ */
+
+#ifdef WIN32
+#include <windows.h>
+#else
+#include <sys/time.h>
+#include <sys/resource.h>
+#include <sys/times.h>
+#endif /* WIN32 */
+#include "opj_includes.h"
+
+double opj_clock(void) {
+#ifdef WIN32
+       /* WIN32: use QueryPerformance (very accurate) */
+    LARGE_INTEGER freq , t ;
+    /* freq is the clock speed of the CPU */
+    QueryPerformanceFrequency(&freq) ;
+       /* cout << "freq = " << ((double) freq.QuadPart) << endl; */
+    /* t is the high resolution performance counter (see MSDN) */
+    QueryPerformanceCounter ( & t ) ;
+    return ( t.QuadPart /(double) freq.QuadPart ) ;
+#else
+       /* Unix or Linux: use resource usage */
+    struct rusage t;
+    double procTime;
+    /* (1) Get the rusage data structure at this moment (man getrusage) */
+    getrusage(0,&t);
+    /* (2) What is the elapsed time ? - CPU time = User time + System time */
+       /* (2a) Get the seconds */
+    procTime = t.ru_utime.tv_sec + t.ru_stime.tv_sec;
+    /* (2b) More precisely! Get the microseconds part ! */
+    return ( procTime + (t.ru_utime.tv_usec + t.ru_stime.tv_usec) * 1e-6 ) ;
+#endif
+}
+
diff --git a/extern/libopenjpeg/j2k_lib.h b/extern/libopenjpeg/j2k_lib.h
new file mode 100644 (file)
index 0000000..7df4d36
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2005, Hervé Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef __J2K_LIB_H
+#define __J2K_LIB_H
+/**
+@file j2k_lib.h
+@brief Internal functions
+
+The functions in J2K_LIB.C are internal utilities mainly used for timing.
+*/
+
+/** @defgroup MISC MISC - Miscellaneous internal functions */
+/*@{*/
+
+/** @name Exported functions */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+
+/**
+Difference in successive opj_clock() calls tells you the elapsed time
+@return Returns time in seconds
+*/
+double opj_clock(void);
+
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif /* __J2K_LIB_H */
+
diff --git a/extern/libopenjpeg/jp2.c b/extern/libopenjpeg/jp2.c
new file mode 100644 (file)
index 0000000..14f9493
--- /dev/null
@@ -0,0 +1,710 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "opj_includes.h"
+
+/** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */
+/*@{*/
+
+/** @name Local static functions */
+/*@{*/
+
+/**
+Read box headers
+@param cinfo Codec context info
+@param cio Input stream
+@param box
+@return Returns true if successful, returns false otherwise
+*/
+static bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box);
+/*static void jp2_write_url(opj_cio_t *cio, char *Idx_file);*/
+/**
+Read the IHDR box - Image Header box
+@param jp2 JP2 handle
+@param cio Input buffer stream
+@return Returns true if successful, returns false otherwise
+*/
+static bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio);
+static void jp2_write_ihdr(opj_jp2_t *jp2, opj_cio_t *cio);
+static void jp2_write_bpcc(opj_jp2_t *jp2, opj_cio_t *cio);
+static bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio);
+static void jp2_write_colr(opj_jp2_t *jp2, opj_cio_t *cio);
+static bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio);
+/**
+Write the FTYP box - File type box
+@param jp2 JP2 handle
+@param cio Output buffer stream
+*/
+static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio);
+/**
+Read the FTYP box - File type box
+@param jp2 JP2 handle
+@param cio Input buffer stream
+@return Returns true if successful, returns false otherwise
+*/
+static bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio);
+static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info);
+static bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset);
+static void jp2_write_jp(opj_cio_t *cio);
+/**
+Read the JP box - JPEG 2000 signature
+@param jp2 JP2 handle
+@param cio Input buffer stream
+@return Returns true if successful, returns false otherwise
+*/
+static bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio);
+/**
+Decode the structure of a JP2 file
+@param jp2 JP2 handle
+@param cio Input buffer stream
+@return Returns true if successful, returns false otherwise
+*/
+static bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio);
+
+/*@}*/
+
+/*@}*/
+
+/* ----------------------------------------------------------------------- */
+
+static bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box) {
+       box->init_pos = cio_tell(cio);
+       box->length = cio_read(cio, 4);
+       box->type = cio_read(cio, 4);
+       if (box->length == 1) {
+               if (cio_read(cio, 4) != 0) {
+                       opj_event_msg(cinfo, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n");
+                       return false;
+               }
+               box->length = cio_read(cio, 4);
+               if (box->length == 0) 
+                       box->length = cio_numbytesleft(cio) + 12;
+       }
+       else if (box->length == 0) {
+               box->length = cio_numbytesleft(cio) + 8;
+       }
+       
+       return true;
+}
+
+#if 0
+static void jp2_write_url(opj_cio_t *cio, char *Idx_file) {
+       unsigned int i;
+       opj_jp2_box_t box;
+
+       box.init_pos = cio_tell(cio);
+       cio_skip(cio, 4);
+       cio_write(cio, JP2_URL, 4);     /* DBTL */
+       cio_write(cio, 0, 1);           /* VERS */
+       cio_write(cio, 0, 3);           /* FLAG */
+
+       if(Idx_file) {
+               for (i = 0; i < strlen(Idx_file); i++) {
+                       cio_write(cio, Idx_file[i], 1);
+               }
+       }
+
+       box.length = cio_tell(cio) - box.init_pos;
+       cio_seek(cio, box.init_pos);
+       cio_write(cio, box.length, 4);  /* L */
+       cio_seek(cio, box.init_pos + box.length);
+}
+#endif
+
+static bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) {
+       opj_jp2_box_t box;
+
+       opj_common_ptr cinfo = jp2->cinfo;
+
+       jp2_read_boxhdr(cinfo, cio, &box);
+       if (JP2_IHDR != box.type) {
+               opj_event_msg(cinfo, EVT_ERROR, "Expected IHDR Marker\n");
+               return false;
+       }
+
+       jp2->h = cio_read(cio, 4);                      /* HEIGHT */
+       jp2->w = cio_read(cio, 4);                      /* WIDTH */
+       jp2->numcomps = cio_read(cio, 2);       /* NC */
+       jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
+
+       jp2->bpc = cio_read(cio, 1);            /* BPC */
+
+       jp2->C = cio_read(cio, 1);                      /* C */
+       jp2->UnkC = cio_read(cio, 1);           /* UnkC */
+       jp2->IPR = cio_read(cio, 1);            /* IPR */
+
+       if (cio_tell(cio) - box.init_pos != box.length) {
+               opj_event_msg(cinfo, EVT_ERROR, "Error with IHDR Box\n");
+               return false;
+       }
+
+       return true;
+}
+
+static void jp2_write_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) {
+       opj_jp2_box_t box;
+
+       box.init_pos = cio_tell(cio);
+       cio_skip(cio, 4);
+       cio_write(cio, JP2_IHDR, 4);            /* IHDR */
+
+       cio_write(cio, jp2->h, 4);                      /* HEIGHT */
+       cio_write(cio, jp2->w, 4);                      /* WIDTH */
+       cio_write(cio, jp2->numcomps, 2);       /* NC */
+
+       cio_write(cio, jp2->bpc, 1);            /* BPC */
+
+       cio_write(cio, jp2->C, 1);                      /* C : Always 7 */
+       cio_write(cio, jp2->UnkC, 1);           /* UnkC, colorspace unknown */
+       cio_write(cio, jp2->IPR, 1);            /* IPR, no intellectual property */
+
+       box.length = cio_tell(cio) - box.init_pos;
+       cio_seek(cio, box.init_pos);
+       cio_write(cio, box.length, 4);  /* L */
+       cio_seek(cio, box.init_pos + box.length);
+}
+
+static void jp2_write_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) {
+       unsigned int i;
+       opj_jp2_box_t box;
+
+       box.init_pos = cio_tell(cio);
+       cio_skip(cio, 4);
+       cio_write(cio, JP2_BPCC, 4);    /* BPCC */
+
+       for (i = 0; i < jp2->numcomps; i++) {
+               cio_write(cio, jp2->comps[i].bpcc, 1);
+       }
+
+       box.length = cio_tell(cio) - box.init_pos;
+       cio_seek(cio, box.init_pos);
+       cio_write(cio, box.length, 4);  /* L */
+       cio_seek(cio, box.init_pos + box.length);
+}
+
+
+static bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) {
+       unsigned int i;
+       opj_jp2_box_t box;
+
+       opj_common_ptr cinfo = jp2->cinfo;
+
+       jp2_read_boxhdr(cinfo, cio, &box);
+       if (JP2_BPCC != box.type) {
+               opj_event_msg(cinfo, EVT_ERROR, "Expected BPCC Marker\n");
+               return false;
+       }
+
+       for (i = 0; i < jp2->numcomps; i++) {
+               jp2->comps[i].bpcc = cio_read(cio, 1);
+       }
+
+       if (cio_tell(cio) - box.init_pos != box.length) {
+               opj_event_msg(cinfo, EVT_ERROR, "Error with BPCC Box\n");
+               return false;
+       }
+
+       return true;
+}
+
+static void jp2_write_colr(opj_jp2_t *jp2, opj_cio_t *cio) {
+       opj_jp2_box_t box;
+
+       box.init_pos = cio_tell(cio);
+       cio_skip(cio, 4);
+       cio_write(cio, JP2_COLR, 4);            /* COLR */
+
+       cio_write(cio, jp2->meth, 1);           /* METH */
+       cio_write(cio, jp2->precedence, 1);     /* PRECEDENCE */
+       cio_write(cio, jp2->approx, 1);         /* APPROX */
+
+       if (jp2->meth == 1) {
+               cio_write(cio, jp2->enumcs, 4); /* EnumCS */
+       } else {
+               cio_write(cio, 0, 1);                   /* PROFILE (??) */
+       }
+
+       box.length = cio_tell(cio) - box.init_pos;
+       cio_seek(cio, box.init_pos);
+       cio_write(cio, box.length, 4);  /* L */
+       cio_seek(cio, box.init_pos + box.length);
+}
+
+static bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio) {
+       opj_jp2_box_t box;
+       int skip_len;
+
+       opj_common_ptr cinfo = jp2->cinfo;
+
+       jp2_read_boxhdr(cinfo, cio, &box);
+       do {
+               if (JP2_COLR != box.type) {
+                       cio_skip(cio, box.length - 8);
+                       jp2_read_boxhdr(cinfo, cio, &box);
+               }
+       } while(JP2_COLR != box.type);
+
+       jp2->meth = cio_read(cio, 1);           /* METH */
+       jp2->precedence = cio_read(cio, 1);     /* PRECEDENCE */
+       jp2->approx = cio_read(cio, 1);         /* APPROX */
+
+       if (jp2->meth == 1) {
+               jp2->enumcs = cio_read(cio, 4); /* EnumCS */
+       } else {
+               /* skip PROFILE */
+               skip_len = box.init_pos + box.length - cio_tell(cio);
+               if (skip_len < 0) {
+                       opj_event_msg(cinfo, EVT_ERROR, "Error with JP2H box size\n");
+                       return false;
+               }
+               cio_skip(cio, box.init_pos + box.length - cio_tell(cio));
+       }
+
+       if (cio_tell(cio) - box.init_pos != box.length) {
+               opj_event_msg(cinfo, EVT_ERROR, "Error with BPCC Box\n");
+               return false;
+       }
+       return true;
+}
+
+void jp2_write_jp2h(opj_jp2_t *jp2, opj_cio_t *cio) {
+       opj_jp2_box_t box;
+
+       box.init_pos = cio_tell(cio);
+       cio_skip(cio, 4);
+       cio_write(cio, JP2_JP2H, 4);    /* JP2H */
+
+       jp2_write_ihdr(jp2, cio);
+
+       if (jp2->bpc == 255) {
+               jp2_write_bpcc(jp2, cio);
+       }
+       jp2_write_colr(jp2, cio);
+
+       box.length = cio_tell(cio) - box.init_pos;
+       cio_seek(cio, box.init_pos);
+       cio_write(cio, box.length, 4);  /* L */
+       cio_seek(cio, box.init_pos + box.length);
+}
+
+bool jp2_read_jp2h(opj_jp2_t *jp2, opj_cio_t *cio) {
+       opj_jp2_box_t box;
+       int skip_len;
+
+       opj_common_ptr cinfo = jp2->cinfo;
+
+       jp2_read_boxhdr(cinfo, cio, &box);
+       do {
+               if (JP2_JP2H != box.type) {
+                       if (box.type == JP2_JP2C) {
+                               opj_event_msg(cinfo, EVT_ERROR, "Expected JP2H Marker\n");
+                               return false;
+                       }
+                       cio_skip(cio, box.length - 8);
+                       jp2_read_boxhdr(cinfo, cio, &box);
+               }
+       } while(JP2_JP2H != box.type);
+
+       if (!jp2_read_ihdr(jp2, cio))
+               return false;
+
+       if (jp2->bpc == 255) {
+               if (!jp2_read_bpcc(jp2, cio))
+                       return false;
+       }
+       if (!jp2_read_colr(jp2, cio))
+               return false;
+
+       skip_len = box.init_pos + box.length - cio_tell(cio);
+       if (skip_len < 0) {
+               opj_event_msg(cinfo, EVT_ERROR, "Error with JP2H Box\n");
+               return false;
+       }
+       cio_skip(cio, box.init_pos + box.length - cio_tell(cio));
+
+       return true;
+}
+
+static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
+       unsigned int i;
+       opj_jp2_box_t box;
+
+       box.init_pos = cio_tell(cio);
+       cio_skip(cio, 4);
+       cio_write(cio, JP2_FTYP, 4);            /* FTYP */
+
+       cio_write(cio, jp2->brand, 4);          /* BR */
+       cio_write(cio, jp2->minversion, 4);     /* MinV */
+
+       for (i = 0; i < jp2->numcl; i++) {
+               cio_write(cio, jp2->cl[i], 4);  /* CL */
+       }
+
+       box.length = cio_tell(cio) - box.init_pos;
+       cio_seek(cio, box.init_pos);
+       cio_write(cio, box.length, 4);  /* L */
+       cio_seek(cio, box.init_pos + box.length);
+}
+
+static bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
+       int i;
+       opj_jp2_box_t box;
+
+       opj_common_ptr cinfo = jp2->cinfo;
+
+       jp2_read_boxhdr(cinfo, cio, &box);
+
+       if (JP2_FTYP != box.type) {
+               opj_event_msg(cinfo, EVT_ERROR, "Expected FTYP Marker\n");
+               return false;
+       }
+
+       jp2->brand = cio_read(cio, 4);          /* BR */
+       jp2->minversion = cio_read(cio, 4);     /* MinV */
+       jp2->numcl = (box.length - 16) / 4;
+       jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int));
+
+       for (i = 0; i < (int)jp2->numcl; i++) {
+               jp2->cl[i] = cio_read(cio, 4);  /* CLi */
+       }
+
+       if (cio_tell(cio) - box.init_pos != box.length) {
+               opj_event_msg(cinfo, EVT_ERROR, "Error with FTYP Box\n");
+               return false;
+       }
+
+       return true;
+}
+
+static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
+       unsigned int j2k_codestream_offset, j2k_codestream_length;
+       opj_jp2_box_t box;
+
+       opj_j2k_t *j2k = jp2->j2k;
+
+       box.init_pos = cio_tell(cio);
+       cio_skip(cio, 4);
+       cio_write(cio, JP2_JP2C, 4);    /* JP2C */
+
+       /* J2K encoding */
+       j2k_codestream_offset = cio_tell(cio);
+       if(!j2k_encode(j2k, cio, image, cstr_info)) {
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Failed to encode image\n");
+               return 0;
+       }
+       j2k_codestream_length = cio_tell(cio) - j2k_codestream_offset;
+
+       jp2->j2k_codestream_offset = j2k_codestream_offset;
+       jp2->j2k_codestream_length = j2k_codestream_length;
+
+       box.length = 8 + jp2->j2k_codestream_length;
+       cio_seek(cio, box.init_pos);
+       cio_write(cio, box.length, 4);  /* L */
+       cio_seek(cio, box.init_pos + box.length);
+
+       return box.length;
+}
+
+static bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset) {
+       opj_jp2_box_t box;
+
+       opj_common_ptr cinfo = jp2->cinfo;
+
+       jp2_read_boxhdr(cinfo, cio, &box);
+       do {
+               if(JP2_JP2C != box.type) {
+                       cio_skip(cio, box.length - 8);
+                       jp2_read_boxhdr(cinfo, cio, &box);
+               }
+       } while(JP2_JP2C != box.type);
+
+       *j2k_codestream_offset = cio_tell(cio);
+       *j2k_codestream_length = box.length - 8;
+
+       return true;
+}
+
+static void jp2_write_jp(opj_cio_t *cio) {
+       opj_jp2_box_t box;
+
+       box.init_pos = cio_tell(cio);
+       cio_skip(cio, 4);
+       cio_write(cio, JP2_JP, 4);              /* JP2 signature */
+       cio_write(cio, 0x0d0a870a, 4);
+
+       box.length = cio_tell(cio) - box.init_pos;
+       cio_seek(cio, box.init_pos);
+       cio_write(cio, box.length, 4);  /* L */
+       cio_seek(cio, box.init_pos + box.length);
+}
+
+static bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio) {
+       opj_jp2_box_t box;
+
+       opj_common_ptr cinfo = jp2->cinfo;
+
+       jp2_read_boxhdr(cinfo, cio, &box);
+       if (JP2_JP != box.type) {
+               opj_event_msg(cinfo, EVT_ERROR, "Expected JP Marker\n");
+               return false;
+       }
+       if (0x0d0a870a != cio_read(cio, 4)) {
+               opj_event_msg(cinfo, EVT_ERROR, "Error with JP Marker\n");
+               return false;
+       }
+       if (cio_tell(cio) - box.init_pos != box.length) {
+               opj_event_msg(cinfo, EVT_ERROR, "Error with JP Box size\n");
+               return false;
+       }
+
+       return true;
+}
+
+
+static bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio) {
+       if (!jp2_read_jp(jp2, cio))
+               return false;
+       if (!jp2_read_ftyp(jp2, cio))
+               return false;
+       if (!jp2_read_jp2h(jp2, cio))
+               return false;
+       if (!jp2_read_jp2c(jp2, cio, &jp2->j2k_codestream_length, &jp2->j2k_codestream_offset))
+               return false;
+       
+       return true;
+}
+
+/* ----------------------------------------------------------------------- */
+/* JP2 decoder interface                                             */
+/* ----------------------------------------------------------------------- */
+
+opj_jp2_t* jp2_create_decompress(opj_common_ptr cinfo) {
+       opj_jp2_t *jp2 = (opj_jp2_t*) opj_calloc(1, sizeof(opj_jp2_t));
+       if(jp2) {
+               jp2->cinfo = cinfo;
+               /* create the J2K codec */
+               jp2->j2k = j2k_create_decompress(cinfo);
+               if(jp2->j2k == NULL) {
+                       jp2_destroy_decompress(jp2);
+                       return NULL;
+               }
+       }
+       return jp2;
+}
+
+void jp2_destroy_decompress(opj_jp2_t *jp2) {
+       if(jp2) {
+               /* destroy the J2K codec */
+               j2k_destroy_decompress(jp2->j2k);
+
+               if(jp2->comps) {
+                       opj_free(jp2->comps);
+               }
+               if(jp2->cl) {
+                       opj_free(jp2->cl);
+               }
+               opj_free(jp2);
+       }
+}
+
+void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters) {
+       /* setup the J2K codec */
+       j2k_setup_decoder(jp2->j2k, parameters);
+       /* further JP2 initializations go here */
+}
+
+opj_image_t* jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio, opj_codestream_info_t *cstr_info) {
+       opj_common_ptr cinfo;
+       opj_image_t *image = NULL;
+
+       if(!jp2 || !cio) {
+               return NULL;
+       }
+
+       cinfo = jp2->cinfo;
+
+       /* JP2 decoding */
+       if(!jp2_read_struct(jp2, cio)) {
+               opj_event_msg(cinfo, EVT_ERROR, "Failed to decode jp2 structure\n");
+               return NULL;
+       }
+
+       /* J2K decoding */
+       image = j2k_decode(jp2->j2k, cio, cstr_info);
+       if(!image) {
+               opj_event_msg(cinfo, EVT_ERROR, "Failed to decode J2K image\n");
+       }
+
+       /* Set Image Color Space */
+       if (jp2->enumcs == 16)
+               image->color_space = CLRSPC_SRGB;
+       else if (jp2->enumcs == 17)
+               image->color_space = CLRSPC_GRAY;
+       else if (jp2->enumcs == 18)
+               image->color_space = CLRSPC_SYCC;
+       else
+               image->color_space = CLRSPC_UNKNOWN;
+
+       return image;
+}
+
+/* ----------------------------------------------------------------------- */
+/* JP2 encoder interface                                             */
+/* ----------------------------------------------------------------------- */
+
+opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo) {
+       opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t));
+       if(jp2) {
+               jp2->cinfo = cinfo;
+               /* create the J2K codec */
+               jp2->j2k = j2k_create_compress(cinfo);
+               if(jp2->j2k == NULL) {
+                       jp2_destroy_compress(jp2);
+                       return NULL;
+               }
+       }
+       return jp2;
+}
+
+void jp2_destroy_compress(opj_jp2_t *jp2) {
+       if(jp2) {
+               /* destroy the J2K codec */
+               j2k_destroy_compress(jp2->j2k);
+
+               if(jp2->comps) {
+                       opj_free(jp2->comps);
+               }
+               if(jp2->cl) {
+                       opj_free(jp2->cl);
+               }
+               opj_free(jp2);
+       }
+}
+
+void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_t *image) {
+       int i;
+       int depth_0, sign;
+
+       if(!jp2 || !parameters || !image)
+               return;
+
+       /* setup the J2K codec */
+       /* ------------------- */
+
+       /* Check if number of components respects standard */
+       if (image->numcomps < 1 || image->numcomps > 16384) {
+               opj_event_msg(jp2->cinfo, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n");
+               return;
+       }
+
+       j2k_setup_encoder(jp2->j2k, parameters, image);
+
+       /* setup the JP2 codec */
+       /* ------------------- */
+       
+       /* Profile box */
+
+       jp2->brand = JP2_JP2;   /* BR */
+       jp2->minversion = 0;    /* MinV */
+       jp2->numcl = 1;
+       jp2->cl = (unsigned int*) opj_malloc(jp2->numcl * sizeof(unsigned int));
+       jp2->cl[0] = JP2_JP2;   /* CL0 : JP2 */
+
+       /* Image Header box */
+
+       jp2->numcomps = image->numcomps;        /* NC */
+       jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
+       jp2->h = image->y1 - image->y0;         /* HEIGHT */
+       jp2->w = image->x1 - image->x0;         /* WIDTH */
+       /* BPC */
+       depth_0 = image->comps[0].prec - 1;
+       sign = image->comps[0].sgnd;
+       jp2->bpc = depth_0 + (sign << 7);
+       for (i = 1; i < image->numcomps; i++) {
+               int depth = image->comps[i].prec - 1;
+               sign = image->comps[i].sgnd;
+               if (depth_0 != depth)
+                       jp2->bpc = 255;
+       }
+       jp2->C = 7;                     /* C : Always 7 */
+       jp2->UnkC = 0;          /* UnkC, colorspace specified in colr box */
+       jp2->IPR = 0;           /* IPR, no intellectual property */
+       
+       /* BitsPerComponent box */
+
+       for (i = 0; i < image->numcomps; i++) {
+               jp2->comps[i].bpcc = image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
+       }
+
+       /* Colour Specification box */
+
+       if ((image->numcomps == 1 || image->numcomps == 3) && (jp2->bpc != 255)) {
+               jp2->meth = 1;  /* METH: Enumerated colourspace */
+       } else {
+               jp2->meth = 2;  /* METH: Restricted ICC profile */
+       }
+       if (jp2->meth == 1) {
+               if (image->color_space == 1)
+                       jp2->enumcs = 16;       /* sRGB as defined by IEC 61966\962\961 */
+               else if (image->color_space == 2)
+                       jp2->enumcs = 17;       /* greyscale */
+               else if (image->color_space == 3)
+                       jp2->enumcs = 18;       /* YUV */
+       } else {
+               jp2->enumcs = 0;                /* PROFILE (??) */
+       }
+       jp2->precedence = 0;    /* PRECEDENCE */
+       jp2->approx = 0;                /* APPROX */
+
+}
+
+bool jp2_encode(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
+
+       /* JP2 encoding */
+
+       /* JPEG 2000 Signature box */
+       jp2_write_jp(cio);
+       /* File Type box */
+       jp2_write_ftyp(jp2, cio);
+       /* JP2 Header box */
+       jp2_write_jp2h(jp2, cio);
+
+       /* J2K encoding */
+
+       if(!jp2_write_jp2c(jp2, cio, image, cstr_info)) {
+               opj_event_msg(jp2->cinfo, EVT_ERROR, "Failed to encode image\n");
+               return false;
+       }
+
+       return true;
+}
+
+
diff --git a/extern/libopenjpeg/jp2.h b/extern/libopenjpeg/jp2.h
new file mode 100644 (file)
index 0000000..7e363be
--- /dev/null
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * 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 __JP2_H
+#define __JP2_H
+/**
+@file jp2.h
+@brief The JPEG-2000 file format Reader/Writer (JP2)
+
+*/
+
+/** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */
+/*@{*/
+
+#define JPIP_JPIP 0x6a706970
+
+#define JP2_JP   0x6a502020            /**< JPEG 2000 signature box */
+#define JP2_FTYP 0x66747970            /**< File type box */
+#define JP2_JP2H 0x6a703268            /**< JP2 header box */
+#define JP2_IHDR 0x69686472            /**< Image header box */
+#define JP2_COLR 0x636f6c72            /**< Colour specification box */
+#define JP2_JP2C 0x6a703263            /**< Contiguous codestream box */
+#define JP2_URL  0x75726c20            /**< URL box */
+#define JP2_DBTL 0x6474626c            /**< ??? */
+#define JP2_BPCC 0x62706363            /**< Bits per component box */
+#define JP2_JP2  0x6a703220            /**< File type fields */
+
+/* ----------------------------------------------------------------------- */
+
+/** 
+JP2 component
+*/
+typedef struct opj_jp2_comps {
+  int depth;             
+  int sgnd;               
+  int bpcc;
+} opj_jp2_comps_t;
+
+/**
+JPEG-2000 file format reader/writer
+*/
+typedef struct opj_jp2 {
+       /** codec context */
+       opj_common_ptr cinfo;
+       /** handle to the J2K codec  */
+       opj_j2k_t *j2k;
+       unsigned int w;
+       unsigned int h;
+       unsigned int numcomps;
+       unsigned int bpc;
+       unsigned int C;
+       unsigned int UnkC;
+       unsigned int IPR;
+       unsigned int meth;
+       unsigned int approx;
+       unsigned int enumcs;
+       unsigned int precedence;
+       unsigned int brand;
+       unsigned int minversion;
+       unsigned int numcl;
+       unsigned int *cl;
+       opj_jp2_comps_t *comps;
+       unsigned int j2k_codestream_offset;
+       unsigned int j2k_codestream_length;
+} opj_jp2_t;
+
+/**
+JP2 Box
+*/
+typedef struct opj_jp2_box {
+  int length;
+  int type;
+  int init_pos;
+} opj_jp2_box_t;
+
+/** @name Exported functions */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+/**
+Write the JP2H box - JP2 Header box (used in MJ2)
+@param jp2 JP2 handle
+@param cio Output buffer stream
+*/
+void jp2_write_jp2h(opj_jp2_t *jp2, opj_cio_t *cio);
+/**
+Read the JP2H box - JP2 Header box (used in MJ2)
+@param jp2 JP2 handle
+@param cio Input buffer stream
+@return Returns true if successful, returns false otherwise
+*/
+bool jp2_read_jp2h(opj_jp2_t *jp2, opj_cio_t *cio);
+/**
+Creates a JP2 decompression structure
+@param cinfo Codec context info
+@return Returns a handle to a JP2 decompressor if successful, returns NULL otherwise
+*/
+opj_jp2_t* jp2_create_decompress(opj_common_ptr cinfo);
+/**
+Destroy a JP2 decompressor handle
+@param jp2 JP2 decompressor handle to destroy
+*/
+void jp2_destroy_decompress(opj_jp2_t *jp2);
+/**
+Setup the decoder decoding parameters using user parameters.
+Decoding parameters are returned in jp2->j2k->cp. 
+@param jp2 JP2 decompressor handle
+@param parameters decompression parameters
+*/
+void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters);
+/**
+Decode an image from a JPEG-2000 file stream
+@param jp2 JP2 decompressor handle
+@param cio Input buffer stream
+@param cstr_info Codestream information structure if required, NULL otherwise
+@return Returns a decoded image if successful, returns NULL otherwise
+*/
+opj_image_t* jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio, opj_codestream_info_t *cstr_info);
+/**
+Creates a JP2 compression structure
+@param cinfo Codec context info
+@return Returns a handle to a JP2 compressor if successful, returns NULL otherwise
+*/
+opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo);
+/**
+Destroy a JP2 compressor handle
+@param jp2 JP2 compressor handle to destroy
+*/
+void jp2_destroy_compress(opj_jp2_t *jp2);
+/**
+Setup the encoder parameters using the current image and using user parameters. 
+Coding parameters are returned in jp2->j2k->cp. 
+@param jp2 JP2 compressor handle
+@param parameters compression parameters
+@param image input filled image
+*/
+void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_t *image);
+/**
+Encode an image into a JPEG-2000 file stream
+@param jp2 JP2 compressor handle
+@param cio Output buffer stream
+@param image Image to encode
+@param cstr_info Codestream information structure if required, NULL otherwise
+@return Returns true if successful, returns false otherwise
+*/
+bool jp2_encode(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info);
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif /* __JP2_H */
+
diff --git a/extern/libopenjpeg/jpt.c b/extern/libopenjpeg/jpt.c
new file mode 100644 (file)
index 0000000..a2566ea
--- /dev/null
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "opj_includes.h"
+
+/*
+ * Read the information contains in VBAS [JPP/JPT stream message header]
+ * Store information (7 bits) in value
+ *
+ */
+unsigned int jpt_read_VBAS_info(opj_cio_t *cio, unsigned int value) {
+       unsigned char elmt;
+
+       elmt = cio_read(cio, 1);
+       while ((elmt >> 7) == 1) {
+               value = (value << 7);
+               value |= (elmt & 0x7f);
+               elmt = cio_read(cio, 1);
+       }
+       value = (value << 7);
+       value |= (elmt & 0x7f);
+
+       return value;
+}
+
+/*
+ * Initialize the value of the message header structure 
+ *
+ */
+void jpt_init_msg_header(opj_jpt_msg_header_t * header) {
+       header->Id = 0;         /* In-class Identifier    */
+       header->last_byte = 0;  /* Last byte information  */
+       header->Class_Id = 0;           /* Class Identifier       */
+       header->CSn_Id = 0;             /* CSn : index identifier */
+       header->Msg_offset = 0; /* Message offset         */
+       header->Msg_length = 0; /* Message length         */
+       header->Layer_nb = 0;           /* Auxiliary for JPP case */
+}
+
+/*
+ * Re-initialize the value of the message header structure
+ *
+ * Only parameters always present in message header
+ *
+ */
+void jpt_reinit_msg_header(opj_jpt_msg_header_t * header) {
+       header->Id = 0;         /* In-class Identifier    */
+       header->last_byte = 0;  /* Last byte information  */
+       header->Msg_offset = 0; /* Message offset         */
+       header->Msg_length = 0; /* Message length         */
+}
+
+/*
+ * Read the message header for a JPP/JPT - stream
+ *
+ */
+void jpt_read_msg_header(opj_common_ptr cinfo, opj_cio_t *cio, opj_jpt_msg_header_t *header) {
+       unsigned char elmt, Class = 0, CSn = 0;
+       jpt_reinit_msg_header(header);
+
+       /* ------------- */
+       /* VBAS : Bin-ID */
+       /* ------------- */
+       elmt = cio_read(cio, 1);
+
+       /* See for Class and CSn */
+       switch ((elmt >> 5) & 0x03) {
+               case 0:
+                       opj_event_msg(cinfo, EVT_ERROR, "Forbidden value encounter in message header !!\n");
+                       break;
+               case 1:
+                       Class = 0;
+                       CSn = 0;
+                       break;
+               case 2:
+                       Class = 1;
+                       CSn = 0;
+                       break;
+               case 3:
+                       Class = 1;
+                       CSn = 1;
+                       break;
+               default:
+                       break;
+       }
+
+       /* see information on bits 'c' [p 10 : A.2.1 general, ISO/IEC FCD 15444-9] */
+       if (((elmt >> 4) & 0x01) == 1)
+               header->last_byte = 1;
+
+       /* In-class identifier */
+       header->Id |= (elmt & 0x0f);
+       if ((elmt >> 7) == 1)
+               header->Id = jpt_read_VBAS_info(cio, header->Id);
+
+       /* ------------ */
+       /* VBAS : Class */
+       /* ------------ */
+       if (Class == 1) {
+               header->Class_Id = 0;
+               header->Class_Id = jpt_read_VBAS_info(cio, header->Class_Id);
+       }
+
+       /* ---------- */
+       /* VBAS : CSn */
+       /* ---------- */
+       if (CSn == 1) {
+               header->CSn_Id = 0;
+               header->CSn_Id = jpt_read_VBAS_info(cio, header->CSn_Id);
+       }
+
+       /* ----------------- */
+       /* VBAS : Msg_offset */
+       /* ----------------- */
+       header->Msg_offset = jpt_read_VBAS_info(cio, header->Msg_offset);
+
+       /* ----------------- */
+       /* VBAS : Msg_length */
+       /* ----------------- */
+       header->Msg_length = jpt_read_VBAS_info(cio, header->Msg_length);
+
+       /* ---------- */
+       /* VBAS : Aux */
+       /* ---------- */
+       if ((header->Class_Id & 0x01) == 1) {
+               header->Layer_nb = 0;
+               header->Layer_nb = jpt_read_VBAS_info(cio, header->Layer_nb);
+       }
+}
diff --git a/extern/libopenjpeg/jpt.h b/extern/libopenjpeg/jpt.h
new file mode 100644 (file)
index 0000000..eb01f98
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * 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 __JPT_H
+#define __JPT_H
+/**
+@file jpt.h
+@brief JPT-stream reader (JPEG 2000, JPIP)
+
+JPT-stream functions are implemented in J2K.C. 
+*/
+
+/**
+Message Header JPT stream structure
+*/
+typedef struct opj_jpt_msg_header {
+       /** In-class Identifier */
+       unsigned int Id;
+       /** Last byte information */
+       unsigned int last_byte; 
+       /** Class Identifier */
+       unsigned int Class_Id;  
+       /** CSn : index identifier */
+       unsigned int CSn_Id;
+       /** Message offset */
+       unsigned int Msg_offset;
+       /** Message length */
+       unsigned int Msg_length;
+       /** Auxiliary for JPP case */
+       unsigned int Layer_nb;
+} opj_jpt_msg_header_t;
+
+/* ----------------------------------------------------------------------- */
+
+/**
+Initialize the value of the message header structure 
+@param header Message header structure
+*/
+void jpt_init_msg_header(opj_jpt_msg_header_t * header);
+
+/**
+Read the message header for a JPP/JPT - stream
+@param cinfo Codec context info
+@param cio CIO handle
+@param header Message header structure
+*/
+void jpt_read_msg_header(opj_common_ptr cinfo, opj_cio_t *cio, opj_jpt_msg_header_t *header);
+
+#endif
diff --git a/extern/libopenjpeg/license.txt b/extern/libopenjpeg/license.txt
new file mode 100644 (file)
index 0000000..d1e5b6a
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
\ No newline at end of file
diff --git a/extern/libopenjpeg/mct.c b/extern/libopenjpeg/mct.c
new file mode 100644 (file)
index 0000000..ca21744
--- /dev/null
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "opj_includes.h"
+
+/* <summary> */
+/* This table contains the norms of the basis function of the reversible MCT. */
+/* </summary> */
+static const double mct_norms[3] = { 1.732, .8292, .8292 };
+
+/* <summary> */
+/* This table contains the norms of the basis function of the irreversible MCT. */
+/* </summary> */
+static const double mct_norms_real[3] = { 1.732, 1.805, 1.573 };
+
+/* <summary> */
+/* Foward reversible MCT. */
+/* </summary> */
+void mct_encode(
+               int* restrict c0,
+               int* restrict c1,
+               int* restrict c2,
+               int n)
+{
+       int i;
+       for(i = 0; i < n; ++i) {
+               int r = c0[i];
+               int g = c1[i];
+               int b = c2[i];
+               int y = (r + (g * 2) + b) >> 2;
+               int u = b - g;
+               int v = r - g;
+               c0[i] = y;
+               c1[i] = u;
+               c2[i] = v;
+       }
+}
+
+/* <summary> */
+/* Inverse reversible MCT. */
+/* </summary> */
+void mct_decode(
+               int* restrict c0,
+               int* restrict c1, 
+               int* restrict c2, 
+               int n)
+{
+       int i;
+       for (i = 0; i < n; ++i) {
+               int y = c0[i];
+               int u = c1[i];
+               int v = c2[i];
+               int g = y - ((u + v) >> 2);
+               int r = v + g;
+               int b = u + g;
+               c0[i] = r;
+               c1[i] = g;
+               c2[i] = b;
+       }
+}
+
+/* <summary> */
+/* Get norm of basis function of reversible MCT. */
+/* </summary> */
+double mct_getnorm(int compno) {
+       return mct_norms[compno];
+}
+
+/* <summary> */
+/* Foward irreversible MCT. */
+/* </summary> */
+void mct_encode_real(
+               int* restrict c0,
+               int* restrict c1,
+               int* restrict c2,
+               int n)
+{
+       int i;
+       for(i = 0; i < n; ++i) {
+               int r = c0[i];
+               int g = c1[i];
+               int b = c2[i];
+               int y =  fix_mul(r, 2449) + fix_mul(g, 4809) + fix_mul(b, 934);
+               int u = -fix_mul(r, 1382) - fix_mul(g, 2714) + fix_mul(b, 4096);
+               int v =  fix_mul(r, 4096) - fix_mul(g, 3430) - fix_mul(b, 666);
+               c0[i] = y;
+               c1[i] = u;
+               c2[i] = v;
+       }
+}
+
+/* <summary> */
+/* Inverse irreversible MCT. */
+/* </summary> */
+void mct_decode_real(
+               float* restrict c0,
+               float* restrict c1,
+               float* restrict c2,
+               int n)
+{
+       int i;
+       for(i = 0; i < n; ++i) {
+               float y = c0[i];
+               float u = c1[i];
+               float v = c2[i];
+               float r = y + (v * 1.402f);
+               float g = y - (u * 0.34413f) - (v * (0.71414f));
+               float b = y + (u * 1.772f);
+               c0[i] = r;
+               c1[i] = g;
+               c2[i] = b;
+       }
+}
+
+/* <summary> */
+/* Get norm of basis function of irreversible MCT. */
+/* </summary> */
+double mct_getnorm_real(int compno) {
+       return mct_norms_real[compno];
+}
diff --git a/extern/libopenjpeg/mct.h b/extern/libopenjpeg/mct.h
new file mode 100644 (file)
index 0000000..84e3f8a
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __MCT_H
+#define __MCT_H
+/**
+@file mct.h
+@brief Implementation of a multi-component transforms (MCT)
+
+The functions in MCT.C have for goal to realize reversible and irreversible multicomponent
+transform. The functions in MCT.C are used by some function in TCD.C.
+*/
+
+/** @defgroup MCT MCT - Implementation of a multi-component transform */
+/*@{*/
+
+/** @name Exported functions */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+/**
+Apply a reversible multi-component transform to an image
+@param c0 Samples for red component
+@param c1 Samples for green component
+@param c2 Samples blue component
+@param n Number of samples for each component
+*/
+void mct_encode(int *c0, int *c1, int *c2, int n);
+/**
+Apply a reversible multi-component inverse transform to an image
+@param c0 Samples for luminance component
+@param c1 Samples for red chrominance component
+@param c2 Samples for blue chrominance component
+@param n Number of samples for each component
+*/
+void mct_decode(int *c0, int *c1, int *c2, int n);
+/**
+Get norm of the basis function used for the reversible multi-component transform
+@param compno Number of the component (0->Y, 1->U, 2->V)
+@return 
+*/
+double mct_getnorm(int compno);
+
+/**
+Apply an irreversible multi-component transform to an image
+@param c0 Samples for red component
+@param c1 Samples for green component
+@param c2 Samples blue component
+@param n Number of samples for each component
+*/
+void mct_encode_real(int *c0, int *c1, int *c2, int n);
+/**
+Apply an irreversible multi-component inverse transform to an image
+@param c0 Samples for luminance component
+@param c1 Samples for red chrominance component
+@param c2 Samples for blue chrominance component
+@param n Number of samples for each component
+*/
+void mct_decode_real(float* c0, float* c1, float* c2, int n);
+/**
+Get norm of the basis function used for the irreversible multi-component transform
+@param compno Number of the component (0->Y, 1->U, 2->V)
+@return 
+*/
+double mct_getnorm_real(int compno);
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif /* __MCT_H */
diff --git a/extern/libopenjpeg/mqc.c b/extern/libopenjpeg/mqc.c
new file mode 100644 (file)
index 0000000..9aa9d2c
--- /dev/null
@@ -0,0 +1,538 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "opj_includes.h"
+
+/** @defgroup MQC MQC - Implementation of an MQ-Coder */
+/*@{*/
+
+/** @name Local static functions */
+/*@{*/
+
+/**
+Output a byte, doing bit-stuffing if necessary.
+After a 0xff byte, the next byte must be smaller than 0x90.
+@param mqc MQC handle
+*/
+static void mqc_byteout(opj_mqc_t *mqc);
+/**
+Renormalize mqc->a and mqc->c while encoding, so that mqc->a stays between 0x8000 and 0x10000
+@param mqc MQC handle
+*/
+static void mqc_renorme(opj_mqc_t *mqc);
+/**
+Encode the most probable symbol
+@param mqc MQC handle
+*/
+static void mqc_codemps(opj_mqc_t *mqc);
+/**
+Encode the most least symbol
+@param mqc MQC handle
+*/
+static void mqc_codelps(opj_mqc_t *mqc);
+/**
+Fill mqc->c with 1's for flushing
+@param mqc MQC handle
+*/
+static void mqc_setbits(opj_mqc_t *mqc);
+/**
+FIXME: documentation ???
+@param mqc MQC handle
+@return 
+*/
+static int mqc_mpsexchange(opj_mqc_t *mqc);
+/**
+FIXME: documentation ???
+@param mqc MQC handle
+@return 
+*/
+static int mqc_lpsexchange(opj_mqc_t *mqc);
+/**
+Input a byte
+@param mqc MQC handle
+*/
+static void mqc_bytein(opj_mqc_t *mqc);
+/**
+Renormalize mqc->a and mqc->c while decoding
+@param mqc MQC handle
+*/
+static void mqc_renormd(opj_mqc_t *mqc);
+
+/*@}*/
+
+/*@}*/
+
+/* <summary> */
+/* This array defines all the possible states for a context. */
+/* </summary> */
+static opj_mqc_state_t mqc_states[47 * 2] = {
+       {0x5601, 0, &mqc_states[2], &mqc_states[3]},
+       {0x5601, 1, &mqc_states[3], &mqc_states[2]},
+       {0x3401, 0, &mqc_states[4], &mqc_states[12]},
+       {0x3401, 1, &mqc_states[5], &mqc_states[13]},
+       {0x1801, 0, &mqc_states[6], &mqc_states[18]},
+       {0x1801, 1, &mqc_states[7], &mqc_states[19]},
+       {0x0ac1, 0, &mqc_states[8], &mqc_states[24]},
+       {0x0ac1, 1, &mqc_states[9], &mqc_states[25]},
+       {0x0521, 0, &mqc_states[10], &mqc_states[58]},
+       {0x0521, 1, &mqc_states[11], &mqc_states[59]},
+       {0x0221, 0, &mqc_states[76], &mqc_states[66]},
+       {0x0221, 1, &mqc_states[77], &mqc_states[67]},
+       {0x5601, 0, &mqc_states[14], &mqc_states[13]},
+       {0x5601, 1, &mqc_states[15], &mqc_states[12]},
+       {0x5401, 0, &mqc_states[16], &mqc_states[28]},
+       {0x5401, 1, &mqc_states[17], &mqc_states[29]},
+       {0x4801, 0, &mqc_states[18], &mqc_states[28]},
+       {0x4801, 1, &mqc_states[19], &mqc_states[29]},
+       {0x3801, 0, &mqc_states[20], &mqc_states[28]},
+       {0x3801, 1, &mqc_states[21], &mqc_states[29]},
+       {0x3001, 0, &mqc_states[22], &mqc_states[34]},
+       {0x3001, 1, &mqc_states[23], &mqc_states[35]},
+       {0x2401, 0, &mqc_states[24], &mqc_states[36]},
+       {0x2401, 1, &mqc_states[25], &mqc_states[37]},
+       {0x1c01, 0, &mqc_states[26], &mqc_states[40]},
+       {0x1c01, 1, &mqc_states[27], &mqc_states[41]},
+       {0x1601, 0, &mqc_states[58], &mqc_states[42]},
+       {0x1601, 1, &mqc_states[59], &mqc_states[43]},
+       {0x5601, 0, &mqc_states[30], &mqc_states[29]},
+       {0x5601, 1, &mqc_states[31], &mqc_states[28]},
+       {0x5401, 0, &mqc_states[32], &mqc_states[28]},
+       {0x5401, 1, &mqc_states[33], &mqc_states[29]},
+       {0x5101, 0, &mqc_states[34], &mqc_states[30]},
+       {0x5101, 1, &mqc_states[35], &mqc_states[31]},
+       {0x4801, 0, &mqc_states[36], &mqc_states[32]},
+       {0x4801, 1, &mqc_states[37], &mqc_states[33]},
+       {0x3801, 0, &mqc_states[38], &mqc_states[34]},
+       {0x3801, 1, &mqc_states[39], &mqc_states[35]},
+       {0x3401, 0, &mqc_states[40], &mqc_states[36]},
+       {0x3401, 1, &mqc_states[41], &mqc_states[37]},
+       {0x3001, 0, &mqc_states[42], &mqc_states[38]},
+       {0x3001, 1, &mqc_states[43], &mqc_states[39]},
+       {0x2801, 0, &mqc_states[44], &mqc_states[38]},
+       {0x2801, 1, &mqc_states[45], &mqc_states[39]},
+       {0x2401, 0, &mqc_states[46], &mqc_states[40]},
+       {0x2401, 1, &mqc_states[47], &mqc_states[41]},
+       {0x2201, 0, &mqc_states[48], &mqc_states[42]},
+       {0x2201, 1, &mqc_states[49], &mqc_states[43]},
+       {0x1c01, 0, &mqc_states[50], &mqc_states[44]},
+       {0x1c01, 1, &mqc_states[51], &mqc_states[45]},
+       {0x1801, 0, &mqc_states[52], &mqc_states[46]},
+       {0x1801, 1, &mqc_states[53], &mqc_states[47]},
+       {0x1601, 0, &mqc_states[54], &mqc_states[48]},
+       {0x1601, 1, &mqc_states[55], &mqc_states[49]},
+       {0x1401, 0, &mqc_states[56], &mqc_states[50]},
+       {0x1401, 1, &mqc_states[57], &mqc_states[51]},
+       {0x1201, 0, &mqc_states[58], &mqc_states[52]},
+       {0x1201, 1, &mqc_states[59], &mqc_states[53]},
+       {0x1101, 0, &mqc_states[60], &mqc_states[54]},
+       {0x1101, 1, &mqc_states[61], &mqc_states[55]},
+       {0x0ac1, 0, &mqc_states[62], &mqc_states[56]},
+       {0x0ac1, 1, &mqc_states[63], &mqc_states[57]},
+       {0x09c1, 0, &mqc_states[64], &mqc_states[58]},
+       {0x09c1, 1, &mqc_states[65], &mqc_states[59]},
+       {0x08a1, 0, &mqc_states[66], &mqc_states[60]},
+       {0x08a1, 1, &mqc_states[67], &mqc_states[61]},
+       {0x0521, 0, &mqc_states[68], &mqc_states[62]},
+       {0x0521, 1, &mqc_states[69], &mqc_states[63]},
+       {0x0441, 0, &mqc_states[70], &mqc_states[64]},
+       {0x0441, 1, &mqc_states[71], &mqc_states[65]},
+       {0x02a1, 0, &mqc_states[72], &mqc_states[66]},
+       {0x02a1, 1, &mqc_states[73], &mqc_states[67]},
+       {0x0221, 0, &mqc_states[74], &mqc_states[68]},
+       {0x0221, 1, &mqc_states[75], &mqc_states[69]},
+       {0x0141, 0, &mqc_states[76], &mqc_states[70]},
+       {0x0141, 1, &mqc_states[77], &mqc_states[71]},
+       {0x0111, 0, &mqc_states[78], &mqc_states[72]},
+       {0x0111, 1, &mqc_states[79], &mqc_states[73]},
+       {0x0085, 0, &mqc_states[80], &mqc_states[74]},
+       {0x0085, 1, &mqc_states[81], &mqc_states[75]},
+       {0x0049, 0, &mqc_states[82], &mqc_states[76]},
+       {0x0049, 1, &mqc_states[83], &mqc_states[77]},
+       {0x0025, 0, &mqc_states[84], &mqc_states[78]},
+       {0x0025, 1, &mqc_states[85], &mqc_states[79]},
+       {0x0015, 0, &mqc_states[86], &mqc_states[80]},
+       {0x0015, 1, &mqc_states[87], &mqc_states[81]},
+       {0x0009, 0, &mqc_states[88], &mqc_states[82]},
+       {0x0009, 1, &mqc_states[89], &mqc_states[83]},
+       {0x0005, 0, &mqc_states[90], &mqc_states[84]},
+       {0x0005, 1, &mqc_states[91], &mqc_states[85]},
+       {0x0001, 0, &mqc_states[90], &mqc_states[86]},
+       {0x0001, 1, &mqc_states[91], &mqc_states[87]},
+       {0x5601, 0, &mqc_states[92], &mqc_states[92]},
+       {0x5601, 1, &mqc_states[93], &mqc_states[93]},
+};
+
+/* 
+==========================================================
+   local functions
+==========================================================
+*/
+
+static void mqc_byteout(opj_mqc_t *mqc) {
+       if (*mqc->bp == 0xff) {
+               mqc->bp++;
+               *mqc->bp = mqc->c >> 20;
+               mqc->c &= 0xfffff;
+               mqc->ct = 7;
+       } else {
+               if ((mqc->c & 0x8000000) == 0) {        /* ((mqc->c&0x8000000)==0) CHANGE */
+                       mqc->bp++;
+                       *mqc->bp = mqc->c >> 19;
+                       mqc->c &= 0x7ffff;
+                       mqc->ct = 8;
+               } else {
+                       (*mqc->bp)++;
+                       if (*mqc->bp == 0xff) {
+                               mqc->c &= 0x7ffffff;
+                               mqc->bp++;
+                               *mqc->bp = mqc->c >> 20;
+                               mqc->c &= 0xfffff;
+                               mqc->ct = 7;
+                       } else {
+                               mqc->bp++;
+                               *mqc->bp = mqc->c >> 19;
+                               mqc->c &= 0x7ffff;
+                               mqc->ct = 8;
+                       }
+               }
+       }
+}
+
+static void mqc_renorme(opj_mqc_t *mqc) {
+       do {
+               mqc->a <<= 1;
+               mqc->c <<= 1;
+               mqc->ct--;
+               if (mqc->ct == 0) {
+                       mqc_byteout(mqc);
+               }
+       } while ((mqc->a & 0x8000) == 0);
+}
+
+static void mqc_codemps(opj_mqc_t *mqc) {
+       mqc->a -= (*mqc->curctx)->qeval;
+       if ((mqc->a & 0x8000) == 0) {
+               if (mqc->a < (*mqc->curctx)->qeval) {
+                       mqc->a = (*mqc->curctx)->qeval;
+               } else {
+                       mqc->c += (*mqc->curctx)->qeval;
+               }
+               *mqc->curctx = (*mqc->curctx)->nmps;
+               mqc_renorme(mqc);
+       } else {
+               mqc->c += (*mqc->curctx)->qeval;
+       }
+}
+
+static void mqc_codelps(opj_mqc_t *mqc) {
+       mqc->a -= (*mqc->curctx)->qeval;
+       if (mqc->a < (*mqc->curctx)->qeval) {
+               mqc->c += (*mqc->curctx)->qeval;
+       } else {
+               mqc->a = (*mqc->curctx)->qeval;
+       }
+       *mqc->curctx = (*mqc->curctx)->nlps;
+       mqc_renorme(mqc);
+}
+
+static void mqc_setbits(opj_mqc_t *mqc) {
+       unsigned int tempc = mqc->c + mqc->a;
+       mqc->c |= 0xffff;
+       if (mqc->c >= tempc) {
+               mqc->c -= 0x8000;
+       }
+}
+
+static int mqc_mpsexchange(opj_mqc_t *mqc) {
+       int d;
+       if (mqc->a < (*mqc->curctx)->qeval) {
+               d = 1 - (*mqc->curctx)->mps;
+               *mqc->curctx = (*mqc->curctx)->nlps;
+       } else {
+               d = (*mqc->curctx)->mps;
+               *mqc->curctx = (*mqc->curctx)->nmps;
+       }
+       
+       return d;
+}
+
+static int mqc_lpsexchange(opj_mqc_t *mqc) {
+       int d;
+       if (mqc->a < (*mqc->curctx)->qeval) {
+               mqc->a = (*mqc->curctx)->qeval;
+               d = (*mqc->curctx)->mps;
+               *mqc->curctx = (*mqc->curctx)->nmps;
+       } else {
+               mqc->a = (*mqc->curctx)->qeval;
+               d = 1 - (*mqc->curctx)->mps;
+               *mqc->curctx = (*mqc->curctx)->nlps;
+       }
+       
+       return d;
+}
+
+static void mqc_bytein(opj_mqc_t *mqc) {
+       if (mqc->bp != mqc->end) {
+               unsigned int c;
+               if (mqc->bp + 1 != mqc->end) {
+                       c = *(mqc->bp + 1);
+               } else {
+                       c = 0xff;
+               }
+               if (*mqc->bp == 0xff) {
+                       if (c > 0x8f) {
+                               mqc->c += 0xff00;
+                               mqc->ct = 8;
+                       } else {
+                               mqc->bp++;
+                               mqc->c += c << 9;
+                               mqc->ct = 7;
+                       }
+               } else {
+                       mqc->bp++;
+                       mqc->c += c << 8;
+                       mqc->ct = 8;
+               }
+       } else {
+               mqc->c += 0xff00;
+               mqc->ct = 8;
+       }
+}
+
+static void mqc_renormd(opj_mqc_t *mqc) {
+       do {
+               if (mqc->ct == 0) {
+                       mqc_bytein(mqc);
+               }
+               mqc->a <<= 1;
+               mqc->c <<= 1;
+               mqc->ct--;
+       } while (mqc->a < 0x8000);
+}
+
+/* 
+==========================================================
+   MQ-Coder interface
+==========================================================
+*/
+
+opj_mqc_t* mqc_create(void) {
+       opj_mqc_t *mqc = (opj_mqc_t*)opj_malloc(sizeof(opj_mqc_t));
+       return mqc;
+}
+
+void mqc_destroy(opj_mqc_t *mqc) {
+       if(mqc) {
+               opj_free(mqc);
+       }
+}
+
+int mqc_numbytes(opj_mqc_t *mqc) {
+       return mqc->bp - mqc->start;
+}
+
+void mqc_init_enc(opj_mqc_t *mqc, unsigned char *bp) {
+       mqc_setcurctx(mqc, 0);
+       mqc->a = 0x8000;
+       mqc->c = 0;
+       mqc->bp = bp - 1;
+       mqc->ct = 12;
+       if (*mqc->bp == 0xff) {
+               mqc->ct = 13;
+       }
+       mqc->start = bp;
+}
+
+void mqc_encode(opj_mqc_t *mqc, int d) {
+       if ((*mqc->curctx)->mps == d) {
+               mqc_codemps(mqc);
+       } else {
+               mqc_codelps(mqc);
+       }
+}
+
+void mqc_flush(opj_mqc_t *mqc) {
+       mqc_setbits(mqc);
+       mqc->c <<= mqc->ct;
+       mqc_byteout(mqc);
+       mqc->c <<= mqc->ct;
+       mqc_byteout(mqc);
+       
+       if (*mqc->bp != 0xff) {
+               mqc->bp++;
+       }
+}
+
+void mqc_bypass_init_enc(opj_mqc_t *mqc) {
+       mqc->c = 0;
+       mqc->ct = 8;
+       /*if (*mqc->bp == 0xff) {
+       mqc->ct = 7;
+     } */
+}
+
+void mqc_bypass_enc(opj_mqc_t *mqc, int d) {
+       mqc->ct--;
+       mqc->c = mqc->c + (d << mqc->ct);
+       if (mqc->ct == 0) {
+               mqc->bp++;
+               *mqc->bp = mqc->c;
+               mqc->ct = 8;
+               if (*mqc->bp == 0xff) {
+                       mqc->ct = 7;
+               }
+               mqc->c = 0;
+       }
+}
+
+int mqc_bypass_flush_enc(opj_mqc_t *mqc) {
+       unsigned char bit_padding;
+       
+       bit_padding = 0;
+       
+       if (mqc->ct != 0) {
+               while (mqc->ct > 0) {
+                       mqc->ct--;
+                       mqc->c += bit_padding << mqc->ct;
+                       bit_padding = (bit_padding + 1) & 0x01;
+               }
+               mqc->bp++;
+               *mqc->bp = mqc->c;
+               mqc->ct = 8;
+               mqc->c = 0;
+       }
+       
+       return 1;
+}
+
+void mqc_reset_enc(opj_mqc_t *mqc) {
+       mqc_resetstates(mqc);
+       mqc_setstate(mqc, T1_CTXNO_UNI, 0, 46);
+       mqc_setstate(mqc, T1_CTXNO_AGG, 0, 3);
+       mqc_setstate(mqc, T1_CTXNO_ZC, 0, 4);
+}
+
+int mqc_restart_enc(opj_mqc_t *mqc) {
+       int correction = 1;
+       
+       /* <flush part> */
+       int n = 27 - 15 - mqc->ct;
+       mqc->c <<= mqc->ct;
+       while (n > 0) {
+               mqc_byteout(mqc);
+               n -= mqc->ct;
+               mqc->c <<= mqc->ct;
+       }
+       mqc_byteout(mqc);
+       
+       return correction;
+}
+
+void mqc_restart_init_enc(opj_mqc_t *mqc) {
+       /* <Re-init part> */
+       mqc_setcurctx(mqc, 0);
+       mqc->a = 0x8000;
+       mqc->c = 0;
+       mqc->ct = 12;
+       mqc->bp--;
+       if (*mqc->bp == 0xff) {
+               mqc->ct = 13;
+       }
+}
+
+void mqc_erterm_enc(opj_mqc_t *mqc) {
+       int k = 11 - mqc->ct + 1;
+       
+       while (k > 0) {
+               mqc->c <<= mqc->ct;
+               mqc->ct = 0;
+               mqc_byteout(mqc);
+               k -= mqc->ct;
+       }
+       
+       if (*mqc->bp != 0xff) {
+               mqc_byteout(mqc);
+       }
+}
+
+void mqc_segmark_enc(opj_mqc_t *mqc) {
+       int i;
+       mqc_setcurctx(mqc, 18);
+       
+       for (i = 1; i < 5; i++) {
+               mqc_encode(mqc, i % 2);
+       }
+}
+
+void mqc_init_dec(opj_mqc_t *mqc, unsigned char *bp, int len) {
+       mqc_setcurctx(mqc, 0);
+       mqc->start = bp;
+       mqc->end = bp + len;
+       mqc->bp = bp;
+       if (len==0) mqc->c = 0xff << 16;
+       else mqc->c = *mqc->bp << 16;
+       mqc_bytein(mqc);
+       mqc->c <<= 7;
+       mqc->ct -= 7;
+       mqc->a = 0x8000;
+}
+
+int mqc_decode(opj_mqc_t *mqc) {
+       int d;
+       mqc->a -= (*mqc->curctx)->qeval;
+       if ((mqc->c >> 16) < (*mqc->curctx)->qeval) {
+               d = mqc_lpsexchange(mqc);
+               mqc_renormd(mqc);
+       } else {
+               mqc->c -= (*mqc->curctx)->qeval << 16;
+               if ((mqc->a & 0x8000) == 0) {
+                       d = mqc_mpsexchange(mqc);
+                       mqc_renormd(mqc);
+               } else {
+                       d = (*mqc->curctx)->mps;
+               }
+       }
+
+       return d;
+}
+
+void mqc_resetstates(opj_mqc_t *mqc) {
+       int i;
+       for (i = 0; i < MQC_NUMCTXS; i++) {
+               mqc->ctxs[i] = mqc_states;
+       }
+}
+
+void mqc_setstate(opj_mqc_t *mqc, int ctxno, int msb, int prob) {
+       mqc->ctxs[ctxno] = &mqc_states[msb + (prob << 1)];
+}
+
+
diff --git a/extern/libopenjpeg/mqc.h b/extern/libopenjpeg/mqc.h
new file mode 100644 (file)
index 0000000..8cc8c93
--- /dev/null
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __MQC_H
+#define __MQC_H
+/**
+@file mqc.h
+@brief Implementation of an MQ-Coder (MQC)
+
+The functions in MQC.C have for goal to realize the MQ-coder operations. The functions
+in MQC.C are used by some function in T1.C.
+*/
+
+/** @defgroup MQC MQC - Implementation of an MQ-Coder */
+/*@{*/
+
+/**
+This struct defines the state of a context.
+*/
+typedef struct opj_mqc_state {
+       /** the probability of the Least Probable Symbol (0.75->0x8000, 1.5->0xffff) */
+       unsigned int qeval;
+       /** the Most Probable Symbol (0 or 1) */
+       int mps;
+       /** next state if the next encoded symbol is the MPS */
+       struct opj_mqc_state *nmps;
+       /** next state if the next encoded symbol is the LPS */
+       struct opj_mqc_state *nlps;
+} opj_mqc_state_t;
+
+#define MQC_NUMCTXS 19
+
+/**
+MQ coder
+*/
+typedef struct opj_mqc {
+       unsigned int c;
+       unsigned int a;
+       unsigned int ct;
+       unsigned char *bp;
+       unsigned char *start;
+       unsigned char *end;
+       opj_mqc_state_t *ctxs[MQC_NUMCTXS];
+       opj_mqc_state_t **curctx;
+} opj_mqc_t;
+
+/** @name Exported functions */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+/**
+Create a new MQC handle 
+@return Returns a new MQC handle if successful, returns NULL otherwise
+*/
+opj_mqc_t* mqc_create(void);
+/**
+Destroy a previously created MQC handle
+@param mqc MQC handle to destroy
+*/
+void mqc_destroy(opj_mqc_t *mqc);
+/**
+Return the number of bytes written/read since initialisation
+@param mqc MQC handle
+@return Returns the number of bytes already encoded
+*/
+int mqc_numbytes(opj_mqc_t *mqc);
+/**
+Reset the states of all the context of the coder/decoder 
+(each context is set to a state where 0 and 1 are more or less equiprobable)
+@param mqc MQC handle
+*/
+void mqc_resetstates(opj_mqc_t *mqc);
+/**
+Set the state of a particular context
+@param mqc MQC handle
+@param ctxno Number that identifies the context
+@param msb The MSB of the new state of the context
+@param prob Number that identifies the probability of the symbols for the new state of the context
+*/
+void mqc_setstate(opj_mqc_t *mqc, int ctxno, int msb, int prob);
+/**
+Initialize the encoder
+@param mqc MQC handle
+@param bp Pointer to the start of the buffer where the bytes will be written
+*/
+void mqc_init_enc(opj_mqc_t *mqc, unsigned char *bp);
+/**
+Set the current context used for coding/decoding
+@param mqc MQC handle
+@param ctxno Number that identifies the context
+*/
+#define mqc_setcurctx(mqc, ctxno)      (mqc)->curctx = &(mqc)->ctxs[(int)(ctxno)]
+/**
+Encode a symbol using the MQ-coder
+@param mqc MQC handle
+@param d The symbol to be encoded (0 or 1)
+*/
+void mqc_encode(opj_mqc_t *mqc, int d);
+/**
+Flush the encoder, so that all remaining data is written
+@param mqc MQC handle
+*/
+void mqc_flush(opj_mqc_t *mqc);
+/**
+BYPASS mode switch, initialization operation. 
+JPEG 2000 p 505. 
+<h2>Not fully implemented and tested !!</h2>
+@param mqc MQC handle
+*/
+void mqc_bypass_init_enc(opj_mqc_t *mqc);
+/**
+BYPASS mode switch, coding operation. 
+JPEG 2000 p 505. 
+<h2>Not fully implemented and tested !!</h2>
+@param mqc MQC handle
+@param d The symbol to be encoded (0 or 1)
+*/
+void mqc_bypass_enc(opj_mqc_t *mqc, int d);
+/**
+BYPASS mode switch, flush operation
+<h2>Not fully implemented and tested !!</h2>
+@param mqc MQC handle
+@return Returns 1 (always)
+*/
+int mqc_bypass_flush_enc(opj_mqc_t *mqc);
+/**
+RESET mode switch
+@param mqc MQC handle
+*/
+void mqc_reset_enc(opj_mqc_t *mqc);
+/**
+RESTART mode switch (TERMALL)
+@param mqc MQC handle
+@return Returns 1 (always)
+*/
+int mqc_restart_enc(opj_mqc_t *mqc);
+/**
+RESTART mode switch (TERMALL) reinitialisation
+@param mqc MQC handle
+*/
+void mqc_restart_init_enc(opj_mqc_t *mqc);
+/**
+ERTERM mode switch (PTERM)
+@param mqc MQC handle
+*/
+void mqc_erterm_enc(opj_mqc_t *mqc);
+/**
+SEGMARK mode switch (SEGSYM)
+@param mqc MQC handle
+*/
+void mqc_segmark_enc(opj_mqc_t *mqc);
+/**
+Initialize the decoder
+@param mqc MQC handle
+@param bp Pointer to the start of the buffer from which the bytes will be read
+@param len Length of the input buffer
+*/
+void mqc_init_dec(opj_mqc_t *mqc, unsigned char *bp, int len);
+/**
+Decode a symbol
+@param mqc MQC handle
+@return Returns the decoded symbol (0 or 1)
+*/
+int mqc_decode(opj_mqc_t *mqc);
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif /* __MQC_H */
diff --git a/extern/libopenjpeg/openjpeg.c b/extern/libopenjpeg/openjpeg.c
new file mode 100644 (file)
index 0000000..96fa0ad
--- /dev/null
@@ -0,0 +1,329 @@
+/*
+ * Copyright (c) 2005, Hervé 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.
+ */
+
+#ifdef WIN32
+#include <windows.h>
+#endif /* WIN32 */
+
+#include "opj_includes.h"
+
+/* ---------------------------------------------------------------------- */
+#ifdef WIN32
+#ifndef OPJ_STATIC
+BOOL APIENTRY
+DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
+       switch (ul_reason_for_call) {
+               case DLL_PROCESS_ATTACH :
+                       break;
+               case DLL_PROCESS_DETACH :
+                       break;
+               case DLL_THREAD_ATTACH :
+               case DLL_THREAD_DETACH :
+                       break;
+    }
+
+    return TRUE;
+}
+#endif /* OPJ_STATIC */
+#endif /* WIN32 */