Update openjpeg

BUG=407964, 414182, 413447
R=tsepez@chromium.org

Review URL: https://codereview.chromium.org/589243004
diff --git a/core/src/fxcodec/codec/fx_codec_jpx_opj.cpp b/core/src/fxcodec/codec/fx_codec_jpx_opj.cpp
index 595d4df6..32adb8e 100644
--- a/core/src/fxcodec/codec/fx_codec_jpx_opj.cpp
+++ b/core/src/fxcodec/codec/fx_codec_jpx_opj.cpp
@@ -82,7 +82,7 @@
     if (! l_stream) {
         return NULL;
     }
-    opj_stream_set_user_data_v3(l_stream, data, NULL);
+    opj_stream_set_user_data(l_stream, data, NULL);
     opj_stream_set_user_data_length(l_stream, data->src_size);
     opj_stream_set_read_function(l_stream, opj_read_from_memory);
     opj_stream_set_write_function(l_stream, opj_write_from_memory);
@@ -609,11 +609,13 @@
         image = NULL;
         return FALSE;
     }
+/*
     if(this->m_useColorSpace) {
         image->useColorSpace = 1;
     } else {
         image->useColorSpace = 0;
     }
+*/
     if (!parameters.nb_tile_to_decode) {
         if (!opj_set_decode_area(l_codec, image, parameters.DA_x0,
                                     parameters.DA_y0, parameters.DA_x1, parameters.DA_y1)) {
@@ -643,7 +645,8 @@
     if(image->color_space == OPJ_CLRSPC_SYCC) {
         color_sycc_to_rgb(image);
     }
-    if(image->icc_profile_buf && !image->useColorSpace) {
+    //if(image->icc_profile_buf && !image->useColorSpace) {
+    if(image->icc_profile_buf) {
         FX_Free(image->icc_profile_buf);
         image->icc_profile_buf = NULL;
         image->icc_profile_len = 0;
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/CMakeLists.txt b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/CMakeLists.txt
index 5c87f29..fcf60ec 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/CMakeLists.txt
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/CMakeLists.txt
@@ -68,10 +68,12 @@
   DESTINATION ${OPENJPEG_INSTALL_INCLUDE_DIR} COMPONENT Headers
 )
 
+if(BUILD_DOC)
 # install man page of the library
 install(
   FILES       ${OPENJPEG_SOURCE_DIR}/doc/man/man3/libopenjp2.3
   DESTINATION ${OPENJPEG_INSTALL_MAN_DIR}/man3)
+endif()
 
 # internal utilities to generate t1_luts.h (part of the jp2 lib)
 # no need to install:
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/cio.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/cio.c
index 6cba658..c455bf7 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/cio.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/cio.c
@@ -151,12 +151,11 @@
 opj_stream_t* OPJ_CALLCONV opj_stream_create(OPJ_SIZE_T p_buffer_size,OPJ_BOOL l_is_input)
 {
 	opj_stream_private_t * l_stream = 00;
-	l_stream = (opj_stream_private_t*) opj_malloc(sizeof(opj_stream_private_t));
+	l_stream = (opj_stream_private_t*) opj_calloc(1,sizeof(opj_stream_private_t));
 	if (! l_stream) {
 		return 00;
 	}
 
-	memset(l_stream,0,sizeof(opj_stream_private_t));
 	l_stream->m_buffer_size = p_buffer_size;
 	l_stream->m_stored_data = (OPJ_BYTE *) opj_malloc(p_buffer_size);
 	if (! l_stream->m_stored_data) {
@@ -204,11 +203,6 @@
 	}
 }
 
-void OPJ_CALLCONV opj_stream_destroy_v3(opj_stream_t* p_stream)
-{
-	opj_stream_destroy(p_stream);
-}
-
 void OPJ_CALLCONV opj_stream_set_read_function(opj_stream_t* p_stream, opj_stream_read_fn p_function)
 {
 	opj_stream_private_t* l_stream = (opj_stream_private_t*) p_stream;
@@ -252,15 +246,7 @@
 	l_stream->m_skip_fn = p_function;
 }
 
-void OPJ_CALLCONV opj_stream_set_user_data(opj_stream_t* p_stream, void * p_data)
-{
-	opj_stream_private_t* l_stream = (opj_stream_private_t*) p_stream;
-	if (!l_stream)
-		return;
-	l_stream->m_user_data = p_data;
-}
-
-void OPJ_CALLCONV opj_stream_set_user_data_v3(opj_stream_t* p_stream, void * p_data, opj_stream_free_user_data_fn p_function)
+void OPJ_CALLCONV opj_stream_set_user_data(opj_stream_t* p_stream, void * p_data, opj_stream_free_user_data_fn p_function)
 {
 	opj_stream_private_t* l_stream = (opj_stream_private_t*) p_stream;
 	if (!l_stream)
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/cio.h b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/cio.h
index 729d073..6dfa5bb 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/cio.h
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/cio.h
@@ -49,7 +49,7 @@
 /** @defgroup CIO CIO - byte input-output stream */
 /*@{*/
 
-#include "opj_config.h"
+#include "opj_config_private.h"
 
 /* ----------------------------------------------------------------------- */
 
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/dwt.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/dwt.c
index 60698e3..bea4574 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/dwt.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/dwt.c
@@ -571,6 +571,7 @@
 	h.mem = (OPJ_INT32*)
 	opj_aligned_malloc(opj_dwt_max_resolution(tr, numres) * sizeof(OPJ_INT32));
 	if (! h.mem){
+		/* FIXME event manager error callback */
 		return OPJ_FALSE;
 	}
 
@@ -808,7 +809,6 @@
 		a = 1;
 		b = 0;
 	}
-
 #ifdef __SSE__
 	opj_v4dwt_decode_step1_sse(dwt->wavelet+a, dwt->sn, _mm_set1_ps(opj_K));
 	opj_v4dwt_decode_step1_sse(dwt->wavelet+b, dwt->dn, _mm_set1_ps(opj_c13318));
@@ -843,6 +843,10 @@
 	OPJ_UINT32 w = (OPJ_UINT32)(tilec->x1 - tilec->x0);
 
 	h.wavelet = (opj_v4_t*) opj_aligned_malloc((opj_dwt_max_resolution(res, numres)+5) * sizeof(opj_v4_t));
+	if (!h.wavelet) {
+		/* FIXME event manager error callback */
+		return OPJ_FALSE;
+	}
 	v.wavelet = h.wavelet;
 
 	while( --numres) {
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/function_list.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/function_list.c
index 4c8aae6..b9a8b4a 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/function_list.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/function_list.c
@@ -39,22 +39,19 @@
 opj_procedure_list_t *  opj_procedure_list_create()
 {
         /* memory allocation */
-        opj_procedure_list_t * l_validation = (opj_procedure_list_t *) opj_malloc(sizeof(opj_procedure_list_t));
+        opj_procedure_list_t * l_validation = (opj_procedure_list_t *) opj_calloc(1,sizeof(opj_procedure_list_t));
         if (! l_validation)
         {
                 return 00;
         }
         /* initialization */
-        memset(l_validation,0,sizeof(opj_procedure_list_t));
         l_validation->m_nb_max_procedures = OPJ_VALIDATION_SIZE;
-        l_validation->m_procedures = (opj_procedure*)opj_malloc(
-                OPJ_VALIDATION_SIZE * sizeof(opj_procedure));
+        l_validation->m_procedures = (opj_procedure*)opj_calloc(OPJ_VALIDATION_SIZE, sizeof(opj_procedure));
         if (! l_validation->m_procedures)
         {
                 opj_free(l_validation);
                 return 00;
         }
-        memset(l_validation->m_procedures,0,OPJ_VALIDATION_SIZE * sizeof(opj_procedure));
         return l_validation;
 }
 
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/image.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/image.c
index 2c3540c..8e68668 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/image.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/image.c
@@ -205,21 +205,19 @@
 	OPJ_UINT32 compno;
 	opj_image_t *image = 00;
 
-	image = (opj_image_t*) opj_malloc(sizeof(opj_image_t));
+	image = (opj_image_t*) opj_calloc(1,sizeof(opj_image_t));
 	if (image)
 	{
-		memset(image,0,sizeof(opj_image_t));
 		
 		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));
+		image->comps = (opj_image_comp_t*)opj_calloc(image->numcomps, sizeof(opj_image_comp_t));
 		if (!image->comps) {
 			opj_image_destroy(image);
 			return 00;
 		}
-		memset(image->comps,0,image->numcomps * sizeof(opj_image_comp_t));
 		
 		/* create the individual image components */
 		for(compno = 0; compno < numcmpts; compno++) {
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/j2k.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/j2k.c
index bf411ef..b794dc3 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/j2k.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/j2k.c
@@ -42,11 +42,6 @@
 
 #include "opj_includes.h"
 
-#define CINEMA_24_CS 1302083	/*Codestream length for 24fps*/
-#define CINEMA_48_CS 651041		/*Codestream length for 48fps*/
-#define COMP_24_CS 1041666		/*Maximum size per color component for 2K & 4K @ 24fps*/
-#define COMP_48_CS 520833		/*Maximum size per color component for 2K @ 48fps*/
-
 /** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
 /*@{*/
 
@@ -1172,7 +1167,7 @@
 
 static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t *p_manager);
 
-static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_CINEMA_MODE cinema_mode, opj_event_mgr_t *p_manager);
+static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz, opj_event_mgr_t *p_manager);
 
 /*@}*/
 
@@ -1504,7 +1499,6 @@
                 opj_event_msg(p_manager , EVT_ERROR, "Not enough memory for checking the poc values.\n");
                 return OPJ_FALSE;
         }
-        memset(packet_array,0,step_l * p_num_layers* sizeof(OPJ_UINT32));
 
         if (p_nb_pocs == 0) {
         opj_free(packet_array);
@@ -1945,7 +1939,7 @@
 
         opj_read_bytes(p_header_data,&l_tmp ,2);                                                /* Rsiz (capabilities) */
         p_header_data+=2;
-        l_cp->rsiz = (OPJ_RSIZ_CAPABILITIES) l_tmp;
+        l_cp->rsiz = (OPJ_UINT16) l_tmp;
         opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x1, 4);   /* Xsiz */
         p_header_data+=4;
         opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y1, 4);   /* Ysiz */
@@ -2043,7 +2037,6 @@
                 return OPJ_FALSE;
         }
 
-        memset(l_image->comps,0,l_image->numcomps * sizeof(opj_image_comp_t));
         l_img_comp = l_image->comps;
 
         /* Read the component information */
@@ -2172,7 +2165,6 @@
                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
                 return OPJ_FALSE;
         }
-        memset(l_cp->tcps,0,l_nb_tiles*sizeof(opj_tcp_t));
 
 #ifdef USE_JPWL
         if (l_cp->correct) {
@@ -2193,27 +2185,24 @@
                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
                 return OPJ_FALSE;
         }
-        memset(p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps ,0,l_image->numcomps*sizeof(opj_tccp_t));
 
         p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records =
-                        (opj_mct_data_t*)opj_malloc(OPJ_J2K_MCT_DEFAULT_NB_RECORDS * sizeof(opj_mct_data_t));
+                        (opj_mct_data_t*)opj_calloc(OPJ_J2K_MCT_DEFAULT_NB_RECORDS ,sizeof(opj_mct_data_t));
 
         if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records) {
                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
                 return OPJ_FALSE;
         }
-        memset(p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records,0,OPJ_J2K_MCT_DEFAULT_NB_RECORDS * sizeof(opj_mct_data_t));
         p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mct_records = OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
 
         p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records =
                         (opj_simple_mcc_decorrelation_data_t*)
-                        opj_malloc(OPJ_J2K_MCC_DEFAULT_NB_RECORDS * sizeof(opj_simple_mcc_decorrelation_data_t));
+                        opj_calloc(OPJ_J2K_MCC_DEFAULT_NB_RECORDS, sizeof(opj_simple_mcc_decorrelation_data_t));
 
         if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records) {
                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
                 return OPJ_FALSE;
         }
-        memset(p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records,0,OPJ_J2K_MCC_DEFAULT_NB_RECORDS * sizeof(opj_simple_mcc_decorrelation_data_t));
         p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mcc_records = OPJ_J2K_MCC_DEFAULT_NB_RECORDS;
 
         /* set up default dc level shift */
@@ -2225,12 +2214,11 @@
 
         l_current_tile_param = l_cp->tcps;
         for     (i = 0; i < l_nb_tiles; ++i) {
-                l_current_tile_param->tccps = (opj_tccp_t*) opj_malloc(l_image->numcomps * sizeof(opj_tccp_t));
+                l_current_tile_param->tccps = (opj_tccp_t*) opj_calloc(l_image->numcomps, sizeof(opj_tccp_t));
                 if (l_current_tile_param->tccps == 00) {
                         opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
                         return OPJ_FALSE;
                 }
-                memset(l_current_tile_param->tccps,0,l_image->numcomps * sizeof(opj_tccp_t));
 
                 ++l_current_tile_param;
         }
@@ -3102,7 +3090,7 @@
         l_nb_comps = p_j2k->m_private_image->numcomps - 1;
         l_nb_bytes += opj_j2k_get_max_toc_size(p_j2k);
 
-        if (p_j2k->m_cp.m_specific_param.m_enc.m_cinema == 0) {
+        if (!(OPJ_IS_CINEMA(p_j2k->m_cp.rsiz))) {
                 l_coc_bytes = opj_j2k_get_max_coc_size(p_j2k);
                 l_nb_bytes += l_nb_comps * l_coc_bytes;
 
@@ -3581,13 +3569,12 @@
                 l_cp->ppm_len = l_N_ppm;
                 l_cp->ppm_data_read = 0;
 
-                l_cp->ppm_data = (OPJ_BYTE *) opj_malloc(l_cp->ppm_len);
+                l_cp->ppm_data = (OPJ_BYTE *) opj_calloc(1,l_cp->ppm_len);
                 l_cp->ppm_buffer = l_cp->ppm_data;
                 if (l_cp->ppm_data == 00) {
                         opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read ppm marker\n");
                         return OPJ_FALSE;
                 }
-                memset(l_cp->ppm_data,0,l_cp->ppm_len);
 
                 l_cp->ppm_data_current = l_cp->ppm_data;
 
@@ -3654,7 +3641,6 @@
 
                 if (p_header_size)
                 {
-						if (p_header_size < 4) return OPJ_FALSE;
                         opj_read_bytes(p_header_data,&l_N_ppm,4);               /* N_ppm^i */
                         p_header_data+=4;
                         p_header_size-=4;
@@ -4074,10 +4060,8 @@
                                 if (l_current_part >= l_tcp->m_nb_tile_parts){
                                         opj_event_msg(p_manager, EVT_ERROR, "In SOT marker, TPSot (%d) is not valid regards to the current "
                                                         "number of tile-part (%d), giving up\n", l_current_part, l_tcp->m_nb_tile_parts );
-                                      //  p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
-                                     //   return OPJ_FALSE;
-										
-										l_num_parts++; 
+                                        p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
+                                        return OPJ_FALSE;
                                 }
                         }
                         if( l_current_part >= l_num_parts ) {
@@ -4093,7 +4077,7 @@
                 /* If know the number of tile part header we will check if we didn't read the last*/
                 if (l_tcp->m_nb_tile_parts) {
                         if (l_tcp->m_nb_tile_parts == (l_current_part+1)) {
-                                p_j2k->m_specific_param.m_decoder.m_can_decode = 0; /* Process the last tile-part header*/
+                                p_j2k->m_specific_param.m_decoder.m_can_decode = 1; /* Process the last tile-part header*/
                         }
                 }
 
@@ -4136,6 +4120,10 @@
                                 if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
                                         p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
                                                 (opj_tp_index_t*)opj_calloc(l_num_parts, sizeof(opj_tp_index_t));
+                                        if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
+                                                opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n");
+                                                return OPJ_FALSE;
+																				}
                                 }
                                 else {
                                         opj_tp_index_t *new_tp_index = (opj_tp_index_t *) opj_realloc(
@@ -4143,7 +4131,7 @@
                                         if (! new_tp_index) {
                                                 opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index);
                                                 p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL;
-                                                opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
+                                                opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n");
                                                 return OPJ_FALSE;
                                         }
                                         p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = new_tp_index;
@@ -4157,6 +4145,11 @@
                                                 p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
                                                         (opj_tp_index_t*)opj_calloc( p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps,
                                                                         sizeof(opj_tp_index_t));
+																								if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
+                                                        p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0;
+                                                        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n");
+                                                        return OPJ_FALSE;
+																				        }
                                         }
 
                                         if ( l_current_part >= p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps ){
@@ -4169,7 +4162,7 @@
                                                         opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index);
                                                         p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL;
                                                         p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0;
-                                                        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
+                                                        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n");
                                                         return OPJ_FALSE;
                                                 }
                                                 p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = new_tp_index;
@@ -4331,11 +4324,7 @@
                 *l_current_data = (OPJ_BYTE*) opj_malloc(p_j2k->m_specific_param.m_decoder.m_sot_length);
             }
             else {
-				OPJ_BYTE *l_new_current_data = NULL;
-				//BUGID: 0056005 and 0056022.
-				//test file: 366683_fuzz-asan_heap-oob_6bae99_3155_5245.pdf and fuzz-12.pdf.
-				if ((OPJ_UINT32)-1 - p_j2k->m_specific_param.m_decoder.m_sot_length >= *l_tile_len)
-					l_new_current_data = (OPJ_BYTE *) opj_realloc(*l_current_data, *l_tile_len + p_j2k->m_specific_param.m_decoder.m_sot_length);
+                OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(*l_current_data, *l_tile_len + p_j2k->m_specific_param.m_decoder.m_sot_length);
                 if (! l_new_current_data) {
                         opj_free(*l_current_data);
                         /*nothing more is done as l_current_data will be set to null, and just
@@ -4729,7 +4718,7 @@
                 return OPJ_FALSE;
         }
 
-        if (l_cp->m_specific_param.m_enc.m_cinema) {
+        if (OPJ_IS_CINEMA(l_cp->rsiz)) {
                 p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer =
                                 (OPJ_BYTE *) opj_malloc(5*p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
                 if (! p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
@@ -5865,12 +5854,11 @@
 
 opj_j2k_t* opj_j2k_create_compress(void)
 {
-        opj_j2k_t *l_j2k = (opj_j2k_t*) opj_malloc(sizeof(opj_j2k_t));
+        opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1,sizeof(opj_j2k_t));
         if (!l_j2k) {
                 return NULL;
         }
 
-        memset(l_j2k,0,sizeof(opj_j2k_t));
 
         l_j2k->m_is_decoder = 0;
         l_j2k->m_cp.m_is_decoder = 0;
@@ -5921,24 +5909,8 @@
 void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t *p_manager)
 {
     /* Configure cinema parameters */
-    OPJ_FLOAT32 max_rate = 0;
-    OPJ_FLOAT32 temp_rate = 0;
     int i;
 
-    /* profile (Rsiz) */
-    switch (parameters->cp_cinema){
-    case OPJ_CINEMA2K_24:
-    case OPJ_CINEMA2K_48:
-        parameters->cp_rsiz = OPJ_CINEMA2K;
-        break;
-    case OPJ_CINEMA4K_24:
-        parameters->cp_rsiz = OPJ_CINEMA4K;
-        break;
-    case OPJ_OFF:
-        assert(0);
-        break;
-    }
-
     /* No tiling */
     parameters->tile_size_on = OPJ_FALSE;
     parameters->cp_tdx=1;
@@ -5976,15 +5948,16 @@
         opj_event_msg(p_manager, EVT_WARNING,
                 "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
                 "1 single quality layer"
-                "-> Number of layers forced to 1 (rather than %d)\n",
-                parameters->tcp_numlayers);
+                "-> Number of layers forced to 1 (rather than %d)\n"
+                "-> Rate of the last layer (%3.1f) will be used",
+                parameters->tcp_numlayers, parameters->tcp_rates[parameters->tcp_numlayers-1]);
+        parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers-1];
         parameters->tcp_numlayers = 1;
     }
 
     /* Resolution levels */
-    switch (parameters->cp_cinema){
-    case OPJ_CINEMA2K_24:
-    case OPJ_CINEMA2K_48:
+    switch (parameters->rsiz){
+    case OPJ_PROFILE_CINEMA_2K:
         if(parameters->numresolution > 6){
             opj_event_msg(p_manager, EVT_WARNING,
                     "JPEG 2000 Profile-3 (2k dc profile) requires:\n"
@@ -5994,7 +5967,7 @@
             parameters->numresolution = 6;
         }
         break;
-    case OPJ_CINEMA4K_24:
+    case OPJ_PROFILE_CINEMA_4K:
         if(parameters->numresolution < 2){
             opj_event_msg(p_manager, EVT_WARNING,
                     "JPEG 2000 Profile-4 (4k dc profile) requires:\n"
@@ -6027,7 +6000,7 @@
     parameters->prog_order = OPJ_CPRL;
 
     /* Progression order changes for 4K, disallowed for 2K */
-    if (parameters->cp_cinema == OPJ_CINEMA4K_24) {
+    if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) {
         parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC,parameters->numresolution);
     } else {
         parameters->numpocs = 0;
@@ -6035,62 +6008,42 @@
 
     /* Limited bit-rate */
     parameters->cp_disto_alloc = 1;
-    switch (parameters->cp_cinema){
-    case OPJ_CINEMA2K_24:
-    case OPJ_CINEMA4K_24:
-        max_rate = (OPJ_FLOAT32) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)/
-                (OPJ_FLOAT32)(CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);
-        if (parameters->tcp_rates[0] == 0){
-            parameters->tcp_rates[0] = max_rate;
-        }else{
-            temp_rate =(OPJ_FLOAT32)(image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)/
-                    (parameters->tcp_rates[0] * 8 * (OPJ_FLOAT32)image->comps[0].dx * (OPJ_FLOAT32)image->comps[0].dy);
-            if (temp_rate > CINEMA_24_CS ){
-                opj_event_msg(p_manager, EVT_WARNING,
-                        "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
-                        "Maximum 1302083 compressed bytes @ 24fps\n"
-                        "-> Specified rate (%3.1f) exceeds this limit. Rate will be forced to %3.1f.\n",
-                        parameters->tcp_rates[0], max_rate);
-                parameters->tcp_rates[0]= max_rate;
-            }else{
-                opj_event_msg(p_manager, EVT_WARNING,
-                        "JPEG 2000 Profile-3 and 4 (2k/4k dc profile):\n"
-                        "INFO : Specified rate (%3.1f) is below the 2k/4k limit @ 24fps.\n",
-                        parameters->tcp_rates[0]);
-            }
-        }
-        parameters->max_comp_size = COMP_24_CS;
-        break;
-    case OPJ_CINEMA2K_48:
-        max_rate = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
-                (float)(CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);
-        if (parameters->tcp_rates[0] == 0){
-            parameters->tcp_rates[0] = max_rate;
-        }else{
-            temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
-                    (parameters->tcp_rates[0] * 8 * (float)image->comps[0].dx * (float)image->comps[0].dy);
-            if (temp_rate > CINEMA_48_CS ){
-                opj_event_msg(p_manager, EVT_WARNING,
-                        "JPEG 2000 Profile-3 (2k dc profile) requires:\n"
-                        "Maximum 651041 compressed bytes @ 48fps\n"
-                        "-> Specified rate (%3.1f) exceeds this limit. Rate will be forced to %3.1f.\n",
-                        parameters->tcp_rates[0], max_rate);
-                parameters->tcp_rates[0]= max_rate;
-            }else{
-                opj_event_msg(p_manager, EVT_WARNING,
-                        "JPEG 2000 Profile-3 (2k dc profile):\n"
-                        "INFO : Specified rate (%3.1f) is below the 2k limit @ 48 fps.\n",
-                        parameters->tcp_rates[0]);
-            }
-        }
-        parameters->max_comp_size = COMP_48_CS;
-        break;
-    default:
-        break;
+    if (parameters->max_cs_size <= 0) {
+        /* No rate has been introduced, 24 fps is assumed */
+        parameters->max_cs_size = OPJ_CINEMA_24_CS;
+        opj_event_msg(p_manager, EVT_WARNING,
+                      "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
+                      "Maximum 1302083 compressed bytes @ 24fps\n"
+                      "As no rate has been given, this limit will be used.\n");
+    } else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) {
+        opj_event_msg(p_manager, EVT_WARNING,
+                      "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
+                      "Maximum 1302083 compressed bytes @ 24fps\n"
+                      "-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n");
+        parameters->max_cs_size = OPJ_CINEMA_24_CS;
     }
+
+    if (parameters->max_comp_size <= 0) {
+        /* No rate has been introduced, 24 fps is assumed */
+        parameters->max_comp_size = OPJ_CINEMA_24_COMP;
+        opj_event_msg(p_manager, EVT_WARNING,
+                      "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
+                      "Maximum 1041666 compressed bytes @ 24fps\n"
+                      "As no rate has been given, this limit will be used.\n");
+    } else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) {
+        opj_event_msg(p_manager, EVT_WARNING,
+                      "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
+                      "Maximum 1041666 compressed bytes @ 24fps\n"
+                      "-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n");
+        parameters->max_comp_size = OPJ_CINEMA_24_COMP;
+    }
+
+    parameters->tcp_rates[0] = (OPJ_FLOAT32) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)/
+            (OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx * image->comps[0].dy);
+
 }
 
-OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_CINEMA_MODE cinema_mode, opj_event_mgr_t *p_manager)
+OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz, opj_event_mgr_t *p_manager)
 {
     OPJ_UINT32 i;
 
@@ -6122,9 +6075,8 @@
     }
 
     /* Image size */
-    switch (cinema_mode){
-    case OPJ_CINEMA2K_24:
-    case OPJ_CINEMA2K_48:
+    switch (rsiz){
+    case OPJ_PROFILE_CINEMA_2K:
         if (((image->comps[0].w > 2048) | (image->comps[0].h > 1080))){
             opj_event_msg(p_manager, EVT_WARNING,
                     "JPEG 2000 Profile-3 (2k dc profile) requires:\n"
@@ -6135,7 +6087,7 @@
             return OPJ_FALSE;
         }
         break;
-    case OPJ_CINEMA4K_24:
+    case OPJ_PROFILE_CINEMA_4K:
         if (((image->comps[0].w > 4096) | (image->comps[0].h > 2160))){
             opj_event_msg(p_manager, EVT_WARNING,
                     "JPEG 2000 Profile-4 (4k dc profile) requires:\n"
@@ -6153,7 +6105,7 @@
     return OPJ_TRUE;
 }
 
-void opj_j2k_setup_encoder(     opj_j2k_t *p_j2k,
+OPJ_BOOL opj_j2k_setup_encoder(     opj_j2k_t *p_j2k,
                                                     opj_cparameters_t *parameters,
                                                     opj_image_t *image,
                                                     opj_event_mgr_t * p_manager)
@@ -6162,7 +6114,7 @@
         opj_cp_t *cp = 00;
 
         if(!p_j2k || !parameters || ! image) {
-                return;
+                return OPJ_FALSE;
         }
 
         /* keep a link to cp so that we can destroy it later in j2k_destroy_compress */
@@ -6172,20 +6124,130 @@
         cp->tw = 1;
         cp->th = 1;
 
+        /* FIXME ADE: to be removed once deprecated cp_cinema and cp_rsiz have been removed */
+        if (parameters->rsiz == OPJ_PROFILE_NONE) { /* consider deprecated fields only if RSIZ has not been set */
+            OPJ_BOOL deprecated_used = OPJ_FALSE;
+            switch (parameters->cp_cinema){
+            case OPJ_CINEMA2K_24:
+                parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
+                parameters->max_cs_size = OPJ_CINEMA_24_CS;
+                parameters->max_comp_size = OPJ_CINEMA_24_COMP;
+                deprecated_used = OPJ_TRUE;
+                break;
+            case OPJ_CINEMA2K_48:
+                parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
+                parameters->max_cs_size = OPJ_CINEMA_48_CS;
+                parameters->max_comp_size = OPJ_CINEMA_48_COMP;
+                deprecated_used = OPJ_TRUE;
+                break;
+            case OPJ_CINEMA4K_24:
+                parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
+                parameters->max_cs_size = OPJ_CINEMA_24_CS;
+                parameters->max_comp_size = OPJ_CINEMA_24_COMP;
+                deprecated_used = OPJ_TRUE;
+                break;
+            case OPJ_OFF:
+            default:
+                break;
+            }
+            switch (parameters->cp_rsiz){
+            case OPJ_CINEMA2K:
+                parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
+                deprecated_used = OPJ_TRUE;
+                break;
+            case OPJ_CINEMA4K:
+                parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
+                deprecated_used = OPJ_TRUE;
+                break;
+            case OPJ_MCT:
+                parameters->rsiz = OPJ_PROFILE_PART2 | OPJ_EXTENSION_MCT;
+                deprecated_used = OPJ_TRUE;
+            case OPJ_STD_RSIZ:
+            default:
+                break;
+            }
+            if (deprecated_used) {
+                opj_event_msg(p_manager, EVT_WARNING,
+                        "Deprecated fields cp_cinema or cp_rsiz are used\n"
+                        "Please consider using only the rsiz field\n"
+                        "See openjpeg.h documentation for more details\n");
+            }
+        }
+
+        /* see if max_codestream_size does limit input rate */
+        if (parameters->max_cs_size <= 0) {
+            if (parameters->tcp_rates[parameters->tcp_numlayers-1] > 0) {
+                OPJ_FLOAT32 temp_size;
+                temp_size =(OPJ_FLOAT32)(image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)/
+                        (parameters->tcp_rates[parameters->tcp_numlayers-1] * 8 * (OPJ_FLOAT32)image->comps[0].dx * (OPJ_FLOAT32)image->comps[0].dy);
+                parameters->max_cs_size = (int) floor(temp_size);
+            } else {
+                parameters->max_cs_size = 0;
+            }
+        } else {
+            OPJ_FLOAT32 temp_rate;
+            OPJ_BOOL cap = OPJ_FALSE;
+            temp_rate = (OPJ_FLOAT32) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)/
+                    (OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx * image->comps[0].dy);
+            for (i = 0; i < (OPJ_UINT32) parameters->tcp_numlayers; i++) {
+                if (parameters->tcp_rates[i] < temp_rate) {
+                    parameters->tcp_rates[i] = temp_rate;
+                    cap = OPJ_TRUE;
+                }
+            }
+            if (cap) {
+                opj_event_msg(p_manager, EVT_WARNING,
+                        "The desired maximum codestream size has limited\n"
+                        "at least one of the desired quality layers\n");
+            }
+        }
+
+        /* Manage profiles and applications and set RSIZ */
         /* set cinema parameters if required */
-        if (parameters->cp_cinema){
-            opj_j2k_set_cinema_parameters(parameters,image,p_manager);
-            if (!opj_j2k_is_cinema_compliant(image,parameters->cp_cinema,p_manager)) {
-                parameters->cp_rsiz = OPJ_STD_RSIZ;
+        if (OPJ_IS_CINEMA(parameters->rsiz)){
+            if ((parameters->rsiz == OPJ_PROFILE_CINEMA_S2K)
+                    || (parameters->rsiz == OPJ_PROFILE_CINEMA_S4K)){
+                opj_event_msg(p_manager, EVT_WARNING,
+                        "JPEG 2000 Scalable Digital Cinema profiles not yet supported\n");
+                parameters->rsiz = OPJ_PROFILE_NONE;
+            } else {
+                opj_j2k_set_cinema_parameters(parameters,image,p_manager);
+                if (!opj_j2k_is_cinema_compliant(image,parameters->rsiz,p_manager)) {
+                    parameters->rsiz = OPJ_PROFILE_NONE;
+                }
+            }
+        } else if (OPJ_IS_STORAGE(parameters->rsiz)) {
+            opj_event_msg(p_manager, EVT_WARNING,
+                    "JPEG 2000 Long Term Storage profile not yet supported\n");
+            parameters->rsiz = OPJ_PROFILE_NONE;
+        } else if (OPJ_IS_BROADCAST(parameters->rsiz)) {
+            opj_event_msg(p_manager, EVT_WARNING,
+                    "JPEG 2000 Broadcast profiles not yet supported\n");
+            parameters->rsiz = OPJ_PROFILE_NONE;
+        } else if (OPJ_IS_IMF(parameters->rsiz)) {
+            opj_event_msg(p_manager, EVT_WARNING,
+                    "JPEG 2000 IMF profiles not yet supported\n");
+            parameters->rsiz = OPJ_PROFILE_NONE;
+        } else if (OPJ_IS_PART2(parameters->rsiz)) {
+            if (parameters->rsiz == ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_NONE))) {
+                opj_event_msg(p_manager, EVT_WARNING,
+                              "JPEG 2000 Part-2 profile defined\n"
+                              "but no Part-2 extension enabled.\n"
+                              "Profile set to NONE.\n");
+                parameters->rsiz = OPJ_PROFILE_NONE;
+            } else if (parameters->rsiz != ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_MCT))) {
+                opj_event_msg(p_manager, EVT_WARNING,
+                              "Unsupported Part-2 extension enabled\n"
+                              "Profile set to NONE.\n");
+                parameters->rsiz = OPJ_PROFILE_NONE;
             }
         }
 
         /*
         copy user encoding parameters
         */
-        cp->m_specific_param.m_enc.m_cinema = parameters->cp_cinema;
         cp->m_specific_param.m_enc.m_max_comp_size = (OPJ_UINT32)parameters->max_comp_size;
-        cp->rsiz   = parameters->cp_rsiz;
+        cp->rsiz = parameters->rsiz;
         cp->m_specific_param.m_enc.m_disto_alloc = (OPJ_UINT32)parameters->cp_disto_alloc & 1u;
         cp->m_specific_param.m_enc.m_fixed_alloc = (OPJ_UINT32)parameters->cp_fixed_alloc & 1u;
         cp->m_specific_param.m_enc.m_fixed_quality = (OPJ_UINT32)parameters->cp_fixed_quality & 1u;
@@ -6194,6 +6256,10 @@
         if (parameters->cp_fixed_alloc && parameters->cp_matrice) {
                 size_t array_size = (size_t)parameters->tcp_numlayers * (size_t)parameters->numresolution * 3 * sizeof(OPJ_INT32);
                 cp->m_specific_param.m_enc.m_matrice = (OPJ_INT32 *) opj_malloc(array_size);
+								if (!cp->m_specific_param.m_enc.m_matrice) {
+								        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate copy of user encoding parameters matrix \n");
+								        return OPJ_FALSE;
+								}
                 memcpy(cp->m_specific_param.m_enc.m_matrice, parameters->cp_matrice, array_size);
         }
 
@@ -6207,11 +6273,36 @@
 
         /* 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);
-                }
-        }
+                cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1U);
+								if(!cp->comment) {
+								        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate copy of comment string\n");
+								        return OPJ_FALSE;
+								}
+                strcpy(cp->comment, parameters->cp_comment);
+        } else {
+                /* Create default comment for codestream */
+                const char comment[] = "Created by OpenJPEG version ";
+                const size_t clen = strlen(comment);
+                const char *version = opj_version();
+
+                /* UniPG>> */
+#ifdef USE_JPWL
+                cp->comment = (char*)opj_malloc(clen+strlen(version)+11);
+								if(!cp->comment) {
+								        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate comment string\n");
+								        return OPJ_FALSE;
+								}
+                sprintf(cp->comment,"%s%s with JPWL", comment, version);
+#else
+                cp->comment = (char*)opj_malloc(clen+strlen(version)+1);
+								if(!cp->comment) {
+								        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate comment string\n");
+								        return OPJ_FALSE;
+								}
+                sprintf(cp->comment,"%s%s", comment, version);
+#endif
+                /* <<UniPG */
+				}
 
         /*
         calculate other encoding parameters
@@ -6289,6 +6380,10 @@
         /* initialize the mutiple tiles */
         /* ---------------------------- */
         cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
+        if (!cp->tcps) {
+                opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate tile coding parameters\n");
+                return OPJ_FALSE;
+        }
         if (parameters->numpocs) {
                 /* initialisation of POC */
                 opj_j2k_check_poc_val(parameters->POC,parameters->numpocs, (OPJ_UINT32)parameters->numresolution, image->numcomps, (OPJ_UINT32)parameters->tcp_numlayers, p_manager);
@@ -6300,7 +6395,7 @@
                 tcp->numlayers = (OPJ_UINT32)parameters->tcp_numlayers;
 
                 for (j = 0; j < tcp->numlayers; j++) {
-                        if(cp->m_specific_param.m_enc.m_cinema){
+                        if(OPJ_IS_CINEMA(cp->rsiz)){
                                 if (cp->m_specific_param.m_enc.m_fixed_quality) {
                                         tcp->distoratio[j] = parameters->tcp_distoratio[j];
                                 }
@@ -6346,24 +6441,54 @@
                 }
 
                 tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
-
+                if (!tcp->tccps) {
+                        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate tile component coding parameters\n");
+                        return OPJ_FALSE;
+                }
                 if (parameters->mct_data) {
                       
                     OPJ_UINT32 lMctSize = image->numcomps * image->numcomps * (OPJ_UINT32)sizeof(OPJ_FLOAT32);
                     OPJ_FLOAT32 * lTmpBuf = (OPJ_FLOAT32*)opj_malloc(lMctSize);
                     OPJ_INT32 * l_dc_shift = (OPJ_INT32 *) ((OPJ_BYTE *) parameters->mct_data + lMctSize);
 
+										if (!lTmpBuf) {
+                            opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate temp buffer\n");
+                            return OPJ_FALSE;
+                    }
+
                     tcp->mct = 2;
                     tcp->m_mct_coding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize);
+										if (! tcp->m_mct_coding_matrix) {
+                            opj_free(lTmpBuf);
+														lTmpBuf = NULL;
+                            opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate encoder MCT coding matrix \n");
+                            return OPJ_FALSE;
+                    }
                     memcpy(tcp->m_mct_coding_matrix,parameters->mct_data,lMctSize);
                     memcpy(lTmpBuf,parameters->mct_data,lMctSize);
 
                     tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize);
-                    assert(opj_matrix_inversion_f(lTmpBuf,(tcp->m_mct_decoding_matrix),image->numcomps));
+										if (! tcp->m_mct_decoding_matrix) {
+														opj_free(lTmpBuf);
+														lTmpBuf = NULL;
+                            opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate encoder MCT decoding matrix \n");
+                            return OPJ_FALSE;
+                    }
+                    if(opj_matrix_inversion_f(lTmpBuf,(tcp->m_mct_decoding_matrix),image->numcomps) == OPJ_FALSE) {
+                            opj_free(lTmpBuf);
+														lTmpBuf = NULL;
+                            opj_event_msg(p_manager, EVT_ERROR, "Failed to inverse encoder MCT decoding matrix \n");
+                            return OPJ_FALSE;
+										}
 
                     tcp->mct_norms = (OPJ_FLOAT64*)
                                     opj_malloc(image->numcomps * sizeof(OPJ_FLOAT64));
-
+										if (! tcp->mct_norms) {
+                            opj_free(lTmpBuf);
+														lTmpBuf = NULL;
+                            opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate encoder MCT norms \n");
+                            return OPJ_FALSE;
+                    }
                     opj_calculate_norms(tcp->mct_norms,image->numcomps,tcp->m_mct_decoding_matrix);
                     opj_free(lTmpBuf);
 
@@ -6372,9 +6497,22 @@
                             tccp->m_dc_level_shift = l_dc_shift[i];
                     }
 
-                    opj_j2k_setup_mct_encoding(tcp,image);                        
+                    if (opj_j2k_setup_mct_encoding(tcp,image) == OPJ_FALSE) {
+                        /* free will be handled by opj_j2k_destroy */
+												opj_event_msg(p_manager, EVT_ERROR, "Failed to setup j2k mct encoding\n");
+                        return OPJ_FALSE;
+                    }
                 }
                 else {
+                    if(tcp->mct==1 && image->numcomps == 3) { // RGB->YCC MCT is enabled
+                        if ((image->comps[0].dx != image->comps[1].dx) ||
+                                (image->comps[0].dx != image->comps[2].dx) ||
+                                (image->comps[0].dy != image->comps[1].dy) ||
+                                (image->comps[0].dy != image->comps[2].dy)) {
+                            opj_event_msg(p_manager, EVT_WARNING, "Cannot perform MCT on components with different sizes. Disabling MCT.\n");
+                            tcp->mct = 0;
+                        }
+                    }
                         for (i = 0; i < image->numcomps; i++) {
                                 opj_tccp_t *tccp = &tcp->tccps[i];
                                 opj_image_comp_t * l_comp = &(image->comps[i]);
@@ -6461,6 +6599,7 @@
                 opj_free(parameters->mct_data);
                 parameters->mct_data = 00;
         }
+        return OPJ_TRUE;
 }
 
 static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len)
@@ -7554,8 +7693,6 @@
 
                         if (! p_j2k->m_specific_param.m_decoder.m_can_decode){
                                 /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
-							while(1)  //liang
-							{
                                 if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
                                         opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
                                         return OPJ_FALSE;
@@ -7563,8 +7700,6 @@
 
                                 /* Read 2 bytes from buffer as the new marker ID */
                                 opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_current_marker,2);
-								if((l_current_marker & 0xff00) == 0xff00) break;
-							}
                         }
                 }
                 else {
@@ -7615,7 +7750,7 @@
         }
 
         opj_event_msg(p_manager, EVT_INFO, "Header of tile %d / %d has been read.\n",
-                        p_j2k->m_current_tile_number, (p_j2k->m_cp.th * p_j2k->m_cp.tw) - 1);
+                        p_j2k->m_current_tile_number+1, (p_j2k->m_cp.th * p_j2k->m_cp.tw));
 
         *p_tile_index = p_j2k->m_current_tile_number;
         *p_go_on = OPJ_TRUE;
@@ -7700,13 +7835,13 @@
                         p_j2k->m_specific_param.m_decoder.m_state =  0x0100;/*FIXME J2K_DEC_STATE_EOC;*/
                 }
                 else if (l_current_marker != J2K_MS_SOT)
-                {
-                        opj_event_msg(p_manager, EVT_ERROR, "Stream too short, expected SOT\n");
-                        
+                {       
                         if(opj_stream_get_number_byte_left(p_stream) == 0) {
                             p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
+                            opj_event_msg(p_manager, EVT_WARNING, "Stream does not end with EOC\n");
                             return OPJ_TRUE;
                         }
+                        opj_event_msg(p_manager, EVT_ERROR, "Stream too short, expected SOT\n");
                         return OPJ_FALSE;
                 }
         }
@@ -8134,23 +8269,21 @@
 
 opj_j2k_t* opj_j2k_create_decompress(void)
 {
-        opj_j2k_t *l_j2k = (opj_j2k_t*) opj_malloc(sizeof(opj_j2k_t));
+        opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1,sizeof(opj_j2k_t));
         if (!l_j2k) {
                 return 00;
         }
-        memset(l_j2k,0,sizeof(opj_j2k_t));
 
         l_j2k->m_is_decoder = 1;
         l_j2k->m_cp.m_is_decoder = 1;
 
-        l_j2k->m_specific_param.m_decoder.m_default_tcp = (opj_tcp_t*) opj_malloc(sizeof(opj_tcp_t));
+        l_j2k->m_specific_param.m_decoder.m_default_tcp = (opj_tcp_t*) opj_calloc(1,sizeof(opj_tcp_t));
         if (!l_j2k->m_specific_param.m_decoder.m_default_tcp) {
                 opj_j2k_destroy(l_j2k);
                 return 00;
         }
-        memset(l_j2k->m_specific_param.m_decoder.m_default_tcp,0,sizeof(opj_tcp_t));
 
-        l_j2k->m_specific_param.m_decoder.m_header_data = (OPJ_BYTE *) opj_malloc(OPJ_J2K_DEFAULT_HEADER_SIZE);
+        l_j2k->m_specific_param.m_decoder.m_header_data = (OPJ_BYTE *) opj_calloc(1,OPJ_J2K_DEFAULT_HEADER_SIZE);
         if (! l_j2k->m_specific_param.m_decoder.m_header_data) {
                 opj_j2k_destroy(l_j2k);
                 return 00;
@@ -8164,16 +8297,11 @@
 
         /* codestream index creation */
         l_j2k->cstr_index = opj_j2k_create_cstr_index();
-
-                        /*(opj_codestream_index_t*) opj_malloc(sizeof(opj_codestream_index_t));
         if (!l_j2k->cstr_index){
                 opj_j2k_destroy(l_j2k);
-                return NULL;
+                return 00;
         }
 
-        l_j2k->cstr_index->marker = (opj_marker_info_t*) opj_malloc(100 * sizeof(opj_marker_info_t));
-*/
-
         /* validation list creation */
         l_j2k->m_validation_list = opj_procedure_list_create();
         if (! l_j2k->m_validation_list) {
@@ -9588,6 +9716,10 @@
         assert(p_manager != 00);
 
         p_j2k->m_private_image = opj_image_create0();
+        if (! p_j2k->m_private_image) {
+                opj_event_msg(p_manager, EVT_ERROR, "Failed to allocate image header." );
+                return OPJ_FALSE;
+        }
         opj_copy_image_header(p_image, p_j2k->m_private_image);
 
         /* TODO_MSD: Find a better way */
@@ -9809,7 +9941,7 @@
         /* DEVELOPER CORNER, insert your custom procedures */
         opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_eoc );
 
-        if (p_j2k->m_cp.m_specific_param.m_enc.m_cinema) {
+        if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
                 opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_updated_tlm);
         }
 
@@ -9841,14 +9973,14 @@
         opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_cod );
         opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_qcd );
 
-        if (p_j2k->m_cp.m_specific_param.m_enc.m_cinema) {
+        if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
                 /* No need for COC or QCC, QCD and COD are used
                 opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_all_coc );
                 opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_all_qcc );
                 */
                 opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_tlm );
 
-                if (p_j2k->m_cp.m_specific_param.m_enc.m_cinema == OPJ_CINEMA4K_24) {
+                if (p_j2k->m_cp.rsiz == OPJ_PROFILE_CINEMA_4K) {
                         opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_poc );
                 }
         }
@@ -9860,7 +9992,7 @@
         }
 
         /* DEVELOPER CORNER, insert your custom procedures */
-        if (p_j2k->m_cp.rsiz & OPJ_MCT) {
+        if (p_j2k->m_cp.rsiz & OPJ_EXTENSION_MCT) {
                 opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_mct_data_group );
         }
         /* End of Developer Corner */
@@ -9909,7 +10041,7 @@
         p_data += l_current_nb_bytes_written;
         p_total_data_size -= l_current_nb_bytes_written;
 
-        if (l_cp->m_specific_param.m_enc.m_cinema == 0) {
+        if (!OPJ_IS_CINEMA(l_cp->rsiz)) {
 #if 0
                 for (compno = 1; compno < p_j2k->m_private_image->numcomps; compno++) {
                         l_current_nb_bytes_written = 0;
@@ -9946,7 +10078,7 @@
         /* Writing Psot in SOT marker */
         opj_write_bytes(l_begin_data + 6,l_nb_bytes_written,4);                                 /* PSOT */
 
-        if (l_cp->m_specific_param.m_enc.m_cinema){
+        if (OPJ_IS_CINEMA(l_cp->rsiz)){
                 opj_j2k_update_tlm(p_j2k,l_nb_bytes_written);
         }
 
@@ -10010,7 +10142,7 @@
                 /* Writing Psot in SOT marker */
                 opj_write_bytes(l_begin_data + 6,l_part_tile_size,4);                                   /* PSOT */
 
-                if (l_cp->m_specific_param.m_enc.m_cinema) {
+                if (OPJ_IS_CINEMA(l_cp->rsiz)) {
                         opj_j2k_update_tlm(p_j2k,l_part_tile_size);
                 }
 
@@ -10051,7 +10183,7 @@
                         /* Writing Psot in SOT marker */
                         opj_write_bytes(l_begin_data + 6,l_part_tile_size,4);                                   /* PSOT */
 
-                        if (l_cp->m_specific_param.m_enc.m_cinema) {
+                        if (OPJ_IS_CINEMA(l_cp->rsiz)) {
                                 opj_j2k_update_tlm(p_j2k,l_part_tile_size);
                         }
 
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/j2k.h b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/j2k.h
index 4228bd6..909e351 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/j2k.h
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/j2k.h
@@ -304,8 +304,6 @@
 
 typedef struct opj_encoding_param
 {
-	/** Digital cinema profile*/
-	OPJ_CINEMA_MODE m_cinema;
 	/** Maximum rate for each component. If == 0, component size limitation is not considered */
 	OPJ_UINT32 m_max_comp_size;
 	/** Position of tile part flag in progression order*/
@@ -343,7 +341,7 @@
 	/** Size of the image in bits*/
 	/*int img_size;*/
 	/** Rsiz*/
-	OPJ_RSIZ_CAPABILITIES rsiz;
+    OPJ_UINT16 rsiz;
 	/** XTOsiz */
 	OPJ_UINT32 tx0; /* MSD see norm */
 	/** YTOsiz */
@@ -596,7 +594,7 @@
 opj_j2k_t* opj_j2k_create_compress(void);
 
 
-void opj_j2k_setup_encoder(	opj_j2k_t *p_j2k,
+OPJ_BOOL opj_j2k_setup_encoder(	opj_j2k_t *p_j2k,
 						    opj_cparameters_t *parameters,
 						    opj_image_t *image,
 						    opj_event_mgr_t * p_manager);
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/jp2.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/jp2.c
index 0a16d1e..dd188c1 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/jp2.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/jp2.c
@@ -537,12 +537,11 @@
 	p_image_header_data += 2;
 
 	/* allocate memory for components */
-	jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
+	jp2->comps = (opj_jp2_comps_t*) opj_calloc(jp2->numcomps, sizeof(opj_jp2_comps_t));
 	if (jp2->comps == 0) {
 		opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle image header (ihdr)\n");
 		return OPJ_FALSE;
 	}
-	memset(jp2->comps,0,jp2->numcomps * sizeof(opj_jp2_comps_t));
 
 	opj_read_bytes(p_image_header_data,&(jp2->bpc),1);			/* BPC */
 	++ p_image_header_data;
@@ -574,11 +573,10 @@
 	assert(p_nb_bytes_written != 00);
 
 	/* default image header is 22 bytes wide */
-	l_ihdr_data = (OPJ_BYTE *) opj_malloc(22);
+	l_ihdr_data = (OPJ_BYTE *) opj_calloc(1,22);
 	if (l_ihdr_data == 00) {
 		return 00;
 	}
-	memset(l_ihdr_data,0,22);
 
 	l_current_ihdr_ptr = l_ihdr_data;
 	
@@ -627,11 +625,10 @@
 	assert(jp2 != 00);
 	assert(p_nb_bytes_written != 00);
 
-	l_bpcc_data = (OPJ_BYTE *) opj_malloc(l_bpcc_size);
+	l_bpcc_data = (OPJ_BYTE *) opj_calloc(1,l_bpcc_size);
 	if (l_bpcc_data == 00) {
 		return 00;
 	}
-	memset(l_bpcc_data,0,l_bpcc_size);
 
 	l_current_bpcc_ptr = l_bpcc_data;
 
@@ -709,11 +706,10 @@
 			return 00;
 	}
 
-	l_colr_data = (OPJ_BYTE *) opj_malloc(l_colr_size);
+	l_colr_data = (OPJ_BYTE *) opj_calloc(1,l_colr_size);
 	if (l_colr_data == 00) {
 		return 00;
 	}
-	memset(l_colr_data,0,l_colr_size);
 	
 	l_current_colr_ptr = l_colr_data;
 
@@ -859,7 +855,11 @@
 	old_comps = image->comps;
 	new_comps = (opj_image_comp_t*)
 			opj_malloc(nr_channels * sizeof(opj_image_comp_t));
-
+	if (!new_comps) {
+		/* FIXME no error code for opj_jp2_apply_pclr */
+		/* FIXME event manager error callback */
+		return;
+	}
 	for(i = 0; i < nr_channels; ++i) {
 		pcol = cmap[i].pcol; cmp = cmap[i].cmp;
 
@@ -875,6 +875,13 @@
 		/* Palette mapping: */
 		new_comps[i].data = (OPJ_INT32*)
 				opj_malloc(old_comps[cmp].w * old_comps[cmp].h * sizeof(OPJ_INT32));
+		if (!new_comps[i].data) {
+			opj_free(new_comps);
+			new_comps = NULL;
+			/* FIXME no error code for opj_jp2_apply_pclr */
+			/* FIXME event manager error callback */
+			return;
+		}
 		new_comps[i].prec = channel_size[i];
 		new_comps[i].sgnd = channel_sign[i];
 	}
@@ -1236,6 +1243,10 @@
 	++p_colr_header_data;
 
 	if (jp2->meth == 1) {
+		if (p_colr_header_size < 7) {
+			opj_event_msg(p_manager, EVT_ERROR, "Bad COLR header box (bad size: %d)\n", p_colr_header_size);
+			return OPJ_FALSE;
+		}
 		if (p_colr_header_size > 7) {
 			/* testcase Altona_Technical_v20_x4.pdf */
 			opj_event_msg(p_manager, EVT_WARNING, "Bad COLR header box (bad size: %d)\n", p_colr_header_size);
@@ -1243,48 +1254,6 @@
 
 		opj_read_bytes(p_colr_header_data,&jp2->enumcs ,4);			/* EnumCS */
         
-		p_colr_header_data += 4;
-
-		if(jp2->enumcs == 14)/* CIELab */
-		{
-			OPJ_UINT32 *cielab;
-			OPJ_UINT32 rl, ol, ra, oa, rb, ob, il;
-
-			cielab = (OPJ_UINT32*)opj_malloc(9 * sizeof(OPJ_UINT32));
-			cielab[0] = 14; /* enumcs */
-
-			if(p_colr_header_size == 7)/* default values */
-			{
-				rl = ra = rb = ol = oa = ob = 0;
-				il = 0x00443530; /* D50 */
-				cielab[1] = 0x44454600;/* DEF */
-			}
-			else if(p_colr_header_size == 35)
-			{
-				opj_read_bytes(p_colr_header_data, &rl, 4);
-				p_colr_header_data += 4;
-				opj_read_bytes(p_colr_header_data, &ol, 4);
-				p_colr_header_data += 4;
-				opj_read_bytes(p_colr_header_data, &ra, 4);
-				p_colr_header_data += 4;
-				opj_read_bytes(p_colr_header_data, &oa, 4);
-				p_colr_header_data += 4;
-				opj_read_bytes(p_colr_header_data, &rb, 4);
-				p_colr_header_data += 4;
-				opj_read_bytes(p_colr_header_data, &ob, 4);
-				p_colr_header_data += 4;
-				opj_read_bytes(p_colr_header_data, &il, 4);
-				p_colr_header_data += 4;
-				cielab[1] = 0;
-			}
-			cielab[2] = rl; cielab[4] = ra; cielab[6] = rb;
-			cielab[3] = ol; cielab[5] = oa; cielab[7] = ob;
-			cielab[8] = il;
-
-			jp2->color.icc_profile_buf = (unsigned char*)cielab;
-			jp2->color.icc_profile_len = 0;
-		}
-
         jp2->color.jp2_has_colr = 1;
 	}
 	else if (jp2->meth == 2) {
@@ -1293,13 +1262,12 @@
 		OPJ_INT32 icc_len = (OPJ_INT32)p_colr_header_size - 3;
 
 		jp2->color.icc_profile_len = (OPJ_UINT32)icc_len;
-		jp2->color.icc_profile_buf = (OPJ_BYTE*) opj_malloc((size_t)icc_len);
+		jp2->color.icc_profile_buf = (OPJ_BYTE*) opj_calloc(1,(size_t)icc_len);
         if (!jp2->color.icc_profile_buf)
         {
             jp2->color.icc_profile_len = 0;
             return OPJ_FALSE;
         }
-		memset(jp2->color.icc_profile_buf, 0, (size_t)icc_len * sizeof(OPJ_BYTE));
 
 		for (it_icc_value = 0; it_icc_value < icc_len; ++it_icc_value)
 		{
@@ -1312,7 +1280,7 @@
 	}
 	else if (jp2->meth > 2)
     {
-        /*	ISO/IEC 15444-1:2004 (E), Table I.9 ?Legal METH values:
+        /*	ISO/IEC 15444-1:2004 (E), Table I.9 ­ Legal METH values:
         conforming JP2 reader shall ignore the entire Colour Specification box.*/
         opj_event_msg(p_manager, EVT_INFO, "COLR BOX meth value is not a regular value (%d), " 
             "so we will ignore the entire Colour Specification box. \n", jp2->meth);
@@ -1361,7 +1329,6 @@
 		    if( !jp2->color.jp2_pclr->cmap)
 			    opj_jp2_free_pclr(&(jp2->color));
 		    else
-				if(!p_image->useColorSpace)
 			    opj_jp2_apply_pclr(p_image, &(jp2->color));
 	    }
 
@@ -1487,15 +1454,13 @@
 	assert(jp2 != 00);
 	assert(p_manager != 00);
 
-	l_ftyp_data = (OPJ_BYTE *) opj_malloc(l_ftyp_size);
+	l_ftyp_data = (OPJ_BYTE *) opj_calloc(1,l_ftyp_size);
 	
 	if (l_ftyp_data == 00) {
 		opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle ftyp data\n");
 		return OPJ_FALSE;
 	}
 
-	memset(l_ftyp_data,0,l_ftyp_size);
-
 	l_current_data_ptr = l_ftyp_data;
 
 	opj_write_bytes(l_current_data_ptr, l_ftyp_size,4); /* box size */
@@ -1606,7 +1571,7 @@
 /* JP2 encoder interface                                             */
 /* ----------------------------------------------------------------------- */
 
-void opj_jp2_setup_encoder(	opj_jp2_t *jp2,
+OPJ_BOOL opj_jp2_setup_encoder(	opj_jp2_t *jp2,
                             opj_cparameters_t *parameters,
                             opj_image_t *image,
                             opj_event_mgr_t * p_manager)
@@ -1616,7 +1581,7 @@
   OPJ_UINT32 sign;
 
 	if(!jp2 || !parameters || !image)
-		return;
+		return OPJ_FALSE;
 
 	/* setup the J2K codec */
 	/* ------------------- */
@@ -1624,10 +1589,12 @@
 	/* Check if number of components respects standard */
 	if (image->numcomps < 1 || image->numcomps > 16384) {
 		opj_event_msg(p_manager, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n");
-		return;
+		return OPJ_FALSE;
 	}
 
-	opj_j2k_setup_encoder(jp2->j2k, parameters, image, p_manager );
+	if (opj_j2k_setup_encoder(jp2->j2k, parameters, image, p_manager ) == OPJ_FALSE) {
+		return OPJ_FALSE;
+	}
 
 	/* setup the JP2 codec */
 	/* ------------------- */
@@ -1638,22 +1605,23 @@
 	jp2->minversion = 0;	/* MinV */
 	jp2->numcl = 1;
 	jp2->cl = (OPJ_UINT32*) opj_malloc(jp2->numcl * sizeof(OPJ_UINT32));
-    if (!jp2->cl){
-        jp2->cl = NULL;
-        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory when setup the JP2 encoder\n");
-        return;
-    }
+	if (!jp2->cl){
+		jp2->cl = NULL;
+		opj_event_msg(p_manager, EVT_ERROR, "Not enough memory when setup the JP2 encoder\n");
+		return OPJ_FALSE;
+	}
 	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));
-    if (!jp2->comps) {
-        jp2->comps = NULL;
-        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory when setup the JP2 encoder\n");
-        return;
-    }
+	if (!jp2->comps) {
+		jp2->comps = NULL;
+		opj_event_msg(p_manager, EVT_ERROR, "Not enough memory when setup the JP2 encoder\n");
+		/* Memory of jp2->cl will be freed by opj_jp2_destroy */
+		return OPJ_FALSE;
+	}
 
 	jp2->h = image->y1 - image->y0;		/* HEIGHT */
 	jp2->w = image->x1 - image->x0;		/* WIDTH */
@@ -1696,6 +1664,8 @@
 	jp2->approx = 0;		/* APPROX */
 
 	jp2->jpip_on = parameters->jpip_on;
+
+	return OPJ_TRUE;
 }
 
 OPJ_BOOL opj_jp2_encode(opj_jp2_t *jp2,
@@ -1846,13 +1816,12 @@
 	assert(jp2 != 00);
 	assert(p_manager != 00);
 
-	l_current_data = (OPJ_BYTE*)opj_malloc(l_last_data_size);
+	l_current_data = (OPJ_BYTE*)opj_calloc(1,l_last_data_size);
 
 	if (l_current_data == 00) {
 		opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle jpeg2000 file header\n");
 		return OPJ_FALSE;
 	}
-	memset(l_current_data, 0 , l_last_data_size);
 
 	while (opj_jp2_read_boxhdr(&box,&l_nb_bytes_read,stream,p_manager)) {
 		/* is it the codestream box ? */
@@ -1874,8 +1843,7 @@
 			return OPJ_FALSE;
 		}
 		/* testcase 1851.pdf.SIGSEGV.ce9.948 */
-		/* testcase K-5787457125613568 */
-		else if	(box.length < l_nb_bytes_read || box.length > opj_stream_get_number_byte_left(stream)) {
+		else if	(box.length < l_nb_bytes_read) {
 			opj_event_msg(p_manager, EVT_ERROR, "invalid box size %d (%x)\n", box.length, box.type);
 			opj_free(l_current_data);
 			return OPJ_FALSE;
@@ -2123,12 +2091,11 @@
 	/* div by 4 */
 	jp2->numcl = l_remaining_bytes >> 2;
 	if (jp2->numcl) {
-		jp2->cl = (OPJ_UINT32 *) opj_malloc(jp2->numcl * sizeof(OPJ_UINT32));
+		jp2->cl = (OPJ_UINT32 *) opj_calloc(jp2->numcl, sizeof(OPJ_UINT32));
 		if (jp2->cl == 00) {
 			opj_event_msg(p_manager, EVT_ERROR, "Not enough memory with FTYP Box\n");
 			return OPJ_FALSE;
 		}
-		memset(jp2->cl,0,jp2->numcl * sizeof(OPJ_UINT32));
 	}
 
 	for (i = 0; i < jp2->numcl; ++i)
@@ -2225,9 +2192,6 @@
 		}
 
 		l_current_handler = opj_jp2_img_find_handler(box.type);
-		//BUGID:0055999
-		//test file: fuzz-signal_sigsegv_6b88de_1123_2509.pdf
-		if (box.length < l_box_size) return OPJ_FALSE;
 		l_current_data_size = box.length - l_box_size;
 		p_header_data += l_box_size;
 
@@ -2574,9 +2538,8 @@
 
 opj_jp2_t* opj_jp2_create(OPJ_BOOL p_is_decoder)
 {
-	opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t));
+	opj_jp2_t *jp2 = (opj_jp2_t*)opj_calloc(1,sizeof(opj_jp2_t));
 	if (jp2) {
-		memset(jp2,0,sizeof(opj_jp2_t));
 
 		/* create the J2K codec */
 		if (! p_is_decoder) {
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/jp2.h b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/jp2.h
index c11d2f3..1e41fb6 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/jp2.h
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/jp2.h
@@ -278,8 +278,9 @@
  * @param parameters compression parameters
  * @param image input filled image
  * @param p_manager  FIXME DOC
+ * @return OPJ_TRUE if successful, OPJ_FALSE otherwise
 */
-void opj_jp2_setup_encoder(  opj_jp2_t *jp2, 
+OPJ_BOOL opj_jp2_setup_encoder(  opj_jp2_t *jp2, 
                             opj_cparameters_t *parameters, 
                             opj_image_t *image, 
                             opj_event_mgr_t * p_manager);
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/mct.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/mct.c
index 89f8222..60ee096 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/mct.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/mct.c
@@ -150,43 +150,42 @@
 {
 	OPJ_UINT32 i;
 #ifdef __SSE__
-    __m128 vrv, vgu, vgv, vbu;
-    vrv = _mm_set1_ps(1.402f);
-    vgu = _mm_set1_ps(0.34413f);
-    vgv = _mm_set1_ps(0.71414f);
-    vbu = _mm_set1_ps(1.772f);
-    for (i = 0; i < (n >> 3); ++i) {
-        __m128 vy, vu, vv;
-        __m128 vr, vg, vb;
+	__m128 vrv, vgu, vgv, vbu;
+	vrv = _mm_set1_ps(1.402f);
+	vgu = _mm_set1_ps(0.34413f);
+	vgv = _mm_set1_ps(0.71414f);
+	vbu = _mm_set1_ps(1.772f);
+	for (i = 0; i < (n >> 3); ++i) {
+		__m128 vy, vu, vv;
+		__m128 vr, vg, vb;
 
-        vy = _mm_load_ps(c0);
-        vu = _mm_load_ps(c1);
-        vv = _mm_load_ps(c2);
-        vr = _mm_add_ps(vy, _mm_mul_ps(vv, vrv));
-        vg = _mm_sub_ps(_mm_sub_ps(vy, _mm_mul_ps(vu, vgu)), _mm_mul_ps(vv, vgv));
-        vb = _mm_add_ps(vy, _mm_mul_ps(vu, vbu));
-        _mm_store_ps(c0, vr);
-        _mm_store_ps(c1, vg);
-        _mm_store_ps(c2, vb);
-        c0 += 4;
-        c1 += 4;
-        c2 += 4;
+		vy = _mm_load_ps(c0);
+		vu = _mm_load_ps(c1);
+		vv = _mm_load_ps(c2);
+		vr = _mm_add_ps(vy, _mm_mul_ps(vv, vrv));
+		vg = _mm_sub_ps(_mm_sub_ps(vy, _mm_mul_ps(vu, vgu)), _mm_mul_ps(vv, vgv));
+		vb = _mm_add_ps(vy, _mm_mul_ps(vu, vbu));
+		_mm_store_ps(c0, vr);
+		_mm_store_ps(c1, vg);
+		_mm_store_ps(c2, vb);
+		c0 += 4;
+		c1 += 4;
+		c2 += 4;
 
-        vy = _mm_load_ps(c0);
-        vu = _mm_load_ps(c1);
-        vv = _mm_load_ps(c2);
-        vr = _mm_add_ps(vy, _mm_mul_ps(vv, vrv));
-        vg = _mm_sub_ps(_mm_sub_ps(vy, _mm_mul_ps(vu, vgu)), _mm_mul_ps(vv, vgv));
-        vb = _mm_add_ps(vy, _mm_mul_ps(vu, vbu));
-        _mm_store_ps(c0, vr);
-        _mm_store_ps(c1, vg);
-        _mm_store_ps(c2, vb);
-        c0 += 4;
-        c1 += 4;
-        c2 += 4;
-    }
-    n &= 7;
-
+		vy = _mm_load_ps(c0);
+		vu = _mm_load_ps(c1);
+		vv = _mm_load_ps(c2);
+		vr = _mm_add_ps(vy, _mm_mul_ps(vv, vrv));
+		vg = _mm_sub_ps(_mm_sub_ps(vy, _mm_mul_ps(vu, vgu)), _mm_mul_ps(vv, vgv));
+		vb = _mm_add_ps(vy, _mm_mul_ps(vu, vbu));
+		_mm_store_ps(c0, vr);
+		_mm_store_ps(c1, vg);
+		_mm_store_ps(c2, vb);
+		c0 += 4;
+		c1 += 4;
+		c2 += 4;
+	}
+	n &= 7;
 #endif
 	for(i = 0; i < n; ++i) {
 		OPJ_FLOAT32 y = c0[i];
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/mqc.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/mqc.c
index 18fcc47..075594b 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/mqc.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/mqc.c
@@ -362,7 +362,9 @@
 opj_mqc_t* opj_mqc_create(void) {
 	opj_mqc_t *mqc = (opj_mqc_t*)opj_malloc(sizeof(opj_mqc_t));
 #ifdef MQC_PERF_OPT
-	mqc->buffer = NULL;
+	if (mqc) {
+		mqc->buffer = NULL;
+	}
 #endif
 	return mqc;
 }
@@ -370,7 +372,9 @@
 void opj_mqc_destroy(opj_mqc_t *mqc) {
 	if(mqc) {
 #ifdef MQC_PERF_OPT
-		opj_free(mqc->buffer);
+		if (mqc->buffer) {
+			opj_free(mqc->buffer);
+		}
 #endif
 		opj_free(mqc);
 	}
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/openjpeg.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/openjpeg.c
index 89bb75a..4907c0c 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/openjpeg.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/openjpeg.c
@@ -132,7 +132,7 @@
 #ifdef _WIN32
 #ifndef OPJ_STATIC
 BOOL APIENTRY
-DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
+DllMain(HINSTANCE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
 
 	OPJ_ARG_NOT_USED(lpReserved);
 	OPJ_ARG_NOT_USED(hModule);
@@ -169,7 +169,6 @@
 	if (!l_codec){
 		return 00;
 	}
-	memset(l_codec, 0, sizeof(opj_codec_private_t));
 
 	l_codec->is_decompressor = 1;
 
@@ -546,7 +545,6 @@
 	if (!l_codec) {
 		return 00;
 	}
-	memset(l_codec, 0, sizeof(opj_codec_private_t));
 	
 	l_codec->is_decompressor = 0;
 
@@ -574,7 +572,7 @@
 
 			l_codec->m_codec_data.m_compression.opj_destroy = (void (*) (void *)) opj_j2k_destroy;
 
-			l_codec->m_codec_data.m_compression.opj_setup_encoder = (void (*) (	void *,
+			l_codec->m_codec_data.m_compression.opj_setup_encoder = (OPJ_BOOL (*) (	void *,
 																				opj_cparameters_t *,
 																				struct opj_image *,
 																				struct opj_event_mgr * )) opj_j2k_setup_encoder;
@@ -611,7 +609,7 @@
 
 			l_codec->m_codec_data.m_compression.opj_destroy = (void (*) (void *)) opj_jp2_destroy;
 
-			l_codec->m_codec_data.m_compression.opj_setup_encoder = (void (*) (	void *,
+			l_codec->m_codec_data.m_compression.opj_setup_encoder = (OPJ_BOOL (*) (	void *,
 																				opj_cparameters_t *,
 																				struct opj_image *,
 																				struct opj_event_mgr * )) opj_jp2_setup_encoder;
@@ -639,10 +637,11 @@
 	if(parameters) {
 		memset(parameters, 0, sizeof(opj_cparameters_t));
 		/* default coding parameters */
-		parameters->cp_cinema = OPJ_OFF; 
+        parameters->cp_cinema = OPJ_OFF; /* DEPRECATED */
+        parameters->rsiz = OPJ_PROFILE_NONE;
 		parameters->max_comp_size = 0;
 		parameters->numresolution = 6;
-		parameters->cp_rsiz = OPJ_STD_RSIZ;
+        parameters->cp_rsiz = OPJ_STD_RSIZ; /* DEPRECATED */
 		parameters->cblockw_init = 64;
 		parameters->cblockh_init = 64;
 		parameters->prog_order = OPJ_LRCP;
@@ -793,8 +792,11 @@
 	OPJ_UINT32 l_mct_total_size = l_matrix_size + l_dc_shift_size;
 
 	/* add MCT capability */
-	OPJ_INT32 rsiz = (OPJ_INT32)parameters->cp_rsiz | (OPJ_INT32)OPJ_MCT;
-	parameters->cp_rsiz = (OPJ_RSIZ_CAPABILITIES)rsiz;
+    if (OPJ_IS_PART2(parameters->rsiz)) {
+        parameters->rsiz |= OPJ_EXTENSION_MCT;
+    } else {
+        parameters->rsiz = ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_MCT));
+    }
 	parameters->irreversible = 1;
 
 	/* use array based MCT */
@@ -917,12 +919,12 @@
 	}
 }
 
-opj_stream_t* OPJ_CALLCONV opj_stream_create_default_file_stream_v3 (const char *fname, OPJ_BOOL p_is_read_stream)
+opj_stream_t* OPJ_CALLCONV opj_stream_create_default_file_stream (const char *fname, OPJ_BOOL p_is_read_stream)
 {
-    return opj_stream_create_file_stream_v3(fname, OPJ_J2K_STREAM_CHUNK_SIZE, p_is_read_stream);
+    return opj_stream_create_file_stream(fname, OPJ_J2K_STREAM_CHUNK_SIZE, p_is_read_stream);
 }
 
-opj_stream_t* OPJ_CALLCONV opj_stream_create_file_stream_v3 (
+opj_stream_t* OPJ_CALLCONV opj_stream_create_file_stream (
         const char *fname, 
 		OPJ_SIZE_T p_size, 
         OPJ_BOOL p_is_read_stream)
@@ -949,7 +951,7 @@
         return NULL;
     }
 
-    opj_stream_set_user_data_v3(l_stream, p_file, (opj_stream_free_user_data_fn) fclose);
+    opj_stream_set_user_data(l_stream, p_file, (opj_stream_free_user_data_fn) fclose);
     opj_stream_set_user_data_length(l_stream, opj_get_data_length_from_file(p_file));
     opj_stream_set_read_function(l_stream, (opj_stream_read_fn) opj_read_from_file);
     opj_stream_set_write_function(l_stream, (opj_stream_write_fn) opj_write_from_file);
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/openjpeg.h b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/openjpeg.h
index 29a9a90..988db72 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/openjpeg.h
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/openjpeg.h
@@ -42,11 +42,6 @@
 #ifndef OPENJPEG_H
 #define OPENJPEG_H
 
-#ifndef OPJ_STATIC
-#define OPJ_STATIC
-#endif
-
-
 
 /* 
 ==========================================================
@@ -116,6 +111,7 @@
 typedef float         OPJ_FLOAT32;
 typedef double        OPJ_FLOAT64;
 typedef unsigned char OPJ_BYTE;
+
 #include "opj_stdint.h"
 
 typedef int8_t   OPJ_INT8;
@@ -177,30 +173,88 @@
 #define OPJ_JP2_INFO		128	/**< JP2 file information */
 #define OPJ_JP2_IND			256	/**< JP2 file index */
 
+/**
+ * JPEG 2000 Profiles, see Table A.10 from 15444-1 (updated in various AMD)
+ * These values help chosing the RSIZ value for the J2K codestream.
+ * The RSIZ value triggers various encoding options, as detailed in Table A.10.
+ * If OPJ_PROFILE_PART2 is chosen, it has to be combined with one or more extensions
+ * described hereunder.
+ *   Example: rsiz = OPJ_PROFILE_PART2 | OPJ_EXTENSION_MCT;
+ * For broadcast profiles, the OPJ_PROFILE value has to be combined with the targeted
+ * mainlevel (3-0 LSB, value between 0 and 11):
+ *   Example: rsiz = OPJ_PROFILE_BC_MULTI | 0x0005; (here mainlevel 5)
+ * For IMF profiles, the OPJ_PROFILE value has to be combined with the targeted mainlevel
+ * (3-0 LSB, value between 0 and 11) and sublevel (7-4 LSB, value between 0 and 9):
+ *   Example: rsiz = OPJ_PROFILE_IMF_2K | 0x0040 | 0x0005; (here main 5 and sublevel 4)
+ * */
+#define OPJ_PROFILE_NONE        0x0000 /** no profile, conform to 15444-1 */
+#define OPJ_PROFILE_0           0x0001 /** Profile 0 as described in 15444-1,Table A.45 */
+#define OPJ_PROFILE_1           0x0002 /** Profile 1 as described in 15444-1,Table A.45 */
+#define OPJ_PROFILE_PART2       0x8000 /** At least 1 extension defined in 15444-2 (Part-2) */
+#define OPJ_PROFILE_CINEMA_2K   0x0003 /** 2K cinema profile defined in 15444-1 AMD1 */
+#define OPJ_PROFILE_CINEMA_4K   0x0004 /** 4K cinema profile defined in 15444-1 AMD1 */
+#define OPJ_PROFILE_CINEMA_S2K  0x0005 /** Scalable 2K cinema profile defined in 15444-1 AMD2 */
+#define OPJ_PROFILE_CINEMA_S4K  0x0006 /** Scalable 4K cinema profile defined in 15444-1 AMD2 */
+#define OPJ_PROFILE_CINEMA_LTS  0x0007 /** Long term storage cinema profile defined in 15444-1 AMD2 */
+#define OPJ_PROFILE_BC_SINGLE   0x0100 /** Single Tile Broadcast profile defined in 15444-1 AMD3 */
+#define OPJ_PROFILE_BC_MULTI    0x0200 /** Multi Tile Broadcast profile defined in 15444-1 AMD3 */
+#define OPJ_PROFILE_BC_MULTI_R  0x0300 /** Multi Tile Reversible Broadcast profile defined in 15444-1 AMD3 */
+#define OPJ_PROFILE_IMF_2K      0x0400 /** 2K Single Tile Lossy IMF profile defined in 15444-1 AMD 8 */
+#define OPJ_PROFILE_IMF_4K      0x0401 /** 4K Single Tile Lossy IMF profile defined in 15444-1 AMD 8 */
+#define OPJ_PROFILE_IMF_8K      0x0402 /** 8K Single Tile Lossy IMF profile defined in 15444-1 AMD 8 */
+#define OPJ_PROFILE_IMF_2K_R    0x0403 /** 2K Single/Multi Tile Reversible IMF profile defined in 15444-1 AMD 8 */
+#define OPJ_PROFILE_IMF_4K_R    0x0800 /** 4K Single/Multi Tile Reversible IMF profile defined in 15444-1 AMD 8 */
+#define OPJ_PROFILE_IMF_8K_R    0x0801  /** 8K Single/Multi Tile Reversible IMF profile defined in 15444-1 AMD 8 */
+
+/**
+ * JPEG 2000 Part-2 extensions
+ * */
+#define OPJ_EXTENSION_NONE      0x0000 /** No Part-2 extension */
+#define OPJ_EXTENSION_MCT       0x0100  /** Custom MCT support */
+
+/**
+ * JPEG 2000 profile macros
+ * */
+#define OPJ_IS_CINEMA(v)     (((v) >= OPJ_PROFILE_CINEMA_2K)&&((v) <= OPJ_PROFILE_CINEMA_S4K))
+#define OPJ_IS_STORAGE(v)    ((v) == OPJ_PROFILE_CINEMA_LTS)
+#define OPJ_IS_BROADCAST(v)  (((v) >= OPJ_PROFILE_BC_SINGLE)&&((v) <= ((OPJ_PROFILE_BC_MULTI_R) | (0x000b))))
+#define OPJ_IS_IMF(v)        (((v) >= OPJ_PROFILE_IMF_2K)&&((v) <= ((OPJ_PROFILE_IMF_8K_R) | (0x009b))))
+#define OPJ_IS_PART2(v)      ((v) & OPJ_PROFILE_PART2)
+
+/**
+ * JPEG 2000 codestream and component size limits in cinema profiles
+ * */
+#define OPJ_CINEMA_24_CS     1302083   	/** Maximum codestream length for 24fps */
+#define OPJ_CINEMA_48_CS     651041     /** Maximum codestream length for 48fps */
+#define OPJ_CINEMA_24_COMP   1041666    /** Maximum size per color component for 2K & 4K @ 24fps */
+#define OPJ_CINEMA_48_COMP   520833		/** Maximum size per color component for 2K @ 48fps */
 
 /* 
 ==========================================================
    enum definitions
 ==========================================================
 */
-/** 
+
+/**
+ * DEPRECATED: use RSIZ, OPJ_PROFILE_* and OPJ_EXTENSION_* instead
  * Rsiz Capabilities
  * */
 typedef enum RSIZ_CAPABILITIES {
-	OPJ_STD_RSIZ = 0,		/** Standard JPEG2000 profile*/
-	OPJ_CINEMA2K = 3,		/** Profile name for a 2K image*/
-	OPJ_CINEMA4K = 4,		/** Profile name for a 4K image*/
-	OPJ_MCT = 0x8100
+    OPJ_STD_RSIZ = 0,		/** Standard JPEG2000 profile*/
+    OPJ_CINEMA2K = 3,		/** Profile name for a 2K image*/
+    OPJ_CINEMA4K = 4,		/** Profile name for a 4K image*/
+    OPJ_MCT = 0x8100
 } OPJ_RSIZ_CAPABILITIES;
 
-/** 
+/**
+ * DEPRECATED: use RSIZ, OPJ_PROFILE_* and OPJ_EXTENSION_* instead
  * Digital cinema operation mode
  * */
 typedef enum CINEMA_MODE {
-	OPJ_OFF = 0,			/** Not Digital Cinema*/
-	OPJ_CINEMA2K_24 = 1,	/** 2K Digital Cinema at 24 fps*/
-	OPJ_CINEMA2K_48 = 2,	/** 2K Digital Cinema at 48 fps*/
-	OPJ_CINEMA4K_24 = 3		/** 4K Digital Cinema at 24 fps*/
+    OPJ_OFF = 0,			/** Not Digital Cinema*/
+    OPJ_CINEMA2K_24 = 1,	/** 2K Digital Cinema at 24 fps*/
+    OPJ_CINEMA2K_48 = 2,	/** 2K Digital Cinema at 48 fps*/
+    OPJ_CINEMA4K_24 = 3		/** 4K Digital Cinema at 24 fps*/
 }OPJ_CINEMA_MODE;
 
 /** 
@@ -219,12 +273,13 @@
  * Supported image color spaces
 */
 typedef enum COLOR_SPACE {
-	OPJ_CLRSPC_UNKNOWN = -1,	/**< not supported by the library */
-	OPJ_CLRSPC_UNSPECIFIED = 0,	/**< not specified in the codestream */ 
-	OPJ_CLRSPC_SRGB = 1,		/**< sRGB */
-	OPJ_CLRSPC_GRAY = 2,		/**< grayscale */
-	OPJ_CLRSPC_SYCC = 3,		/**< YUV */
-  OPJ_CLRSPC_EYCC = 4		/**< e-YCC */
+    OPJ_CLRSPC_UNKNOWN = -1,	/**< not supported by the library */
+    OPJ_CLRSPC_UNSPECIFIED = 0,	/**< not specified in the codestream */
+    OPJ_CLRSPC_SRGB = 1,		/**< sRGB */
+    OPJ_CLRSPC_GRAY = 2,		/**< grayscale */
+    OPJ_CLRSPC_SYCC = 3,		/**< YUV */
+    OPJ_CLRSPC_EYCC = 4,        /**< e-YCC */
+    OPJ_CLRSPC_CMYK = 5         /**< CMYK */
 } OPJ_COLOR_SPACE;
 
 /**
@@ -234,7 +289,9 @@
 	OPJ_CODEC_UNKNOWN = -1,	/**< place-holder */
 	OPJ_CODEC_J2K  = 0,		/**< JPEG-2000 codestream : read/write */
 	OPJ_CODEC_JPT  = 1,		/**< JPT-stream (JPEG 2000, JPIP) : read only */
-	OPJ_CODEC_JP2  = 2 		/**< JPEG-2000 file format : read/write */
+    OPJ_CODEC_JP2  = 2,		/**< JP2 file format : read/write */
+    OPJ_CODEC_JPP  = 3,		/**< JPP-stream (JPEG 2000, JPIP) : to be coded */
+    OPJ_CODEC_JPX  = 4		/**< JPX file format (JPEG 2000 Part-2) : to be coded */
 } OPJ_CODEC_FORMAT;
 
 
@@ -320,7 +377,7 @@
 	OPJ_UINT32 numpocs;
 	/** number of layers */
 	int tcp_numlayers;
-	/** rates of layers */
+    /** rates of layers - might be subsequently limited by the max_cs_size field */
 	float tcp_rates[100];
 	/** different psnr for successive layers */
 	float tcp_distoratio[100];
@@ -401,12 +458,21 @@
 	/*@}*/
 /* <<UniPG */
 
-	/** Digital Cinema compliance 0-not compliant, 1-compliant*/
-	OPJ_CINEMA_MODE cp_cinema;
-	/** Maximum rate for each component. If == 0, component size limitation is not considered */
+    /**
+     * DEPRECATED: use RSIZ, OPJ_PROFILE_* and MAX_COMP_SIZE instead
+     * Digital Cinema compliance 0-not compliant, 1-compliant
+     * */
+    OPJ_CINEMA_MODE cp_cinema;
+    /**
+     * Maximum size (in bytes) for each component.
+     * If == 0, component size limitation is not considered
+     * */
 	int max_comp_size;
-	/** Profile name*/
-	OPJ_RSIZ_CAPABILITIES cp_rsiz;
+    /**
+     * DEPRECATED: use RSIZ, OPJ_PROFILE_* and OPJ_EXTENSION_* instead
+     * Profile name
+     * */
+    OPJ_RSIZ_CAPABILITIES cp_rsiz;
 	/** Tile part generation*/
 	char tp_on;
 	/** Flag for Tile part generation*/
@@ -418,6 +484,16 @@
 	/** Naive implementation of MCT restricted to a single reversible array based 
         encoding without offset concerning all the components. */
 	void * mct_data;
+    /**
+     * Maximum size (in bytes) for the whole codestream.
+     * If == 0, codestream size limitation is not considered
+     * If it does not comply with tcp_rates, max_cs_size prevails
+     * and a warning is issued.
+     * */
+    int max_cs_size;
+    /** RSIZ value
+        To be used to combine OPJ_PROFILE_*, OPJ_EXTENSION_* and (sub)levels values. */
+    OPJ_UINT16 rsiz;
 } opj_cparameters_t;  
 
 #define OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG	0x0001
@@ -597,8 +673,6 @@
 	OPJ_BYTE *icc_profile_buf;
 	/** size of ICC profile */
 	OPJ_UINT32 icc_profile_len;
-
-	OPJ_INT8  useColorSpace;  //liang
 } opj_image_t;
 
 
@@ -1042,14 +1116,6 @@
  * @param	p_stream	the stream to destroy.
  */
 OPJ_API void OPJ_CALLCONV opj_stream_destroy(opj_stream_t* p_stream);
-
-/**
- * Destroys a stream created by opj_create_stream. This function does NOT close the abstract stream. 
- * If needed the user must close its own implementation of the stream.
- *
- * @param	p_stream	the stream to destroy.
- */
-OPJ_API void OPJ_CALLCONV opj_stream_destroy_v3(opj_stream_t* p_stream);
  
 /**
  * Sets the given function to be used as a read function.
@@ -1083,17 +1149,9 @@
  * Sets the given data to be used as a user data for the stream.
  * @param		p_stream	the stream to modify
  * @param		p_data		the data to set.
- * @warning depending on your source object p_stream this function may leak, use opj_stream_set_user_data_v3
-*/
-OPJ_DEPRECATED(OPJ_API void OPJ_CALLCONV opj_stream_set_user_data (opj_stream_t* p_stream, void * p_data));
-
-/**
- * Sets the given data to be used as a user data for the stream.
- * @param		p_stream	the stream to modify
- * @param		p_data		the data to set.
  * @param		p_function	the function to free p_data when opj_stream_destroy() is called.
 */
-OPJ_API void OPJ_CALLCONV opj_stream_set_user_data_v3 (opj_stream_t* p_stream, void * p_data, opj_stream_free_user_data_fn p_function);
+OPJ_API void OPJ_CALLCONV opj_stream_set_user_data (opj_stream_t* p_stream, void * p_data, opj_stream_free_user_data_fn p_function);
 
 /**
  * Sets the length of the user data for the stream.
@@ -1108,14 +1166,14 @@
  * @param fname             the filename of the file to stream
  * @param p_is_read_stream  whether the stream is a read stream (true) or not (false)
 */
-OPJ_API opj_stream_t* OPJ_CALLCONV opj_stream_create_default_file_stream_v3 (const char *fname, OPJ_BOOL p_is_read_stream);
+OPJ_API opj_stream_t* OPJ_CALLCONV opj_stream_create_default_file_stream (const char *fname, OPJ_BOOL p_is_read_stream);
  
 /** Create a stream from a file identified with its filename with a specific buffer size
  * @param fname             the filename of the file to stream
  * @param p_buffer_size     size of the chunk used to stream
  * @param p_is_read_stream  whether the stream is a read stream (true) or not (false)
 */
-OPJ_API opj_stream_t* OPJ_CALLCONV opj_stream_create_file_stream_v3 (const char *fname, 
+OPJ_API opj_stream_t* OPJ_CALLCONV opj_stream_create_file_stream (const char *fname,
                                                                      OPJ_SIZE_T p_buffer_size,
                                                                      OPJ_BOOL p_is_read_stream);
  
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_codec.h b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_codec.h
index 4fdfa7d..6bd791f 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_codec.h
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_codec.h
@@ -142,10 +142,10 @@
 
             void (* opj_destroy) (void * p_codec);
 
-            void (* opj_setup_encoder) ( void * p_codec,
-                                         opj_cparameters_t * p_param,
-                                         struct opj_image * p_image,
-                                         struct opj_event_mgr * p_manager);
+            OPJ_BOOL (* opj_setup_encoder) ( void * p_codec,
+                                             opj_cparameters_t * p_param,
+                                             struct opj_image * p_image,
+                                             struct opj_event_mgr * p_manager);
         } m_compression;
     } m_codec_data;
     /** FIXME DOC*/
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_config.h b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_config.h
index 0ee7419..9f4bb0f 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_config.h
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_config.h
@@ -1,8 +1,10 @@
-// Copyright 2014 PDFium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
-
 /* create opj_config.h for CMake */
 #define OPJ_HAVE_STDINT_H 		1
+
+/*--------------------------------------------------------------------------*/
+/* OpenJPEG Versioning                                                      */
+
+/* Version number. */
+#define OPJ_VERSION_MAJOR 2
+#define OPJ_VERSION_MINOR 1
+#define OPJ_VERSION_BUILD 0
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_config.h.cmake.in b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_config.h.cmake.in
index 2f5311b..5f762ca 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_config.h.cmake.in
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_config.h.cmake.in
@@ -1,2 +1,10 @@
 /* create opj_config.h for CMake */
 #cmakedefine OPJ_HAVE_STDINT_H 		@OPJ_HAVE_STDINT_H@
+
+/*--------------------------------------------------------------------------*/
+/* OpenJPEG Versioning                                                      */
+
+/* Version number. */
+#define OPJ_VERSION_MAJOR @OPENJPEG_VERSION_MAJOR@
+#define OPJ_VERSION_MINOR @OPENJPEG_VERSION_MINOR@
+#define OPJ_VERSION_BUILD @OPENJPEG_VERSION_BUILD@
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_config_private.h b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_config_private.h
index b0d3a35..5a6c33d 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_config_private.h
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_config_private.h
@@ -1,39 +1,21 @@
-// Copyright 2014 PDFium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
-
 /* create opj_config_private.h for CMake */
-/* #undef OPJ_HAVE_INTTYPES_H */
-
-#ifndef _WIN32
-#ifndef OPJ_HAVE_INTTYPES_H
-#define OPJ_HAVE_INTTYPES_H
-#endif
-#endif
+#define OPJ_HAVE_INTTYPES_H 	1
 
 #define OPJ_PACKAGE_VERSION "2.1.0"
 
 /* Not used by openjp2*/
 /*#define HAVE_MEMORY_H 1*/
 /*#define HAVE_STDLIB_H 1*/
-/* #undef HAVE_STRINGS_H */
+/*#define HAVE_STRINGS_H 1*/
 /*#define HAVE_STRING_H 1*/
 /*#define HAVE_SYS_STAT_H 1*/
 /*#define HAVE_SYS_TYPES_H 1 */
-/* #undef HAVE_UNISTD_H */
+/*#define HAVE_UNISTD_H 1*/
 
 /* #undef _LARGEFILE_SOURCE */
 /* #undef _LARGE_FILES */
 /* #undef _FILE_OFFSET_BITS */
-/* #undef OPJ_HAVE_FSEEKO */
-
-#ifndef _WIN32
-#ifndef OPJ_HAVE_FSEEKO
-#define OPJ_HAVE_FSEEKO
-#endif
-#endif
+#define OPJ_HAVE_FSEEKO ON
 
 /* Byte order.  */
 /* All compilers that support Mac OS X define either __BIG_ENDIAN__ or
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_malloc.h b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_malloc.h
index f2fe82f..5007b0c 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_malloc.h
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/opj_malloc.h
@@ -50,7 +50,6 @@
 @param size Bytes to allocate
 @return Returns a void pointer to the allocated space, or NULL if there is insufficient memory available
 */
-
 #ifdef ALLOC_PERF_OPT
 void * OPJ_CALLCONV opj_malloc(size_t size);
 #else
@@ -161,6 +160,7 @@
 #else
 #define opj_realloc(m, s) realloc(m, s)
 #endif
+#endif
 
 /**
 Deallocates or frees a memory block.
@@ -175,10 +175,11 @@
 #ifdef __GNUC__
 #pragma GCC poison malloc calloc realloc free
 #endif
-#endif
+
 /* ----------------------------------------------------------------------- */
 /*@}*/
 
 /*@}*/
 
 #endif /* __OPJ_MALLOC_H */
+
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/pi.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/pi.c
index 02bbefe..b3fe9af 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/pi.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/pi.c
@@ -815,7 +815,6 @@
 	if (!l_pi) {
 		return NULL;
 	}
-	memset(l_pi,0,l_poc_bound * sizeof(opj_pi_iterator_t));
 
 	l_current_pi = l_pi;
 	for (pino = 0; pino < l_poc_bound ; ++pino) {
@@ -827,21 +826,19 @@
 		}
 
 		l_current_pi->numcomps = image->numcomps;
-		memset(l_current_pi->comps,0,image->numcomps * sizeof(opj_pi_comp_t));
 
 		for (compno = 0; compno < image->numcomps; ++compno) {
 			opj_pi_comp_t *comp = &l_current_pi->comps[compno];
 
 			tccp = &tcp->tccps[compno];
 
-			comp->resolutions = (opj_pi_resolution_t*) opj_malloc(tccp->numresolutions * sizeof(opj_pi_resolution_t));
+			comp->resolutions = (opj_pi_resolution_t*) opj_calloc(tccp->numresolutions, sizeof(opj_pi_resolution_t));
 			if (!comp->resolutions) {
 				opj_pi_destroy(l_pi, l_poc_bound);
 				return 00;
 			}
 
 			comp->numresolutions = tccp->numresolutions;
-			memset(comp->resolutions,0,tccp->numresolutions * sizeof(opj_pi_resolution_t));
 		}
 		++l_current_pi;
 	}
@@ -1108,7 +1105,8 @@
 			    break;
 		    case 'P':
 			    switch(tcp->prg){
-				    case OPJ_LRCP||OPJ_RLCP:
+                    case OPJ_LRCP: // fall through
+                    case OPJ_RLCP:
 					    if(tcp->prc_t == tcp->prcE){
 						    if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){
 							    return OPJ_TRUE;
@@ -1242,7 +1240,6 @@
 		opj_pi_destroy(l_pi, l_bound);
 		return 00;
 	}
-	memset(l_current_pi->include,0, (l_tcp->numlayers + 1) * l_step_l* sizeof(OPJ_INT16));
 
 	/* special treatment for the first packet iterator */
 	l_current_comp = l_current_pi->comps;
@@ -1439,7 +1436,6 @@
 		opj_pi_destroy(l_pi, l_bound);
 		return 00;
 	}
-	memset(l_current_pi->include,0,l_tcp->numlayers * l_step_l* sizeof(OPJ_INT16));
 
 	/* special treatment for the first packet iterator*/
 	l_current_comp = l_current_pi->comps;
@@ -1525,7 +1521,7 @@
 	opj_free(l_tmp_ptr);
 	l_tmp_ptr = 00;
 
-	if (l_tcp->POC && ( p_cp->m_specific_param.m_enc.m_cinema || p_t2_mode == FINAL_PASS)) {
+    if (l_tcp->POC && (OPJ_IS_CINEMA(p_cp->rsiz) || p_t2_mode == FINAL_PASS)) {
 		opj_pi_update_encode_poc_and_final(p_cp,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min);
 	}
 	else {
@@ -1554,7 +1550,7 @@
 	pi[pino].first = 1;
 	pi[pino].poc.prg = tcp->prg;
 
-	if(!(cp->m_specific_param.m_enc.m_tp_on && ((!cp->m_specific_param.m_enc.m_cinema && (t2_mode == FINAL_PASS)) || cp->m_specific_param.m_enc.m_cinema))){
+    if(!(cp->m_specific_param.m_enc.m_tp_on && ((!OPJ_IS_CINEMA(cp->rsiz) && (t2_mode == FINAL_PASS)) || OPJ_IS_CINEMA(cp->rsiz)))){
 		pi[pino].poc.resno0 = tcp->resS;
 		pi[pino].poc.resno1 = tcp->resE;
 		pi[pino].poc.compno0 = tcp->compS;
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/t1.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/t1.c
index 0d6c2f6..5646896 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/t1.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/t1.c
@@ -1170,6 +1170,7 @@
 		opj_aligned_free(t1->data);
 		t1->data = (OPJ_INT32*) opj_aligned_malloc(datasize * sizeof(OPJ_INT32));
 		if(!t1->data){
+			/* FIXME event manager error callback */
 			return OPJ_FALSE;
 		}
 		t1->datasize=datasize;
@@ -1183,6 +1184,7 @@
 		opj_aligned_free(t1->flags);
 		t1->flags = (opj_flag_t*) opj_aligned_malloc(flagssize * sizeof(opj_flag_t));
 		if(!t1->flags){
+			/* FIXME event manager error callback */
 			return OPJ_FALSE;
 		}
 		t1->flagssize=flagssize;
@@ -1207,11 +1209,10 @@
 {
 	opj_t1_t *l_t1 = 00;
 
-	l_t1 = (opj_t1_t*) opj_malloc(sizeof(opj_t1_t));
+	l_t1 = (opj_t1_t*) opj_calloc(1,sizeof(opj_t1_t));
 	if (!l_t1) {
 		return 00;
 	}
-	memset(l_t1,0,sizeof(opj_t1_t));
 
 	/* create MQC and RAW handles */
 	l_t1->mqc = opj_mqc_create();
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/t2.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/t2.c
index de054ac..f2a7c9a 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/t2.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/t2.c
@@ -218,7 +218,7 @@
         opj_image_t *l_image = p_t2->image;
         opj_cp_t *l_cp = p_t2->cp;
         opj_tcp_t *l_tcp = &l_cp->tcps[p_tile_no];
-        OPJ_UINT32 pocno = l_cp->m_specific_param.m_enc.m_cinema == OPJ_CINEMA4K_24? 2: 1;
+        OPJ_UINT32 pocno = (l_cp->rsiz == OPJ_PROFILE_CINEMA_4K)? 2: 1;
         OPJ_UINT32 l_max_comp = l_cp->m_specific_param.m_enc.m_max_comp_size > 0 ? l_image->numcomps : 1;
         OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;
 
@@ -477,11 +477,10 @@
 opj_t2_t* opj_t2_create(opj_image_t *p_image, opj_cp_t *p_cp)
 {
         /* create the t2 structure */
-        opj_t2_t *l_t2 = (opj_t2_t*)opj_malloc(sizeof(opj_t2_t));
+        opj_t2_t *l_t2 = (opj_t2_t*)opj_calloc(1,sizeof(opj_t2_t));
         if (!l_t2) {
                 return NULL;
         }
-        memset(l_t2,0,sizeof(opj_t2_t));
 
         l_t2->image = p_image;
         l_t2->cp = p_cp;
@@ -599,6 +598,10 @@
         }
 
         bio = opj_bio_create();
+        if (!bio) {
+                /* FIXME event manager error callback */
+                return OPJ_FALSE;
+        }
         opj_bio_init_enc(bio, c, length);
         opj_bio_write(bio, 1, 1);           /* Empty header bit */
 
@@ -863,11 +866,10 @@
         if (p_tcp->csty & J2K_CP_CSTY_SOP) {
                 if (p_max_length < 6) {
                         /* TODO opj_event_msg(p_t2->cinfo->event_mgr, EVT_WARNING, "Not enough space for expected SOP marker\n"); */
-                        printf("Not enough space for expected SOP marker\n");
+                        fprintf(stderr, "Not enough space for expected SOP marker\n");
                 } else if ((*l_current_data) != 0xff || (*(l_current_data + 1) != 0x91)) {
                         /* TODO opj_event_msg(p_t2->cinfo->event_mgr, EVT_WARNING, "Expected SOP marker\n"); */
-                        printf("Expected SOP marker\n");
-                        fprintf(stderr, "Error : expected SOP marker\n");
+                        fprintf(stderr, "Warning: expected SOP marker\n");
                 } else {
                         l_current_data += 6;
                 }
@@ -917,7 +919,7 @@
 
                 /* EPH markers */
                 if (p_tcp->csty & J2K_CP_CSTY_EPH) {
-                        if (p_max_length < 2) {
+                        if ((*l_modified_length_ptr - (OPJ_UINT32)(l_header_data - *l_header_data_start)) < 2U) {
                                 fprintf(stderr, "Not enough space for expected EPH marker\n");
                         } else if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) {
                                 fprintf(stderr, "Error : expected EPH marker\n");
@@ -1045,7 +1047,7 @@
 
         /* EPH markers */
         if (p_tcp->csty & J2K_CP_CSTY_EPH) {
-                if (p_max_length < 2) {
+                if ((*l_modified_length_ptr - (OPJ_UINT32)(l_header_data - *l_header_data_start)) < 2U) {
                         fprintf(stderr, "Not enough space for expected EPH marker\n");
                 } else if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) {
                         /* TODO opj_event_msg(t2->cinfo->event_mgr, EVT_ERROR, "Expected EPH marker\n"); */
@@ -1129,7 +1131,8 @@
                         }
 
                         do {
-                                if (l_current_data + l_seg->newlen > p_src_data + p_max_length) {
+                                /* Check possible overflow (on l_current_data only, assumes input args already checked) then size */
+                                if (((OPJ_SIZE_T)(l_current_data + l_seg->newlen) < (OPJ_SIZE_T)l_current_data) || (l_current_data + l_seg->newlen > p_src_data + p_max_length)) {
                                         fprintf(stderr, "read: segment too long (%d) with max (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
                                                 l_seg->newlen, p_max_length, cblkno, p_pi->precno, bandno, p_pi->resno, p_pi->compno);
                                         return OPJ_FALSE;
@@ -1154,11 +1157,18 @@
                                 };
 
 #endif /* USE_JPWL */
+                                /* Check possible overflow on size */
+                                if ((l_cblk->data_current_size + l_seg->newlen) < l_cblk->data_current_size) {
+                                        fprintf(stderr, "read: segment too long (%d) with current size (%d > %d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
+                                                l_seg->newlen, l_cblk->data_current_size, 0xFFFFFFFF - l_seg->newlen, cblkno, p_pi->precno, bandno, p_pi->resno, p_pi->compno);
+                                        return OPJ_FALSE;
+                                }
                                 /* Check if the cblk->data have allocated enough memory */
                                 if ((l_cblk->data_current_size + l_seg->newlen) > l_cblk->data_max_size) {
                                     OPJ_BYTE* new_cblk_data = (OPJ_BYTE*) opj_realloc(l_cblk->data, l_cblk->data_current_size + l_seg->newlen);
                                     if(! new_cblk_data) {
                                         opj_free(l_cblk->data);
+                                        l_cblk->data = NULL;
                                         l_cblk->data_max_size = 0;
                                         /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to realloc code block cata!\n"); */
                                         return OPJ_FALSE;
@@ -1197,6 +1207,7 @@
 
         *(p_data_read) = (OPJ_UINT32)(l_current_data - p_src_data);
 
+
         return OPJ_TRUE;
 }
 
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/tcd.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/tcd.c
index c108675..7dd93e9 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/tcd.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/tcd.c
@@ -175,20 +175,18 @@
         opj_tcd_t *l_tcd = 00;
 
         /* create the tcd structure */
-        l_tcd = (opj_tcd_t*) opj_malloc(sizeof(opj_tcd_t));
+        l_tcd = (opj_tcd_t*) opj_calloc(1,sizeof(opj_tcd_t));
         if (!l_tcd) {
                 return 00;
         }
-        memset(l_tcd,0,sizeof(opj_tcd_t));
 
         l_tcd->m_is_decoder = p_is_decoder ? 1 : 0;
 
-        l_tcd->tcd_image = (opj_tcd_image_t*)opj_malloc(sizeof(opj_tcd_image_t));
+        l_tcd->tcd_image = (opj_tcd_image_t*)opj_calloc(1,sizeof(opj_tcd_image_t));
         if (!l_tcd->tcd_image) {
                 opj_free(l_tcd);
                 return 00;
         }
-        memset(l_tcd->tcd_image,0,sizeof(opj_tcd_image_t));
 
         return l_tcd;
 }
@@ -467,6 +465,10 @@
                 tile_info->numpix = tcd_tile->numpix;
                 tile_info->distotile = tcd_tile->distotile;
                 tile_info->thresh = (OPJ_FLOAT64 *) opj_malloc(tcd_tcp->numlayers * sizeof(OPJ_FLOAT64));
+                if (!tile_info->thresh) {
+                        /* FIXME event manager error callback */
+                        return OPJ_FALSE;
+                }
         }
 
         for (layno = 0; layno < tcd_tcp->numlayers; layno++) {
@@ -502,7 +504,7 @@
                                 opj_tcd_makelayer(tcd, layno, thresh, 0);
 
                                 if (cp->m_specific_param.m_enc.m_fixed_quality) {       /* fixed_quality */
-                                        if(cp->m_specific_param.m_enc.m_cinema){
+                                        if(OPJ_IS_CINEMA(cp->rsiz)){
                                                 if (! opj_t2_encode_packets(t2,tcd->tcd_tileno, tcd_tile, layno + 1, dest, p_data_written, maxlen, cstr_info,tcd->cur_tp_num,tcd->tp_pos,tcd->cur_pino,THRESH_CALC)) {
 
                                                         lo = thresh;
@@ -575,23 +577,18 @@
                                            opj_image_t * p_image,
                                            opj_cp_t * p_cp )
 {
-        OPJ_UINT32 l_tile_comp_size;
-
         p_tcd->image = p_image;
         p_tcd->cp = p_cp;
 
-        p_tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_malloc(sizeof(opj_tcd_tile_t));
+        p_tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_calloc(1,sizeof(opj_tcd_tile_t));
         if (! p_tcd->tcd_image->tiles) {
                 return OPJ_FALSE;
         }
-        memset(p_tcd->tcd_image->tiles,0, sizeof(opj_tcd_tile_t));
 
-        l_tile_comp_size = p_image->numcomps * (OPJ_UINT32)sizeof(opj_tcd_tilecomp_t);
-        p_tcd->tcd_image->tiles->comps = (opj_tcd_tilecomp_t *) opj_malloc(l_tile_comp_size);
+        p_tcd->tcd_image->tiles->comps = (opj_tcd_tilecomp_t *) opj_calloc(p_image->numcomps,sizeof(opj_tcd_tilecomp_t));
         if (! p_tcd->tcd_image->tiles->comps ) {
                 return OPJ_FALSE;
         }
-        memset( p_tcd->tcd_image->tiles->comps , 0 , l_tile_comp_size);
 
         p_tcd->tcd_image->tiles->numcomps = p_image->numcomps;
         p_tcd->tp_pos = p_cp->m_specific_param.m_enc.m_tp_pos;
@@ -686,7 +683,7 @@
                 l_tilec->x1 = opj_int_ceildiv(l_tile->x1, (OPJ_INT32)l_image_comp->dx);                                                                                                                                          \
                 l_tilec->y1 = opj_int_ceildiv(l_tile->y1, (OPJ_INT32)l_image_comp->dy);                                                                                                                                          \
                 /*fprintf(stderr, "\tTile compo border = %d,%d,%d,%d\n", l_tilec->x0, l_tilec->y0,l_tilec->x1,l_tilec->y1);*/                                                                                     \
-                if (l_tilec->x1 < 0 || l_tilec->x0 < 0 || l_tilec->y1 < 0 || l_tilec->y0 < 0) return OPJ_FALSE;\
+                                                                    \
                 l_data_size = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0)           \
                 * (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0) * (OPJ_UINT32)sizeof(OPJ_UINT32 );\
                 l_tilec->numresolutions = l_tccp->numresolutions;   \
@@ -775,8 +772,6 @@
                         /* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */                                                                                                                     \
                         l_pdx = l_tccp->prcw[resno];                                                                                                                                                              \
                         l_pdy = l_tccp->prch[resno];                                                                                                                                                              \
-                        if (l_pdx == 0 || l_pdy == 0)                                                                                                                                                                \
-                            return OPJ_FALSE;                                                                                                                                                                     \
                         /*fprintf(stderr, "\t\t\tpdx=%d, pdy=%d\n", l_pdx, l_pdy);*/                                                                                                                              \
                         /* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000)  */                                                                                                                            \
                         l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx;                                                                                                                           \
@@ -1023,20 +1018,17 @@
                 p_code_block->data+=1;
 
                 /* no memset since data */
-                p_code_block->layers = (opj_tcd_layer_t*) opj_malloc(100 * sizeof(opj_tcd_layer_t));
+                p_code_block->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t));
                 if (! p_code_block->layers) {
                         return OPJ_FALSE;
                 }
 
-                p_code_block->passes = (opj_tcd_pass_t*) opj_malloc(100 * sizeof(opj_tcd_pass_t));
+                p_code_block->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t));
                 if (! p_code_block->passes) {
                         return OPJ_FALSE;
                 }
         }
 
-        memset(p_code_block->layers,0,100 * sizeof(opj_tcd_layer_t));
-        memset(p_code_block->passes,0,100 * sizeof(opj_tcd_pass_t));
-
         return OPJ_TRUE;
 }
 
@@ -1045,8 +1037,6 @@
  */
 OPJ_BOOL opj_tcd_code_block_dec_allocate (opj_tcd_cblk_dec_t * p_code_block)
 {
-        OPJ_UINT32 l_seg_size;
-
         if (! p_code_block->data) {
 
                 p_code_block->data = (OPJ_BYTE*) opj_malloc(OPJ_J2K_DEFAULT_CBLK_DATA_SIZE);
@@ -1056,12 +1046,10 @@
                 p_code_block->data_max_size = OPJ_J2K_DEFAULT_CBLK_DATA_SIZE;
                 /*fprintf(stderr, "Allocate 8192 elements of code_block->data\n");*/
 
-                l_seg_size = OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t);
-                p_code_block->segs = (opj_tcd_seg_t *) opj_malloc(l_seg_size);
+                p_code_block->segs = (opj_tcd_seg_t *) opj_calloc(OPJ_J2K_DEFAULT_NB_SEGS,sizeof(opj_tcd_seg_t));
                 if (! p_code_block->segs) {
                         return OPJ_FALSE;
                 }
-                memset(p_code_block->segs,0,l_seg_size);
                 /*fprintf(stderr, "Allocate %d elements of code_block->data\n", OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t));*/
 
                 p_code_block->m_current_max_segs = OPJ_J2K_DEFAULT_NB_SEGS;
@@ -1137,6 +1125,10 @@
                                 p_cstr_info->tile[p_tile_no].pdy[i] = (int)l_tccp->prch[i];
                         }
                         p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t*) opj_calloc((size_t)p_cstr_info->numcomps * (size_t)p_cstr_info->numlayers * l_num_packs, sizeof(opj_packet_info_t));
+                        if (!p_cstr_info->tile[p_tile_no].packet) {
+                                /* FIXME event manager error callback */
+                                return OPJ_FALSE;
+                        }
                 }
                 /* << INDEX */
 
diff --git a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/tgt.c b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/tgt.c
index e77adb3..6143c08 100644
--- a/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/tgt.c
+++ b/core/src/fxcodec/fx_libopenjpeg/libopenjpeg20/tgt.c
@@ -57,12 +57,11 @@
         OPJ_UINT32 numlvls;
         OPJ_UINT32 n;
 
-        tree = (opj_tgt_tree_t *) opj_malloc(sizeof(opj_tgt_tree_t));
+        tree = (opj_tgt_tree_t *) opj_calloc(1,sizeof(opj_tgt_tree_t));
         if(!tree) {
                 fprintf(stderr, "ERROR in tgt_create while allocating tree\n");
                 return 00;
         }
-        memset(tree,0,sizeof(opj_tgt_tree_t));
 
         tree->numleafsh = numleafsh;
         tree->numleafsv = numleafsv;
@@ -92,7 +91,6 @@
                 opj_free(tree);
                 return 00;
         }
-        memset(tree->nodes,0,tree->numnodes * sizeof(opj_tgt_node_t));
         tree->nodes_size = tree->numnodes * (OPJ_UINT32)sizeof(opj_tgt_node_t);
 
         node = tree->nodes;