defined new type "opj_bool", and new constants OPJ_FALSE and OPJ_TRUE, to avoid havin...
[openjpeg.git] / libopenjpeg / j2k.c
1 /*
2  * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
3  * Copyright (c) 2002-2007, Professor Benoit Macq
4  * Copyright (c) 2001-2003, David Janssens
5  * Copyright (c) 2002-2003, Yannick Verschueren
6  * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
7  * Copyright (c) 2005, Herve Drolon, FreeImage Team
8  * Copyright (c) 2006-2007, Parvatha Elangovan
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "opj_includes.h"
34
35 /** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
36 /*@{*/
37
38 /** @name Local static functions */
39 /*@{*/
40
41 /**
42 Write the SOC marker (Start Of Codestream)
43 @param j2k J2K handle
44 */
45 static void j2k_write_soc(opj_j2k_t *j2k);
46 /**
47 Read the SOC marker (Start of Codestream)
48 @param j2k J2K handle
49 */
50 static void j2k_read_soc(opj_j2k_t *j2k);
51 /**
52 Write the SIZ marker (image and tile size)
53 @param j2k J2K handle
54 */
55 static void j2k_write_siz(opj_j2k_t *j2k);
56 /**
57 Read the SIZ marker (image and tile size)
58 @param j2k J2K handle
59 */
60 static void j2k_read_siz(opj_j2k_t *j2k);
61 /**
62 Write the COM marker (comment)
63 @param j2k J2K handle
64 */
65 static void j2k_write_com(opj_j2k_t *j2k);
66 /**
67 Read the COM marker (comment)
68 @param j2k J2K handle
69 */
70 static void j2k_read_com(opj_j2k_t *j2k);
71 /**
72 Write the value concerning the specified component in the marker COD and COC
73 @param j2k J2K handle
74 @param compno Number of the component concerned by the information written
75 */
76 static void j2k_write_cox(opj_j2k_t *j2k, int compno);
77 /**
78 Read the value concerning the specified component in the marker COD and COC
79 @param j2k J2K handle
80 @param compno Number of the component concerned by the information read
81 */
82 static void j2k_read_cox(opj_j2k_t *j2k, int compno);
83 /**
84 Write the COD marker (coding style default)
85 @param j2k J2K handle
86 */
87 static void j2k_write_cod(opj_j2k_t *j2k);
88 /**
89 Read the COD marker (coding style default)
90 @param j2k J2K handle
91 */
92 static void j2k_read_cod(opj_j2k_t *j2k);
93 /**
94 Write the COC marker (coding style component)
95 @param j2k J2K handle
96 @param compno Number of the component concerned by the information written
97 */
98 static void j2k_write_coc(opj_j2k_t *j2k, int compno);
99 /**
100 Read the COC marker (coding style component)
101 @param j2k J2K handle
102 */
103 static void j2k_read_coc(opj_j2k_t *j2k);
104 /**
105 Write the value concerning the specified component in the marker QCD and QCC
106 @param j2k J2K handle
107 @param compno Number of the component concerned by the information written
108 */
109 static void j2k_write_qcx(opj_j2k_t *j2k, int compno);
110 /**
111 Read the value concerning the specified component in the marker QCD and QCC
112 @param j2k J2K handle
113 @param compno Number of the component concern by the information read
114 @param len Length of the information in the QCX part of the marker QCD/QCC
115 */
116 static void j2k_read_qcx(opj_j2k_t *j2k, int compno, int len);
117 /**
118 Write the QCD marker (quantization default)
119 @param j2k J2K handle
120 */
121 static void j2k_write_qcd(opj_j2k_t *j2k);
122 /**
123 Read the QCD marker (quantization default)
124 @param j2k J2K handle
125 */
126 static void j2k_read_qcd(opj_j2k_t *j2k);
127 /**
128 Write the QCC marker (quantization component)
129 @param j2k J2K handle
130 @param compno Number of the component concerned by the information written
131 */
132 static void j2k_write_qcc(opj_j2k_t *j2k, int compno);
133 /**
134 Read the QCC marker (quantization component)
135 @param j2k J2K handle
136 */
137 static void j2k_read_qcc(opj_j2k_t *j2k);
138 /**
139 Write the POC marker (progression order change)
140 @param j2k J2K handle
141 */
142 static void j2k_write_poc(opj_j2k_t *j2k);
143 /**
144 Read the POC marker (progression order change)
145 @param j2k J2K handle
146 */
147 static void j2k_read_poc(opj_j2k_t *j2k);
148 /**
149 Read the CRG marker (component registration)
150 @param j2k J2K handle
151 */
152 static void j2k_read_crg(opj_j2k_t *j2k);
153 /**
154 Read the TLM marker (tile-part lengths)
155 @param j2k J2K handle
156 */
157 static void j2k_read_tlm(opj_j2k_t *j2k);
158 /**
159 Read the PLM marker (packet length, main header)
160 @param j2k J2K handle
161 */
162 static void j2k_read_plm(opj_j2k_t *j2k);
163 /**
164 Read the PLT marker (packet length, tile-part header)
165 @param j2k J2K handle
166 */
167 static void j2k_read_plt(opj_j2k_t *j2k);
168 /**
169 Read the PPM marker (packet packet headers, main header)
170 @param j2k J2K handle
171 */
172 static void j2k_read_ppm(opj_j2k_t *j2k);
173 /**
174 Read the PPT marker (packet packet headers, tile-part header)
175 @param j2k J2K handle
176 */
177 static void j2k_read_ppt(opj_j2k_t *j2k);
178 /**
179 Write the TLM marker (Mainheader)
180 @param j2k J2K handle
181 */
182 static void j2k_write_tlm(opj_j2k_t *j2k);
183 /**
184 Write the SOT marker (start of tile-part)
185 @param j2k J2K handle
186 */
187 static void j2k_write_sot(opj_j2k_t *j2k);
188 /**
189 Read the SOT marker (start of tile-part)
190 @param j2k J2K handle
191 */
192 static void j2k_read_sot(opj_j2k_t *j2k);
193 /**
194 Write the SOD marker (start of data)
195 @param j2k J2K handle
196 @param tile_coder Pointer to a TCD handle
197 */
198 static void j2k_write_sod(opj_j2k_t *j2k, void *tile_coder);
199 /**
200 Read the SOD marker (start of data)
201 @param j2k J2K handle
202 */
203 static void j2k_read_sod(opj_j2k_t *j2k);
204 /**
205 Write the RGN marker (region-of-interest)
206 @param j2k J2K handle
207 @param compno Number of the component concerned by the information written
208 @param tileno Number of the tile concerned by the information written
209 */
210 static void j2k_write_rgn(opj_j2k_t *j2k, int compno, int tileno);
211 /**
212 Read the RGN marker (region-of-interest)
213 @param j2k J2K handle
214 */
215 static void j2k_read_rgn(opj_j2k_t *j2k);
216 /**
217 Write the EOC marker (end of codestream)
218 @param j2k J2K handle
219 */
220 static void j2k_write_eoc(opj_j2k_t *j2k);
221 /**
222 Read the EOC marker (end of codestream)
223 @param j2k J2K handle
224 */
225 static void j2k_read_eoc(opj_j2k_t *j2k);
226 /**
227 Read an unknown marker
228 @param j2k J2K handle
229 */
230 static void j2k_read_unk(opj_j2k_t *j2k);
231
232 /*@}*/
233
234 /*@}*/
235
236 /* ----------------------------------------------------------------------- */
237 typedef struct j2k_prog_order{
238         OPJ_PROG_ORDER enum_prog;
239         char str_prog[4];
240 }j2k_prog_order_t;
241
242 j2k_prog_order_t j2k_prog_order_list[] = {
243         {CPRL, "CPRL"},
244         {LRCP, "LRCP"},
245         {PCRL, "PCRL"},
246         {RLCP, "RLCP"},
247         {RPCL, "RPCL"},
248         {(OPJ_PROG_ORDER)-1, ""}
249 };
250
251 char *j2k_convert_progression_order(OPJ_PROG_ORDER prg_order){
252         j2k_prog_order_t *po;
253         for(po = j2k_prog_order_list; po->enum_prog != -1; po++ ){
254                 if(po->enum_prog == prg_order){
255                         break;
256                 }
257         }
258         return po->str_prog;
259 }
260
261 /* ----------------------------------------------------------------------- */
262 static int j2k_get_num_tp(opj_cp_t *cp,int pino,int tileno){
263         char *prog;
264         int i;
265         int tpnum=1,tpend=0;
266         opj_tcp_t *tcp = &cp->tcps[tileno];
267         prog = j2k_convert_progression_order(tcp->prg);
268         
269         if(cp->tp_on == 1){
270                 for(i=0;i<4;i++){
271                         if(tpend!=1){
272                                 if( cp->tp_flag == prog[i] ){
273                                         tpend=1;cp->tp_pos=i;
274                                 }
275                                 switch(prog[i]){
276                                 case 'C':
277                                         tpnum= tpnum * tcp->pocs[pino].compE;
278                                         break;
279                                 case 'R':
280                                         tpnum= tpnum * tcp->pocs[pino].resE;
281                                         break;
282                                 case 'P':
283                                         tpnum= tpnum * tcp->pocs[pino].prcE;
284                                         break;
285                                 case 'L':
286                                         tpnum= tpnum * tcp->pocs[pino].layE;
287                                         break;
288                                 }
289                         }
290                 }
291         }else{
292                 tpnum=1;
293         }
294         return tpnum;
295 }
296
297 /**     mem allocation for TLM marker*/
298 int j2k_calculate_tp(opj_cp_t *cp,int img_numcomp,opj_image_t *image,opj_j2k_t *j2k ){
299         int pino,tileno,totnum_tp=0;
300         j2k->cur_totnum_tp = (int *) opj_malloc(cp->tw * cp->th * sizeof(int));
301         for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
302                 int cur_totnum_tp = 0;
303                 opj_tcp_t *tcp = &cp->tcps[tileno];
304                 for(pino = 0; pino <= tcp->numpocs; pino++) {
305                         int tp_num=0;
306                         opj_pi_iterator_t *pi = pi_initialise_encode(image, cp, tileno,FINAL_PASS);
307                         if(!pi) { return -1;}
308                         tp_num = j2k_get_num_tp(cp,pino,tileno);
309                         totnum_tp = totnum_tp + tp_num;
310                         cur_totnum_tp = cur_totnum_tp + tp_num;
311                         pi_destroy(pi, cp, tileno);
312                 }
313                 j2k->cur_totnum_tp[tileno] = cur_totnum_tp;
314                 /* INDEX >> */
315                 if (j2k->cstr_info) {
316                         j2k->cstr_info->tile[tileno].num_tps = cur_totnum_tp;
317                         j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t));
318                 }
319                 /* << INDEX */
320         }
321         return totnum_tp;
322 }
323
324 static void j2k_write_soc(opj_j2k_t *j2k) {
325         opj_cio_t *cio = j2k->cio;
326         cio_write(cio, J2K_MS_SOC, 2);
327
328 /* UniPG>> */
329 #ifdef USE_JPWL
330
331         /* update markers struct */
332         j2k_add_marker(j2k->cstr_info, J2K_MS_SOC, cio_tell(cio) - 2, 2);
333
334 #endif /* USE_JPWL */
335 /* <<UniPG */
336 }
337
338 static void j2k_read_soc(opj_j2k_t *j2k) {      
339         j2k->state = J2K_STATE_MHSIZ;
340         /* Index */
341         if (j2k->cstr_info) {
342                 j2k->cstr_info->main_head_start = cio_tell(j2k->cio) - 2;
343                 j2k->cstr_info->codestream_size = cio_numbytesleft(j2k->cio) + 2 - j2k->cstr_info->main_head_start;
344         }
345 }
346
347 static void j2k_write_siz(opj_j2k_t *j2k) {
348         int i;
349         int lenp, len;
350
351         opj_cio_t *cio = j2k->cio;
352         opj_image_t *image = j2k->image;
353         opj_cp_t *cp = j2k->cp;
354         
355         cio_write(cio, J2K_MS_SIZ, 2);  /* SIZ */
356         lenp = cio_tell(cio);
357         cio_skip(cio, 2);
358         cio_write(cio, cp->rsiz, 2);                    /* Rsiz (capabilities) */
359         cio_write(cio, image->x1, 4);   /* Xsiz */
360         cio_write(cio, image->y1, 4);   /* Ysiz */
361         cio_write(cio, image->x0, 4);   /* X0siz */
362         cio_write(cio, image->y0, 4);   /* Y0siz */
363         cio_write(cio, cp->tdx, 4);             /* XTsiz */
364         cio_write(cio, cp->tdy, 4);             /* YTsiz */
365         cio_write(cio, cp->tx0, 4);             /* XT0siz */
366         cio_write(cio, cp->ty0, 4);             /* YT0siz */
367         cio_write(cio, image->numcomps, 2);     /* Csiz */
368         for (i = 0; i < image->numcomps; i++) {
369                 cio_write(cio, image->comps[i].prec - 1 + (image->comps[i].sgnd << 7), 1);      /* Ssiz_i */
370                 cio_write(cio, image->comps[i].dx, 1);  /* XRsiz_i */
371                 cio_write(cio, image->comps[i].dy, 1);  /* YRsiz_i */
372         }
373         len = cio_tell(cio) - lenp;
374         cio_seek(cio, lenp);
375         cio_write(cio, len, 2);         /* Lsiz */
376         cio_seek(cio, lenp + len);
377 }
378
379 static void j2k_read_siz(opj_j2k_t *j2k) {
380         int len, i;
381         
382         opj_cio_t *cio = j2k->cio;
383         opj_image_t *image = j2k->image;
384         opj_cp_t *cp = j2k->cp;
385         
386         len = cio_read(cio, 2);                 /* Lsiz */
387         cio_read(cio, 2);                               /* Rsiz (capabilities) */
388         image->x1 = cio_read(cio, 4);   /* Xsiz */
389         image->y1 = cio_read(cio, 4);   /* Ysiz */
390         image->x0 = cio_read(cio, 4);   /* X0siz */
391         image->y0 = cio_read(cio, 4);   /* Y0siz */
392         cp->tdx = cio_read(cio, 4);             /* XTsiz */
393         cp->tdy = cio_read(cio, 4);             /* YTsiz */
394         cp->tx0 = cio_read(cio, 4);             /* XT0siz */
395         cp->ty0 = cio_read(cio, 4);             /* YT0siz */
396         
397         if ((image->x0<0)||(image->x1<0)||(image->y0<0)||(image->y1<0)) {
398                 opj_event_msg(j2k->cinfo, EVT_ERROR,
399                                                                         "%s: invalid image size (x0:%d, x1:%d, y0:%d, y1:%d)\n",
400                                                                         image->x0,image->x1,image->y0,image->y1);
401                 return;
402         }
403         
404         image->numcomps = cio_read(cio, 2);     /* Csiz */
405
406 #ifdef USE_JPWL
407         if (j2k->cp->correct) {
408                 /* if JPWL is on, we check whether TX errors have damaged
409                   too much the SIZ parameters */
410                 if (!(image->x1 * image->y1)) {
411                         opj_event_msg(j2k->cinfo, EVT_ERROR,
412                                 "JPWL: bad image size (%d x %d)\n",
413                                 image->x1, image->y1);
414                         if (!JPWL_ASSUME || JPWL_ASSUME) {
415                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
416                                 return;
417                         }
418                 }
419                 if (image->numcomps != ((len - 38) / 3)) {
420                         opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
421                                 "JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n",
422                                 image->numcomps, ((len - 38) / 3));
423                         if (!JPWL_ASSUME) {
424                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
425                                 return;
426                         }
427                         /* we try to correct */
428                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n");
429                         if (image->numcomps < ((len - 38) / 3)) {
430                                 len = 38 + 3 * image->numcomps;
431                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n",
432                                         len);                           
433                         } else {
434                                 image->numcomps = ((len - 38) / 3);
435                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n",
436                                         image->numcomps);                               
437                         }
438                 }
439
440                 /* update components number in the jpwl_exp_comps filed */
441                 cp->exp_comps = image->numcomps;
442         }
443 #endif /* USE_JPWL */
444
445         image->comps = (opj_image_comp_t*) opj_calloc(image->numcomps, sizeof(opj_image_comp_t));
446         for (i = 0; i < image->numcomps; i++) {
447                 int tmp, w, h;
448                 tmp = cio_read(cio, 1);         /* Ssiz_i */
449                 image->comps[i].prec = (tmp & 0x7f) + 1;
450                 image->comps[i].sgnd = tmp >> 7;
451                 image->comps[i].dx = cio_read(cio, 1);  /* XRsiz_i */
452                 image->comps[i].dy = cio_read(cio, 1);  /* YRsiz_i */
453                 
454 #ifdef USE_JPWL
455                 if (j2k->cp->correct) {
456                 /* if JPWL is on, we check whether TX errors have damaged
457                         too much the SIZ parameters, again */
458                         if (!(image->comps[i].dx * image->comps[i].dy)) {
459                                 opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
460                                         "JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n",
461                                         i, i, image->comps[i].dx, image->comps[i].dy);
462                                 if (!JPWL_ASSUME) {
463                                         opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
464                                         return;
465                                 }
466                                 /* we try to correct */
467                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n");
468                                 if (!image->comps[i].dx) {
469                                         image->comps[i].dx = 1;
470                                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting XRsiz_%d to %d => HYPOTHESIS!!!\n",
471                                                 i, image->comps[i].dx);
472                                 }
473                                 if (!image->comps[i].dy) {
474                                         image->comps[i].dy = 1;
475                                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting YRsiz_%d to %d => HYPOTHESIS!!!\n",
476                                                 i, image->comps[i].dy);
477                                 }
478                         }
479                         
480                 }
481 #endif /* USE_JPWL */
482
483                 /* TODO: unused ? */
484                 w = int_ceildiv(image->x1 - image->x0, image->comps[i].dx);
485                 h = int_ceildiv(image->y1 - image->y0, image->comps[i].dy);
486
487                 image->comps[i].resno_decoded = 0;      /* number of resolution decoded */
488                 image->comps[i].factor = cp->reduce; /* reducing factor per component */
489         }
490         
491         cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx);
492         cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy);
493
494 #ifdef USE_JPWL
495         if (j2k->cp->correct) {
496                 /* if JPWL is on, we check whether TX errors have damaged
497                   too much the SIZ parameters */
498                 if ((cp->tw < 1) || (cp->th < 1) || (cp->tw > cp->max_tiles) || (cp->th > cp->max_tiles)) {
499                         opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
500                                 "JPWL: bad number of tiles (%d x %d)\n",
501                                 cp->tw, cp->th);
502                         if (!JPWL_ASSUME) {
503                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
504                                 return;
505                         }
506                         /* we try to correct */
507                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n");
508                         if (cp->tw < 1) {
509                                 cp->tw= 1;
510                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting %d tiles in x => HYPOTHESIS!!!\n",
511                                         cp->tw);
512                         }
513                         if (cp->tw > cp->max_tiles) {
514                                 cp->tw= 1;
515                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- too large x, increase expectance of %d\n"
516                                         "- setting %d tiles in x => HYPOTHESIS!!!\n",
517                                         cp->max_tiles, cp->tw);
518                         }
519                         if (cp->th < 1) {
520                                 cp->th= 1;
521                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting %d tiles in y => HYPOTHESIS!!!\n",
522                                         cp->th);
523                         }
524                         if (cp->th > cp->max_tiles) {
525                                 cp->th= 1;
526                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- too large y, increase expectance of %d to continue\n",
527                                         "- setting %d tiles in y => HYPOTHESIS!!!\n",
528                                         cp->max_tiles, cp->th);
529                         }
530                 }
531         }
532 #endif /* USE_JPWL */
533
534         cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
535         cp->tileno = (int*) opj_malloc(cp->tw * cp->th * sizeof(int));
536         cp->tileno_size = 0;
537         
538 #ifdef USE_JPWL
539         if (j2k->cp->correct) {
540                 if (!cp->tcps) {
541                         opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
542                                 "JPWL: could not alloc tcps field of cp\n");
543                         if (!JPWL_ASSUME || JPWL_ASSUME) {
544                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
545                                 return;
546                         }
547                 }
548         }
549 #endif /* USE_JPWL */
550
551         for (i = 0; i < cp->tw * cp->th; i++) {
552                 cp->tcps[i].POC = 0;
553                 cp->tcps[i].numpocs = 0;
554                 cp->tcps[i].first = 1;
555         }
556         
557         /* Initialization for PPM marker */
558         cp->ppm = 0;
559         cp->ppm_data = NULL;
560         cp->ppm_data_first = NULL;
561         cp->ppm_previous = 0;
562         cp->ppm_store = 0;
563
564         j2k->default_tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
565         for (i = 0; i < cp->tw * cp->th; i++) {
566                 cp->tcps[i].tccps = (opj_tccp_t*) opj_malloc(image->numcomps * sizeof(opj_tccp_t));
567         }       
568         j2k->tile_data = (unsigned char**) opj_calloc(cp->tw * cp->th, sizeof(unsigned char*));
569         j2k->tile_len = (int*) opj_calloc(cp->tw * cp->th, sizeof(int));
570         j2k->state = J2K_STATE_MH;
571
572         /* Index */
573         if (j2k->cstr_info) {
574                 opj_codestream_info_t *cstr_info = j2k->cstr_info;
575                 cstr_info->image_w = image->x1 - image->x0;
576                 cstr_info->image_h = image->y1 - image->y0;
577                 cstr_info->numcomps = image->numcomps;
578                 cstr_info->tw = cp->tw;
579                 cstr_info->th = cp->th;
580                 cstr_info->tile_x = cp->tdx;    
581                 cstr_info->tile_y = cp->tdy;    
582                 cstr_info->tile_Ox = cp->tx0;   
583                 cstr_info->tile_Oy = cp->ty0;                   
584                 cstr_info->tile = (opj_tile_info_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tile_info_t));              
585         }
586 }
587
588 static void j2k_write_com(opj_j2k_t *j2k) {
589         unsigned int i;
590         int lenp, len;
591
592         if(j2k->cp->comment) {
593                 opj_cio_t *cio = j2k->cio;
594                 char *comment = j2k->cp->comment;
595
596                 cio_write(cio, J2K_MS_COM, 2);
597                 lenp = cio_tell(cio);
598                 cio_skip(cio, 2);
599                 cio_write(cio, 1, 2);           /* General use (IS 8859-15:1999 (Latin) values) */
600                 for (i = 0; i < strlen(comment); i++) {
601                         cio_write(cio, comment[i], 1);
602                 }
603                 len = cio_tell(cio) - lenp;
604                 cio_seek(cio, lenp);
605                 cio_write(cio, len, 2);
606                 cio_seek(cio, lenp + len);
607         }
608 }
609
610 static void j2k_read_com(opj_j2k_t *j2k) {
611         int len;
612         
613         opj_cio_t *cio = j2k->cio;
614
615         len = cio_read(cio, 2);
616         cio_skip(cio, len - 2);  
617 }
618
619 static void j2k_write_cox(opj_j2k_t *j2k, int compno) {
620         int i;
621
622         opj_cp_t *cp = j2k->cp;
623         opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
624         opj_tccp_t *tccp = &tcp->tccps[compno];
625         opj_cio_t *cio = j2k->cio;
626         
627         cio_write(cio, tccp->numresolutions - 1, 1);    /* SPcox (D) */
628         cio_write(cio, tccp->cblkw - 2, 1);                             /* SPcox (E) */
629         cio_write(cio, tccp->cblkh - 2, 1);                             /* SPcox (F) */
630         cio_write(cio, tccp->cblksty, 1);                               /* SPcox (G) */
631         cio_write(cio, tccp->qmfbid, 1);                                /* SPcox (H) */
632         
633         if (tccp->csty & J2K_CCP_CSTY_PRT) {
634                 for (i = 0; i < tccp->numresolutions; i++) {
635                         cio_write(cio, tccp->prcw[i] + (tccp->prch[i] << 4), 1);        /* SPcox (I_i) */
636                 }
637         }
638 }
639
640 static void j2k_read_cox(opj_j2k_t *j2k, int compno) {
641         int i;
642
643         opj_cp_t *cp = j2k->cp;
644         opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
645         opj_tccp_t *tccp = &tcp->tccps[compno];
646         opj_cio_t *cio = j2k->cio;
647
648         tccp->numresolutions = cio_read(cio, 1) + 1;    /* SPcox (D) */
649
650         // If user wants to remove more resolutions than the codestream contains, return error
651         if (cp->reduce >= tccp->numresolutions) {
652                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions to remove is higher than the number "
653                                         "of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno);
654                 j2k->state |= J2K_STATE_ERR;
655         }
656
657         tccp->cblkw = cio_read(cio, 1) + 2;     /* SPcox (E) */
658         tccp->cblkh = cio_read(cio, 1) + 2;     /* SPcox (F) */
659         tccp->cblksty = cio_read(cio, 1);       /* SPcox (G) */
660         tccp->qmfbid = cio_read(cio, 1);        /* SPcox (H) */
661         if (tccp->csty & J2K_CP_CSTY_PRT) {
662                 for (i = 0; i < tccp->numresolutions; i++) {
663                         int tmp = cio_read(cio, 1);     /* SPcox (I_i) */
664                         tccp->prcw[i] = tmp & 0xf;
665                         tccp->prch[i] = tmp >> 4;
666                 }
667         }
668
669         /* INDEX >> */
670         if(j2k->cstr_info && compno == 0) {
671                 for (i = 0; i < tccp->numresolutions; i++) {
672                         if (tccp->csty & J2K_CP_CSTY_PRT) {
673                                 j2k->cstr_info->tile[j2k->curtileno].pdx[i] = tccp->prcw[i];
674                                 j2k->cstr_info->tile[j2k->curtileno].pdy[i] = tccp->prch[i];
675                         }
676                         else {
677                                 j2k->cstr_info->tile[j2k->curtileno].pdx[i] = 15;
678                                 j2k->cstr_info->tile[j2k->curtileno].pdx[i] = 15;
679                         }
680                 }
681         }
682         /* << INDEX */
683 }
684
685 static void j2k_write_cod(opj_j2k_t *j2k) {
686         opj_cp_t *cp = NULL;
687         opj_tcp_t *tcp = NULL;
688         int lenp, len;
689
690         opj_cio_t *cio = j2k->cio;
691         
692         cio_write(cio, J2K_MS_COD, 2);  /* COD */
693         
694         lenp = cio_tell(cio);
695         cio_skip(cio, 2);
696         
697         cp = j2k->cp;
698         tcp = &cp->tcps[j2k->curtileno];
699
700         cio_write(cio, tcp->csty, 1);           /* Scod */
701         cio_write(cio, tcp->prg, 1);            /* SGcod (A) */
702         cio_write(cio, tcp->numlayers, 2);      /* SGcod (B) */
703         cio_write(cio, tcp->mct, 1);            /* SGcod (C) */
704         
705         j2k_write_cox(j2k, 0);
706         len = cio_tell(cio) - lenp;
707         cio_seek(cio, lenp);
708         cio_write(cio, len, 2);         /* Lcod */
709         cio_seek(cio, lenp + len);
710 }
711
712 static void j2k_read_cod(opj_j2k_t *j2k) {
713         int len, i, pos;
714         
715         opj_cio_t *cio = j2k->cio;
716         opj_cp_t *cp = j2k->cp;
717         opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
718         opj_image_t *image = j2k->image;
719         
720         len = cio_read(cio, 2);                         /* Lcod */
721         tcp->csty = cio_read(cio, 1);           /* Scod */
722         tcp->prg = (OPJ_PROG_ORDER)cio_read(cio, 1);            /* SGcod (A) */
723         tcp->numlayers = cio_read(cio, 2);      /* SGcod (B) */
724         tcp->mct = cio_read(cio, 1);            /* SGcod (C) */
725         
726         pos = cio_tell(cio);
727         for (i = 0; i < image->numcomps; i++) {
728                 tcp->tccps[i].csty = tcp->csty & J2K_CP_CSTY_PRT;
729                 cio_seek(cio, pos);
730                 j2k_read_cox(j2k, i);
731         }
732
733         /* Index */
734         if (j2k->cstr_info) {
735                 opj_codestream_info_t *cstr_info = j2k->cstr_info;
736                 cstr_info->prog = tcp->prg;
737                 cstr_info->numlayers = tcp->numlayers;
738                 cstr_info->numdecompos = (int*) opj_malloc(image->numcomps * sizeof(int));
739                 for (i = 0; i < image->numcomps; i++) {
740                         cstr_info->numdecompos[i] = tcp->tccps[i].numresolutions - 1;
741                 }
742         }
743 }
744
745 static void j2k_write_coc(opj_j2k_t *j2k, int compno) {
746         int lenp, len;
747
748         opj_cp_t *cp = j2k->cp;
749         opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
750         opj_image_t *image = j2k->image;
751         opj_cio_t *cio = j2k->cio;
752         
753         cio_write(cio, J2K_MS_COC, 2);  /* COC */
754         lenp = cio_tell(cio);
755         cio_skip(cio, 2);
756         cio_write(cio, compno, image->numcomps <= 256 ? 1 : 2); /* Ccoc */
757         cio_write(cio, tcp->tccps[compno].csty, 1);     /* Scoc */
758         j2k_write_cox(j2k, compno);
759         len = cio_tell(cio) - lenp;
760         cio_seek(cio, lenp);
761         cio_write(cio, len, 2);                 /* Lcoc */
762         cio_seek(cio, lenp + len);
763 }
764
765 static void j2k_read_coc(opj_j2k_t *j2k) {
766         int len, compno;
767
768         opj_cp_t *cp = j2k->cp;
769         opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
770         opj_image_t *image = j2k->image;
771         opj_cio_t *cio = j2k->cio;
772         
773         len = cio_read(cio, 2);         /* Lcoc */
774         compno = cio_read(cio, image->numcomps <= 256 ? 1 : 2); /* Ccoc */
775         tcp->tccps[compno].csty = cio_read(cio, 1);     /* Scoc */
776         j2k_read_cox(j2k, compno);
777 }
778
779 static void j2k_write_qcx(opj_j2k_t *j2k, int compno) {
780         int bandno, numbands;
781         int expn, mant;
782         
783         opj_cp_t *cp = j2k->cp;
784         opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
785         opj_tccp_t *tccp = &tcp->tccps[compno];
786         opj_cio_t *cio = j2k->cio;
787         
788         cio_write(cio, tccp->qntsty + (tccp->numgbits << 5), 1);        /* Sqcx */
789         numbands = tccp->qntsty == J2K_CCP_QNTSTY_SIQNT ? 1 : tccp->numresolutions * 3 - 2;
790         
791         for (bandno = 0; bandno < numbands; bandno++) {
792                 expn = tccp->stepsizes[bandno].expn;
793                 mant = tccp->stepsizes[bandno].mant;
794                 
795                 if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
796                         cio_write(cio, expn << 3, 1);   /* SPqcx_i */
797                 } else {
798                         cio_write(cio, (expn << 11) + mant, 2); /* SPqcx_i */
799                 }
800         }
801 }
802
803 static void j2k_read_qcx(opj_j2k_t *j2k, int compno, int len) {
804         int tmp;
805         int bandno, numbands;
806
807         opj_cp_t *cp = j2k->cp;
808         opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
809         opj_tccp_t *tccp = &tcp->tccps[compno];
810         opj_cio_t *cio = j2k->cio;
811
812         tmp = cio_read(cio, 1);         /* Sqcx */
813         tccp->qntsty = tmp & 0x1f;
814         tccp->numgbits = tmp >> 5;
815         numbands = (tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 
816                 1 : ((tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ? len - 1 : (len - 1) / 2);
817
818 #ifdef USE_JPWL
819         if (j2k->cp->correct) {
820
821                 /* if JPWL is on, we check whether there are too many subbands */
822                 if ((numbands < 0) || (numbands >= J2K_MAXBANDS)) {
823                         opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
824                                 "JPWL: bad number of subbands in Sqcx (%d)\n",
825                                 numbands);
826                         if (!JPWL_ASSUME) {
827                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
828                                 return;
829                         }
830                         /* we try to correct */
831                         numbands = 1;
832                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n"
833                                 "- setting number of bands to %d => HYPOTHESIS!!!\n",
834                                 numbands);
835                 };
836
837         };
838 #endif /* USE_JPWL */
839
840         for (bandno = 0; bandno < numbands; bandno++) {
841                 int expn, mant;
842                 if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
843                         expn = cio_read(cio, 1) >> 3;   /* SPqcx_i */
844                         mant = 0;
845                 } else {
846                         tmp = cio_read(cio, 2); /* SPqcx_i */
847                         expn = tmp >> 11;
848                         mant = tmp & 0x7ff;
849                 }
850                 tccp->stepsizes[bandno].expn = expn;
851                 tccp->stepsizes[bandno].mant = mant;
852         }
853         
854         /* Add Antonin : if scalar_derived -> compute other stepsizes */
855         if (tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
856                 for (bandno = 1; bandno < J2K_MAXBANDS; bandno++) {
857                         tccp->stepsizes[bandno].expn = 
858                                 ((tccp->stepsizes[0].expn) - ((bandno - 1) / 3) > 0) ? 
859                                         (tccp->stepsizes[0].expn) - ((bandno - 1) / 3) : 0;
860                         tccp->stepsizes[bandno].mant = tccp->stepsizes[0].mant;
861                 }
862         }
863         /* ddA */
864 }
865
866 static void j2k_write_qcd(opj_j2k_t *j2k) {
867         int lenp, len;
868
869         opj_cio_t *cio = j2k->cio;
870         
871         cio_write(cio, J2K_MS_QCD, 2);  /* QCD */
872         lenp = cio_tell(cio);
873         cio_skip(cio, 2);
874         j2k_write_qcx(j2k, 0);
875         len = cio_tell(cio) - lenp;
876         cio_seek(cio, lenp);
877         cio_write(cio, len, 2);                 /* Lqcd */
878         cio_seek(cio, lenp + len);
879 }
880
881 static void j2k_read_qcd(opj_j2k_t *j2k) {
882         int len, i, pos;
883
884         opj_cio_t *cio = j2k->cio;
885         opj_image_t *image = j2k->image;
886         
887         len = cio_read(cio, 2);         /* Lqcd */
888         pos = cio_tell(cio);
889         for (i = 0; i < image->numcomps; i++) {
890                 cio_seek(cio, pos);
891                 j2k_read_qcx(j2k, i, len - 2);
892         }
893 }
894
895 static void j2k_write_qcc(opj_j2k_t *j2k, int compno) {
896         int lenp, len;
897
898         opj_cio_t *cio = j2k->cio;
899         
900         cio_write(cio, J2K_MS_QCC, 2);  /* QCC */
901         lenp = cio_tell(cio);
902         cio_skip(cio, 2);
903         cio_write(cio, compno, j2k->image->numcomps <= 256 ? 1 : 2);    /* Cqcc */
904         j2k_write_qcx(j2k, compno);
905         len = cio_tell(cio) - lenp;
906         cio_seek(cio, lenp);
907         cio_write(cio, len, 2);                 /* Lqcc */
908         cio_seek(cio, lenp + len);
909 }
910
911 static void j2k_read_qcc(opj_j2k_t *j2k) {
912         int len, compno;
913         int numcomp = j2k->image->numcomps;
914         opj_cio_t *cio = j2k->cio;
915         
916         len = cio_read(cio, 2); /* Lqcc */
917         compno = cio_read(cio, numcomp <= 256 ? 1 : 2); /* Cqcc */
918
919 #ifdef USE_JPWL
920         if (j2k->cp->correct) {
921
922                 static int backup_compno = 0;
923
924                 /* compno is negative or larger than the number of components!!! */
925                 if ((compno < 0) || (compno >= numcomp)) {
926                         opj_event_msg(j2k->cinfo, EVT_ERROR,
927                                 "JPWL: bad component number in QCC (%d out of a maximum of %d)\n",
928                                 compno, numcomp);
929                         if (!JPWL_ASSUME) {
930                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
931                                 return;
932                         }
933                         /* we try to correct */
934                         compno = backup_compno % numcomp;
935                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
936                                 "- setting component number to %d\n",
937                                 compno);
938                 }
939
940                 /* keep your private count of tiles */
941                 backup_compno++;
942         };
943 #endif /* USE_JPWL */
944
945         j2k_read_qcx(j2k, compno, len - 2 - (numcomp <= 256 ? 1 : 2));
946 }
947
948 static void j2k_write_poc(opj_j2k_t *j2k) {
949         int len, numpchgs, i;
950
951         int numcomps = j2k->image->numcomps;
952         
953         opj_cp_t *cp = j2k->cp;
954         opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
955         opj_tccp_t *tccp = &tcp->tccps[0];
956         opj_cio_t *cio = j2k->cio;
957
958         numpchgs = 1 + tcp->numpocs;
959         cio_write(cio, J2K_MS_POC, 2);  /* POC  */
960         len = 2 + (5 + 2 * (numcomps <= 256 ? 1 : 2)) * numpchgs;
961         cio_write(cio, len, 2);         /* Lpoc */
962         for (i = 0; i < numpchgs; i++) {
963                 opj_poc_t *poc = &tcp->pocs[i];
964                 cio_write(cio, poc->resno0, 1); /* RSpoc_i */
965                 cio_write(cio, poc->compno0, (numcomps <= 256 ? 1 : 2));        /* CSpoc_i */
966                 cio_write(cio, poc->layno1, 2); /* LYEpoc_i */
967                 poc->layno1 = int_min(poc->layno1, tcp->numlayers);
968                 cio_write(cio, poc->resno1, 1); /* REpoc_i */
969                 poc->resno1 = int_min(poc->resno1, tccp->numresolutions);
970                 cio_write(cio, poc->compno1, (numcomps <= 256 ? 1 : 2));        /* CEpoc_i */
971                 poc->compno1 = int_min(poc->compno1, numcomps);
972                 cio_write(cio, poc->prg, 1);    /* Ppoc_i */
973         }
974 }
975
976 static void j2k_read_poc(opj_j2k_t *j2k) {
977         int len, numpchgs, i, old_poc;
978
979         int numcomps = j2k->image->numcomps;
980         
981         opj_cp_t *cp = j2k->cp;
982         opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
983         opj_cio_t *cio = j2k->cio;
984         
985         old_poc = tcp->POC ? tcp->numpocs + 1 : 0;
986         tcp->POC = 1;
987         len = cio_read(cio, 2);         /* Lpoc */
988         numpchgs = (len - 2) / (5 + 2 * (numcomps <= 256 ? 1 : 2));
989         
990         for (i = old_poc; i < numpchgs + old_poc; i++) {
991                 opj_poc_t *poc;
992                 poc = &tcp->pocs[i];
993                 poc->resno0 = cio_read(cio, 1); /* RSpoc_i */
994                 poc->compno0 = cio_read(cio, numcomps <= 256 ? 1 : 2);  /* CSpoc_i */
995                 poc->layno1 = cio_read(cio, 2);    /* LYEpoc_i */
996                 poc->resno1 = cio_read(cio, 1);    /* REpoc_i */
997                 poc->compno1 = int_min(
998                         cio_read(cio, numcomps <= 256 ? 1 : 2), (unsigned int) numcomps);       /* CEpoc_i */
999                 poc->prg = (OPJ_PROG_ORDER)cio_read(cio, 1);    /* Ppoc_i */
1000         }
1001         
1002         tcp->numpocs = numpchgs + old_poc - 1;
1003 }
1004
1005 static void j2k_read_crg(opj_j2k_t *j2k) {
1006         int len, i, Xcrg_i, Ycrg_i;
1007         
1008         opj_cio_t *cio = j2k->cio;
1009         int numcomps = j2k->image->numcomps;
1010         
1011         len = cio_read(cio, 2);                 /* Lcrg */
1012         for (i = 0; i < numcomps; i++) {
1013                 Xcrg_i = cio_read(cio, 2);      /* Xcrg_i */
1014                 Ycrg_i = cio_read(cio, 2);      /* Ycrg_i */
1015         }
1016 }
1017
1018 static void j2k_read_tlm(opj_j2k_t *j2k) {
1019         int len, Ztlm, Stlm, ST, SP, tile_tlm, i;
1020         long int Ttlm_i, Ptlm_i;
1021
1022         opj_cio_t *cio = j2k->cio;
1023         
1024         len = cio_read(cio, 2);         /* Ltlm */
1025         Ztlm = cio_read(cio, 1);        /* Ztlm */
1026         Stlm = cio_read(cio, 1);        /* Stlm */
1027         ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
1028         SP = (Stlm >> 6) & 0x01;
1029         tile_tlm = (len - 4) / ((SP + 1) * 2 + ST);
1030         for (i = 0; i < tile_tlm; i++) {
1031                 Ttlm_i = cio_read(cio, ST);     /* Ttlm_i */
1032                 Ptlm_i = cio_read(cio, SP ? 4 : 2);     /* Ptlm_i */
1033         }
1034 }
1035
1036 static void j2k_read_plm(opj_j2k_t *j2k) {
1037         int len, i, Zplm, Nplm, add, packet_len = 0;
1038         
1039         opj_cio_t *cio = j2k->cio;
1040
1041         len = cio_read(cio, 2);         /* Lplm */
1042         Zplm = cio_read(cio, 1);        /* Zplm */
1043         len -= 3;
1044         while (len > 0) {
1045                 Nplm = cio_read(cio, 4);                /* Nplm */
1046                 len -= 4;
1047                 for (i = Nplm; i > 0; i--) {
1048                         add = cio_read(cio, 1);
1049                         len--;
1050                         packet_len = (packet_len << 7) + add;   /* Iplm_ij */
1051                         if ((add & 0x80) == 0) {
1052                                 /* New packet */
1053                                 packet_len = 0;
1054                         }
1055                         if (len <= 0)
1056                                 break;
1057                 }
1058         }
1059 }
1060
1061 static void j2k_read_plt(opj_j2k_t *j2k) {
1062         int len, i, Zplt, packet_len = 0, add;
1063         
1064         opj_cio_t *cio = j2k->cio;
1065         
1066         len = cio_read(cio, 2);         /* Lplt */
1067         Zplt = cio_read(cio, 1);        /* Zplt */
1068         for (i = len - 3; i > 0; i--) {
1069                 add = cio_read(cio, 1);
1070                 packet_len = (packet_len << 7) + add;   /* Iplt_i */
1071                 if ((add & 0x80) == 0) {
1072                         /* New packet */
1073                         packet_len = 0;
1074                 }
1075         }
1076 }
1077
1078 static void j2k_read_ppm(opj_j2k_t *j2k) {
1079         int len, Z_ppm, i, j;
1080         int N_ppm;
1081
1082         opj_cp_t *cp = j2k->cp;
1083         opj_cio_t *cio = j2k->cio;
1084         
1085         len = cio_read(cio, 2);
1086         cp->ppm = 1;
1087         
1088         Z_ppm = cio_read(cio, 1);       /* Z_ppm */
1089         len -= 3;
1090         while (len > 0) {
1091                 if (cp->ppm_previous == 0) {
1092                         N_ppm = cio_read(cio, 4);       /* N_ppm */
1093                         len -= 4;
1094                 } else {
1095                         N_ppm = cp->ppm_previous;
1096                 }
1097                 j = cp->ppm_store;
1098                 if (Z_ppm == 0) {       /* First PPM marker */
1099                         cp->ppm_data = (unsigned char *) opj_malloc(N_ppm * sizeof(unsigned char));
1100                         cp->ppm_data_first = cp->ppm_data;
1101                         cp->ppm_len = N_ppm;
1102                 } else {                        /* NON-first PPM marker */
1103                         cp->ppm_data = (unsigned char *) opj_realloc(cp->ppm_data, (N_ppm +     cp->ppm_store) * sizeof(unsigned char));
1104
1105 #ifdef USE_JPWL
1106                         /* this memory allocation check could be done even in non-JPWL cases */
1107                         if (cp->correct) {
1108                                 if (!cp->ppm_data) {
1109                                         opj_event_msg(j2k->cinfo, EVT_ERROR,
1110                                                 "JPWL: failed memory allocation during PPM marker parsing (pos. %x)\n",
1111                                                 cio_tell(cio));
1112                                         if (!JPWL_ASSUME || JPWL_ASSUME) {
1113                                                 opj_free(cp->ppm_data);
1114                                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
1115                                                 return;
1116                                         }
1117                                 }
1118                         }
1119 #endif
1120
1121                         cp->ppm_data_first = cp->ppm_data;
1122                         cp->ppm_len = N_ppm + cp->ppm_store;
1123                 }
1124                 for (i = N_ppm; i > 0; i--) {   /* Read packet header */
1125                         cp->ppm_data[j] = cio_read(cio, 1);
1126                         j++;
1127                         len--;
1128                         if (len == 0)
1129                                 break;                  /* Case of non-finished packet header in present marker but finished in next one */
1130                 }
1131                 cp->ppm_previous = i - 1;
1132                 cp->ppm_store = j;
1133         }
1134 }
1135
1136 static void j2k_read_ppt(opj_j2k_t *j2k) {
1137         int len, Z_ppt, i, j = 0;
1138
1139         opj_cp_t *cp = j2k->cp;
1140         opj_tcp_t *tcp = cp->tcps + j2k->curtileno;
1141         opj_cio_t *cio = j2k->cio;
1142
1143         len = cio_read(cio, 2);
1144         Z_ppt = cio_read(cio, 1);
1145         tcp->ppt = 1;
1146         if (Z_ppt == 0) {               /* First PPT marker */
1147                 tcp->ppt_data = (unsigned char *) opj_malloc((len - 3) * sizeof(unsigned char));
1148                 tcp->ppt_data_first = tcp->ppt_data;
1149                 tcp->ppt_store = 0;
1150                 tcp->ppt_len = len - 3;
1151         } else {                        /* NON-first PPT marker */
1152                 tcp->ppt_data = (unsigned char *) opj_realloc(tcp->ppt_data, (len - 3 + tcp->ppt_store) * sizeof(unsigned char));
1153                 tcp->ppt_data_first = tcp->ppt_data;
1154                 tcp->ppt_len = len - 3 + tcp->ppt_store;
1155         }
1156         j = tcp->ppt_store;
1157         for (i = len - 3; i > 0; i--) {
1158                 tcp->ppt_data[j] = cio_read(cio, 1);
1159                 j++;
1160         }
1161         tcp->ppt_store = j;
1162 }
1163
1164 static void j2k_write_tlm(opj_j2k_t *j2k){
1165         int lenp;
1166         opj_cio_t *cio = j2k->cio;
1167         j2k->tlm_start = cio_tell(cio);
1168         cio_write(cio, J2K_MS_TLM, 2);/* TLM */
1169         lenp = 4 + (5*j2k->totnum_tp);
1170         cio_write(cio,lenp,2);                          /* Ltlm */
1171         cio_write(cio, 0,1);                                    /* Ztlm=0*/
1172         cio_write(cio,80,1);                                    /* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */
1173         cio_skip(cio,5*j2k->totnum_tp);
1174 }
1175
1176 static void j2k_write_sot(opj_j2k_t *j2k) {
1177         int lenp, len;
1178
1179         opj_cio_t *cio = j2k->cio;
1180
1181         j2k->sot_start = cio_tell(cio);
1182         cio_write(cio, J2K_MS_SOT, 2);          /* SOT */
1183         lenp = cio_tell(cio);
1184         cio_skip(cio, 2);                                       /* Lsot (further) */
1185         cio_write(cio, j2k->curtileno, 2);      /* Isot */
1186         cio_skip(cio, 4);                                       /* Psot (further in j2k_write_sod) */
1187         cio_write(cio, j2k->cur_tp_num , 1);    /* TPsot */
1188         cio_write(cio, j2k->cur_totnum_tp[j2k->curtileno], 1);          /* TNsot */
1189         len = cio_tell(cio) - lenp;
1190         cio_seek(cio, lenp);
1191         cio_write(cio, len, 2);                         /* Lsot */
1192         cio_seek(cio, lenp + len);
1193
1194         /* UniPG>> */
1195 #ifdef USE_JPWL
1196         /* update markers struct */
1197         j2k_add_marker(j2k->cstr_info, J2K_MS_SOT, j2k->sot_start, len + 2);
1198 #endif /* USE_JPWL */
1199         /* <<UniPG */
1200 }
1201
1202 static void j2k_read_sot(opj_j2k_t *j2k) {
1203         int len, tileno, totlen, partno, numparts, i;
1204         opj_tcp_t *tcp = NULL;
1205         char status = 0;
1206
1207         opj_cp_t *cp = j2k->cp;
1208         opj_cio_t *cio = j2k->cio;
1209
1210         len = cio_read(cio, 2);
1211         tileno = cio_read(cio, 2);
1212
1213 #ifdef USE_JPWL
1214         if (j2k->cp->correct) {
1215
1216                 static int backup_tileno = 0;
1217
1218                 /* tileno is negative or larger than the number of tiles!!! */
1219                 if ((tileno < 0) || (tileno > (cp->tw * cp->th))) {
1220                         opj_event_msg(j2k->cinfo, EVT_ERROR,
1221                                 "JPWL: bad tile number (%d out of a maximum of %d)\n",
1222                                 tileno, (cp->tw * cp->th));
1223                         if (!JPWL_ASSUME) {
1224                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
1225                                 return;
1226                         }
1227                         /* we try to correct */
1228                         tileno = backup_tileno;
1229                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
1230                                 "- setting tile number to %d\n",
1231                                 tileno);
1232                 }
1233
1234                 /* keep your private count of tiles */
1235                 backup_tileno++;
1236         };
1237 #endif /* USE_JPWL */
1238         
1239         if (cp->tileno_size == 0) {
1240                 cp->tileno[cp->tileno_size] = tileno;
1241                 cp->tileno_size++;
1242         } else {
1243                 i = 0;
1244                 while (i < cp->tileno_size && status == 0) {
1245                         status = cp->tileno[i] == tileno ? 1 : 0;
1246                         i++;
1247                 }
1248                 if (status == 0) {
1249                         cp->tileno[cp->tileno_size] = tileno;
1250                         cp->tileno_size++;
1251                 }
1252         }
1253         
1254         totlen = cio_read(cio, 4);
1255
1256 #ifdef USE_JPWL
1257         if (j2k->cp->correct) {
1258
1259                 /* totlen is negative or larger than the bytes left!!! */
1260                 if ((totlen < 0) || (totlen > (cio_numbytesleft(cio) + 8))) {
1261                         opj_event_msg(j2k->cinfo, EVT_ERROR,
1262                                 "JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
1263                                 totlen, cio_numbytesleft(cio) + 8);
1264                         if (!JPWL_ASSUME) {
1265                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
1266                                 return;
1267                         }
1268                         /* we try to correct */
1269                         totlen = 0;
1270                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
1271                                 "- setting Psot to %d => assuming it is the last tile\n",
1272                                 totlen);
1273                 }
1274
1275         };
1276 #endif /* USE_JPWL */
1277
1278         if (!totlen)
1279                 totlen = cio_numbytesleft(cio) + 8;
1280         
1281         partno = cio_read(cio, 1);
1282         numparts = cio_read(cio, 1);
1283   
1284   if (partno >= numparts) {
1285     opj_event_msg(j2k->cinfo, EVT_WARNING, "SOT marker inconsistency in tile %d: tile-part index greater than number of tile-parts\n", tileno);
1286     numparts = partno+1;
1287   }
1288         
1289         j2k->curtileno = tileno;
1290         j2k->cur_tp_num = partno;
1291         j2k->eot = cio_getbp(cio) - 12 + totlen;
1292         j2k->state = J2K_STATE_TPH;
1293         tcp = &cp->tcps[j2k->curtileno];
1294
1295         /* Index */
1296         if (j2k->cstr_info) {
1297                 if (tcp->first) {
1298                         if (tileno == 0) 
1299                                 j2k->cstr_info->main_head_end = cio_tell(cio) - 13;
1300                         j2k->cstr_info->tile[tileno].tileno = tileno;
1301                         j2k->cstr_info->tile[tileno].start_pos = cio_tell(cio) - 12;
1302                         j2k->cstr_info->tile[tileno].end_pos = j2k->cstr_info->tile[tileno].start_pos + totlen - 1;                             
1303     } else {
1304                         j2k->cstr_info->tile[tileno].end_pos += totlen;
1305                 }
1306     j2k->cstr_info->tile[tileno].num_tps = numparts;
1307     if (numparts)
1308       j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_realloc(j2k->cstr_info->tile[tileno].tp, numparts * sizeof(opj_tp_info_t));
1309     else
1310       j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_realloc(j2k->cstr_info->tile[tileno].tp, 10 * sizeof(opj_tp_info_t)); // Fixme (10)
1311                 j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = cio_tell(cio) - 12;
1312                 j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos = 
1313                         j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
1314         }
1315         
1316         if (tcp->first == 1) {          
1317                 /* Initialization PPT */
1318                 opj_tccp_t *tmp = tcp->tccps;
1319                 memcpy(tcp, j2k->default_tcp, sizeof(opj_tcp_t));
1320                 tcp->ppt = 0;
1321                 tcp->ppt_data = NULL;
1322                 tcp->ppt_data_first = NULL;
1323                 tcp->tccps = tmp;
1324
1325                 for (i = 0; i < j2k->image->numcomps; i++) {
1326                         tcp->tccps[i] = j2k->default_tcp->tccps[i];
1327                 }
1328                 cp->tcps[j2k->curtileno].first = 0;
1329         }
1330 }
1331
1332 static void j2k_write_sod(opj_j2k_t *j2k, void *tile_coder) {
1333         int l, layno;
1334         int totlen;
1335         opj_tcp_t *tcp = NULL;
1336         opj_codestream_info_t *cstr_info = NULL;
1337         
1338         opj_tcd_t *tcd = (opj_tcd_t*)tile_coder;        /* cast is needed because of conflicts in header inclusions */
1339         opj_cp_t *cp = j2k->cp;
1340         opj_cio_t *cio = j2k->cio;
1341
1342         tcd->tp_num = j2k->tp_num ;
1343         tcd->cur_tp_num = j2k->cur_tp_num;
1344         
1345         cio_write(cio, J2K_MS_SOD, 2);
1346         if (j2k->curtileno == 0) {
1347                 j2k->sod_start = cio_tell(cio) + j2k->pos_correction;
1348         }
1349
1350         /* INDEX >> */
1351         cstr_info = j2k->cstr_info;
1352         if (cstr_info) {
1353                 if (!j2k->cur_tp_num ) {
1354                         cstr_info->tile[j2k->curtileno].end_header = cio_tell(cio) + j2k->pos_correction - 1;
1355                         j2k->cstr_info->tile[j2k->curtileno].tileno = j2k->curtileno;
1356                 }
1357                 else{
1358                         if(cstr_info->tile[j2k->curtileno].packet[cstr_info->packno - 1].end_pos < cio_tell(cio))
1359                                 cstr_info->tile[j2k->curtileno].packet[cstr_info->packno].start_pos = cio_tell(cio);
1360                 }
1361                 /* UniPG>> */
1362 #ifdef USE_JPWL
1363                 /* update markers struct */
1364                 j2k_add_marker(j2k->cstr_info, J2K_MS_SOD, j2k->sod_start, 2);
1365 #endif /* USE_JPWL */
1366                 /* <<UniPG */
1367         }
1368         /* << INDEX */
1369         
1370         tcp = &cp->tcps[j2k->curtileno];
1371         for (layno = 0; layno < tcp->numlayers; layno++) {
1372                 if (tcp->rates[layno]>(j2k->sod_start / (cp->th * cp->tw))) {
1373                         tcp->rates[layno]-=(j2k->sod_start / (cp->th * cp->tw));
1374                 } else if (tcp->rates[layno]) {
1375                         tcp->rates[layno]=1;
1376                 }
1377         }
1378         if(j2k->cur_tp_num == 0){
1379                 tcd->tcd_image->tiles->packno = 0;
1380                 if(cstr_info)
1381                         cstr_info->packno = 0;
1382         }
1383         
1384         l = tcd_encode_tile(tcd, j2k->curtileno, cio_getbp(cio), cio_numbytesleft(cio) - 2, cstr_info);
1385         
1386         /* Writing Psot in SOT marker */
1387         totlen = cio_tell(cio) + l - j2k->sot_start;
1388         cio_seek(cio, j2k->sot_start + 6);
1389         cio_write(cio, totlen, 4);
1390         cio_seek(cio, j2k->sot_start + totlen);
1391         /* Writing Ttlm and Ptlm in TLM marker */
1392         if(cp->cinema){
1393                 cio_seek(cio, j2k->tlm_start + 6 + (5*j2k->cur_tp_num));
1394                 cio_write(cio, j2k->curtileno, 1);
1395                 cio_write(cio, totlen, 4);
1396         }
1397         cio_seek(cio, j2k->sot_start + totlen);
1398 }
1399
1400 static void j2k_read_sod(opj_j2k_t *j2k) {
1401         int len, truncate = 0, i;
1402         unsigned char *data = NULL, *data_ptr = NULL;
1403
1404         opj_cio_t *cio = j2k->cio;
1405         int curtileno = j2k->curtileno;
1406
1407         /* Index */
1408         if (j2k->cstr_info) {
1409                 j2k->cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_header =
1410                         cio_tell(cio) + j2k->pos_correction - 1;
1411                 if (j2k->cur_tp_num == 0)
1412                         j2k->cstr_info->tile[j2k->curtileno].end_header = cio_tell(cio) + j2k->pos_correction - 1;
1413                 j2k->cstr_info->packno = 0;
1414         }
1415         
1416         len = int_min(j2k->eot - cio_getbp(cio), cio_numbytesleft(cio) + 1);
1417
1418         if (len == cio_numbytesleft(cio) + 1) {
1419                 truncate = 1;           /* Case of a truncate codestream */
1420         }       
1421
1422         data = j2k->tile_data[curtileno];
1423         data = (unsigned char*) opj_realloc(data, (j2k->tile_len[curtileno] + len) * sizeof(unsigned char));
1424
1425         data_ptr = data + j2k->tile_len[curtileno];
1426         for (i = 0; i < len; i++) {
1427                 data_ptr[i] = cio_read(cio, 1);
1428         }
1429
1430         j2k->tile_len[curtileno] += len;
1431         j2k->tile_data[curtileno] = data;
1432         
1433         if (!truncate) {
1434                 j2k->state = J2K_STATE_TPHSOT;
1435         } else {
1436                 j2k->state = J2K_STATE_NEOC;    /* RAJOUTE !! */
1437         }
1438         j2k->cur_tp_num++;
1439 }
1440
1441 static void j2k_write_rgn(opj_j2k_t *j2k, int compno, int tileno) {
1442         opj_cp_t *cp = j2k->cp;
1443         opj_tcp_t *tcp = &cp->tcps[tileno];
1444         opj_cio_t *cio = j2k->cio;
1445         int numcomps = j2k->image->numcomps;
1446         
1447         cio_write(cio, J2K_MS_RGN, 2);                                          /* RGN  */
1448         cio_write(cio, numcomps <= 256 ? 5 : 6, 2);                     /* Lrgn */
1449         cio_write(cio, compno, numcomps <= 256 ? 1 : 2);        /* Crgn */
1450         cio_write(cio, 0, 1);                                                           /* Srgn */
1451         cio_write(cio, tcp->tccps[compno].roishift, 1);         /* SPrgn */
1452 }
1453
1454 static void j2k_read_rgn(opj_j2k_t *j2k) {
1455         int len, compno, roisty;
1456
1457         opj_cp_t *cp = j2k->cp;
1458         opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
1459         opj_cio_t *cio = j2k->cio;
1460         int numcomps = j2k->image->numcomps;
1461
1462         len = cio_read(cio, 2);                                                                         /* Lrgn */
1463         compno = cio_read(cio, numcomps <= 256 ? 1 : 2);                        /* Crgn */
1464         roisty = cio_read(cio, 1);                                                                      /* Srgn */
1465
1466 #ifdef USE_JPWL
1467         if (j2k->cp->correct) {
1468                 /* totlen is negative or larger than the bytes left!!! */
1469                 if (compno >= numcomps) {
1470                         opj_event_msg(j2k->cinfo, EVT_ERROR,
1471                                 "JPWL: bad component number in RGN (%d when there are only %d)\n",
1472                                 compno, numcomps);
1473                         if (!JPWL_ASSUME || JPWL_ASSUME) {
1474                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
1475                                 return;
1476                         }
1477                 }
1478         };
1479 #endif /* USE_JPWL */
1480
1481         tcp->tccps[compno].roishift = cio_read(cio, 1);                         /* SPrgn */
1482 }
1483
1484 static void j2k_write_eoc(opj_j2k_t *j2k) {
1485         opj_cio_t *cio = j2k->cio;
1486         /* opj_event_msg(j2k->cinfo, "%.8x: EOC\n", cio_tell(cio) + j2k->pos_correction); */
1487         cio_write(cio, J2K_MS_EOC, 2);
1488
1489 /* UniPG>> */
1490 #ifdef USE_JPWL
1491         /* update markers struct */
1492         j2k_add_marker(j2k->cstr_info, J2K_MS_EOC, cio_tell(cio) - 2, 2);
1493 #endif /* USE_JPWL */
1494 /* <<UniPG */
1495 }
1496
1497 static void j2k_read_eoc(opj_j2k_t *j2k) {
1498         int i, tileno;
1499         opj_bool success;
1500
1501         /* if packets should be decoded */
1502         if (j2k->cp->limit_decoding != DECODE_ALL_BUT_PACKETS) {
1503                 opj_tcd_t *tcd = tcd_create(j2k->cinfo);
1504                 tcd_malloc_decode(tcd, j2k->image, j2k->cp);
1505                 for (i = 0; i < j2k->cp->tileno_size; i++) {
1506                         tcd_malloc_decode_tile(tcd, j2k->image, j2k->cp, i, j2k->cstr_info);
1507                         tileno = j2k->cp->tileno[i];
1508                         success = tcd_decode_tile(tcd, j2k->tile_data[tileno], j2k->tile_len[tileno], tileno, j2k->cstr_info);
1509                         opj_free(j2k->tile_data[tileno]);
1510                         j2k->tile_data[tileno] = NULL;
1511                         tcd_free_decode_tile(tcd, i);
1512                         if (success == OPJ_FALSE) {
1513                                 j2k->state |= J2K_STATE_ERR;
1514                                 break;
1515                         }
1516                 }
1517                 tcd_free_decode(tcd);
1518                 tcd_destroy(tcd);
1519         }
1520         /* if packets should not be decoded  */
1521         else {
1522                 for (i = 0; i < j2k->cp->tileno_size; i++) {
1523                         tileno = j2k->cp->tileno[i];
1524                         opj_free(j2k->tile_data[tileno]);
1525                         j2k->tile_data[tileno] = NULL;
1526                 }
1527         }       
1528         if (j2k->state & J2K_STATE_ERR)
1529                 j2k->state = J2K_STATE_MT + J2K_STATE_ERR;
1530         else
1531                 j2k->state = J2K_STATE_MT; 
1532 }
1533
1534 typedef struct opj_dec_mstabent {
1535         /** marker value */
1536         int id;
1537         /** value of the state when the marker can appear */
1538         int states;
1539         /** action linked to the marker */
1540         void (*handler) (opj_j2k_t *j2k);
1541 } opj_dec_mstabent_t;
1542
1543 opj_dec_mstabent_t j2k_dec_mstab[] = {
1544   {J2K_MS_SOC, J2K_STATE_MHSOC, j2k_read_soc},
1545   {J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, j2k_read_sot},
1546   {J2K_MS_SOD, J2K_STATE_TPH, j2k_read_sod},
1547   {J2K_MS_EOC, J2K_STATE_TPHSOT, j2k_read_eoc},
1548   {J2K_MS_SIZ, J2K_STATE_MHSIZ, j2k_read_siz},
1549   {J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_cod},
1550   {J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_coc},
1551   {J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_rgn},
1552   {J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_qcd},
1553   {J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_qcc},
1554   {J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_poc},
1555   {J2K_MS_TLM, J2K_STATE_MH, j2k_read_tlm},
1556   {J2K_MS_PLM, J2K_STATE_MH, j2k_read_plm},
1557   {J2K_MS_PLT, J2K_STATE_TPH, j2k_read_plt},
1558   {J2K_MS_PPM, J2K_STATE_MH, j2k_read_ppm},
1559   {J2K_MS_PPT, J2K_STATE_TPH, j2k_read_ppt},
1560   {J2K_MS_SOP, 0, 0},
1561   {J2K_MS_CRG, J2K_STATE_MH, j2k_read_crg},
1562   {J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_com},
1563
1564 #ifdef USE_JPWL
1565   {J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc},
1566   {J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb},
1567   {J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd},
1568   {J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red},
1569 #endif /* USE_JPWL */
1570 #ifdef USE_JPSEC
1571   {J2K_MS_SEC, J2K_STATE_MH, j2k_read_sec},
1572   {J2K_MS_INSEC, 0, j2k_read_insec},
1573 #endif /* USE_JPSEC */
1574
1575   {0, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_unk}
1576 };
1577
1578 static void j2k_read_unk(opj_j2k_t *j2k) {
1579         opj_event_msg(j2k->cinfo, EVT_WARNING, "Unknown marker\n");
1580
1581 #ifdef USE_JPWL
1582         if (j2k->cp->correct) {
1583                 int m = 0, id, i;
1584                 int min_id = 0, min_dist = 17, cur_dist = 0, tmp_id;
1585                 cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
1586                 id = cio_read(j2k->cio, 2);
1587                 opj_event_msg(j2k->cinfo, EVT_ERROR,
1588                         "JPWL: really don't know this marker %x\n",
1589                         id);
1590                 if (!JPWL_ASSUME) {
1591                         opj_event_msg(j2k->cinfo, EVT_ERROR,
1592                                 "- possible synch loss due to uncorrectable codestream errors => giving up\n");
1593                         return;
1594                 }
1595                 /* OK, activate this at your own risk!!! */
1596                 /* we look for the marker at the minimum hamming distance from this */
1597                 while (j2k_dec_mstab[m].id) {
1598                         
1599                         /* 1's where they differ */
1600                         tmp_id = j2k_dec_mstab[m].id ^ id;
1601
1602                         /* compute the hamming distance between our id and the current */
1603                         cur_dist = 0;
1604                         for (i = 0; i < 16; i++) {
1605                                 if ((tmp_id >> i) & 0x0001) {
1606                                         cur_dist++;
1607                                 }
1608                         }
1609
1610                         /* if current distance is smaller, set the minimum */
1611                         if (cur_dist < min_dist) {
1612                                 min_dist = cur_dist;
1613                                 min_id = j2k_dec_mstab[m].id;
1614                         }
1615                         
1616                         /* jump to the next marker */
1617                         m++;
1618                 }
1619
1620                 /* do we substitute the marker? */
1621                 if (min_dist < JPWL_MAXIMUM_HAMMING) {
1622                         opj_event_msg(j2k->cinfo, EVT_ERROR,
1623                                 "- marker %x is at distance %d from the read %x\n",
1624                                 min_id, min_dist, id);
1625                         opj_event_msg(j2k->cinfo, EVT_ERROR,
1626                                 "- trying to substitute in place and crossing fingers!\n");
1627                         cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
1628                         cio_write(j2k->cio, min_id, 2);
1629
1630                         /* rewind */
1631                         cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
1632
1633                 }
1634
1635         };
1636 #endif /* USE_JPWL */
1637
1638 }
1639
1640 /**
1641 Read the lookup table containing all the marker, status and action
1642 @param id Marker value
1643 */
1644 static opj_dec_mstabent_t *j2k_dec_mstab_lookup(int id) {
1645         opj_dec_mstabent_t *e;
1646         for (e = j2k_dec_mstab; e->id != 0; e++) {
1647                 if (e->id == id) {
1648                         break;
1649                 }
1650         }
1651         return e;
1652 }
1653
1654 /* ----------------------------------------------------------------------- */
1655 /* J2K / JPT decoder interface                                             */
1656 /* ----------------------------------------------------------------------- */
1657
1658 opj_j2k_t* j2k_create_decompress(opj_common_ptr cinfo) {
1659         opj_j2k_t *j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
1660         if(!j2k)
1661                 return NULL;
1662
1663         j2k->default_tcp = (opj_tcp_t*) opj_calloc(1, sizeof(opj_tcp_t));
1664         if(!j2k->default_tcp) {
1665                 opj_free(j2k);
1666                 return NULL;
1667         }
1668
1669         j2k->cinfo = cinfo;
1670         j2k->tile_data = NULL;
1671
1672         return j2k;
1673 }
1674
1675 void j2k_destroy_decompress(opj_j2k_t *j2k) {
1676         int i = 0;
1677
1678         if(j2k->tile_len != NULL) {
1679                 opj_free(j2k->tile_len);
1680         }
1681         if(j2k->tile_data != NULL) {
1682                 opj_free(j2k->tile_data);
1683         }
1684         if(j2k->default_tcp != NULL) {
1685                 opj_tcp_t *default_tcp = j2k->default_tcp;
1686                 if(default_tcp->ppt_data_first != NULL) {
1687                         opj_free(default_tcp->ppt_data_first);
1688                 }
1689                 if(j2k->default_tcp->tccps != NULL) {
1690                         opj_free(j2k->default_tcp->tccps);
1691                 }
1692                 opj_free(j2k->default_tcp);
1693         }
1694         if(j2k->cp != NULL) {
1695                 opj_cp_t *cp = j2k->cp;
1696                 if(cp->tcps != NULL) {
1697                         for(i = 0; i < cp->tw * cp->th; i++) {
1698                                 if(cp->tcps[i].ppt_data_first != NULL) {
1699                                         opj_free(cp->tcps[i].ppt_data_first);
1700                                 }
1701                                 if(cp->tcps[i].tccps != NULL) {
1702                                         opj_free(cp->tcps[i].tccps);
1703                                 }
1704                         }
1705                         opj_free(cp->tcps);
1706                 }
1707                 if(cp->ppm_data_first != NULL) {
1708                         opj_free(cp->ppm_data_first);
1709                 }
1710                 if(cp->tileno != NULL) {
1711                         opj_free(cp->tileno);  
1712                 }
1713                 if(cp->comment != NULL) {
1714                         opj_free(cp->comment);
1715                 }
1716
1717                 opj_free(cp);
1718         }
1719         opj_free(j2k);
1720 }
1721
1722 void j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters) {
1723         if(j2k && parameters) {
1724                 /* create and initialize the coding parameters structure */
1725                 opj_cp_t *cp = (opj_cp_t*) opj_calloc(1, sizeof(opj_cp_t));
1726                 cp->reduce = parameters->cp_reduce;     
1727                 cp->layer = parameters->cp_layer;
1728                 cp->limit_decoding = parameters->cp_limit_decoding;
1729
1730 #ifdef USE_JPWL
1731                 cp->correct = parameters->jpwl_correct;
1732                 cp->exp_comps = parameters->jpwl_exp_comps;
1733                 cp->max_tiles = parameters->jpwl_max_tiles;
1734 #endif /* USE_JPWL */
1735
1736
1737                 /* keep a link to cp so that we can destroy it later in j2k_destroy_decompress */
1738                 j2k->cp = cp;
1739         }
1740 }
1741
1742 opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *cstr_info) {
1743         opj_image_t *image = NULL;
1744
1745         opj_common_ptr cinfo = j2k->cinfo;      
1746
1747         j2k->cio = cio;
1748         j2k->cstr_info = cstr_info;
1749         if (cstr_info)
1750                 memset(cstr_info, 0, sizeof(opj_codestream_info_t));
1751
1752         /* create an empty image */
1753         image = opj_image_create0();
1754         j2k->image = image;
1755
1756         j2k->state = J2K_STATE_MHSOC;
1757
1758         for (;;) {
1759                 opj_dec_mstabent_t *e;
1760                 int id = cio_read(cio, 2);
1761
1762 #ifdef USE_JPWL
1763                 /* we try to honor JPWL correction power */
1764                 if (j2k->cp->correct) {
1765
1766                         int orig_pos = cio_tell(cio);
1767                         opj_bool status;
1768
1769                         /* call the corrector */
1770                         status = jpwl_correct(j2k);
1771
1772                         /* go back to where you were */
1773                         cio_seek(cio, orig_pos - 2);
1774
1775                         /* re-read the marker */
1776                         id = cio_read(cio, 2);
1777
1778                         /* check whether it begins with ff */
1779                         if (id >> 8 != 0xff) {
1780                                 opj_event_msg(cinfo, EVT_ERROR,
1781                                         "JPWL: possible bad marker %x at %d\n",
1782                                         id, cio_tell(cio) - 2);
1783                                 if (!JPWL_ASSUME) {
1784                                         opj_image_destroy(image);
1785                                         opj_event_msg(cinfo, EVT_ERROR, "JPWL: giving up\n");
1786                                         return 0;
1787                                 }
1788                                 /* we try to correct */
1789                                 id = id | 0xff00;
1790                                 cio_seek(cio, cio_tell(cio) - 2);
1791                                 cio_write(cio, id, 2);
1792                                 opj_event_msg(cinfo, EVT_WARNING, "- trying to adjust this\n"
1793                                         "- setting marker to %x\n",
1794                                         id);
1795                         }
1796
1797                 }
1798 #endif /* USE_JPWL */
1799
1800                 if (id >> 8 != 0xff) {
1801                         opj_image_destroy(image);
1802                         opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
1803                         return 0;
1804                 }
1805                 e = j2k_dec_mstab_lookup(id);
1806                 // Check if the marker is known
1807                 if (!(j2k->state & e->states)) {
1808                         opj_image_destroy(image);
1809                         opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id);
1810                         return 0;
1811                 }
1812                 // Check if the decoding is limited to the main header
1813                 if (e->id == J2K_MS_SOT && j2k->cp->limit_decoding == LIMIT_TO_MAIN_HEADER) {
1814                         opj_event_msg(cinfo, EVT_INFO, "Main Header decoded.\n");
1815                         return image;
1816                 }               
1817
1818                 if (e->handler) {
1819                         (*e->handler)(j2k);
1820                 }
1821                 if (j2k->state & J2K_STATE_ERR) 
1822                         return NULL;    
1823
1824                 if (j2k->state == J2K_STATE_MT) {
1825                         break;
1826                 }
1827                 if (j2k->state == J2K_STATE_NEOC) {
1828                         break;
1829                 }
1830         }
1831         if (j2k->state == J2K_STATE_NEOC) {
1832                 j2k_read_eoc(j2k);
1833         }
1834
1835         if (j2k->state != J2K_STATE_MT) {
1836                 opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n");
1837         }
1838
1839         return image;
1840 }
1841
1842 /*
1843 * Read a JPT-stream and decode file
1844 *
1845 */
1846 opj_image_t* j2k_decode_jpt_stream(opj_j2k_t *j2k, opj_cio_t *cio,  opj_codestream_info_t *cstr_info) {
1847         opj_image_t *image = NULL;
1848         opj_jpt_msg_header_t header;
1849         int position;
1850
1851         opj_common_ptr cinfo = j2k->cinfo;
1852         
1853         j2k->cio = cio;
1854
1855         /* create an empty image */
1856         image = opj_image_create0();
1857         j2k->image = image;
1858
1859         j2k->state = J2K_STATE_MHSOC;
1860         
1861         /* Initialize the header */
1862         jpt_init_msg_header(&header);
1863         /* Read the first header of the message */
1864         jpt_read_msg_header(cinfo, cio, &header);
1865         
1866         position = cio_tell(cio);
1867         if (header.Class_Id != 6) {     /* 6 : Main header data-bin message */
1868                 opj_image_destroy(image);
1869                 opj_event_msg(cinfo, EVT_ERROR, "[JPT-stream] : Expecting Main header first [class_Id %d] !\n", header.Class_Id);
1870                 return 0;
1871         }
1872         
1873         for (;;) {
1874                 opj_dec_mstabent_t *e = NULL;
1875                 int id;
1876                 
1877                 if (!cio_numbytesleft(cio)) {
1878                         j2k_read_eoc(j2k);
1879                         return image;
1880                 }
1881                 /* data-bin read -> need to read a new header */
1882                 if ((unsigned int) (cio_tell(cio) - position) == header.Msg_length) {
1883                         jpt_read_msg_header(cinfo, cio, &header);
1884                         position = cio_tell(cio);
1885                         if (header.Class_Id != 4) {     /* 4 : Tile data-bin message */
1886                                 opj_image_destroy(image);
1887                                 opj_event_msg(cinfo, EVT_ERROR, "[JPT-stream] : Expecting Tile info !\n");
1888                                 return 0;
1889                         }
1890                 }
1891                 
1892                 id = cio_read(cio, 2);
1893                 if (id >> 8 != 0xff) {
1894                         opj_image_destroy(image);
1895                         opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
1896                         return 0;
1897                 }
1898                 e = j2k_dec_mstab_lookup(id);
1899                 if (!(j2k->state & e->states)) {
1900                         opj_image_destroy(image);
1901                         opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id);
1902                         return 0;
1903                 }
1904                 if (e->handler) {
1905                         (*e->handler)(j2k);
1906                 }
1907                 if (j2k->state == J2K_STATE_MT) {
1908                         break;
1909                 }
1910                 if (j2k->state == J2K_STATE_NEOC) {
1911                         break;
1912                 }
1913         }
1914         if (j2k->state == J2K_STATE_NEOC) {
1915                 j2k_read_eoc(j2k);
1916         }
1917         
1918         if (j2k->state != J2K_STATE_MT) {
1919                 opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n");
1920         }
1921
1922         return image;
1923 }
1924
1925 /* ----------------------------------------------------------------------- */
1926 /* J2K encoder interface                                                       */
1927 /* ----------------------------------------------------------------------- */
1928
1929 opj_j2k_t* j2k_create_compress(opj_common_ptr cinfo) {
1930         opj_j2k_t *j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
1931         if(j2k) {
1932                 j2k->cinfo = cinfo;
1933         }
1934         return j2k;
1935 }
1936
1937 void j2k_destroy_compress(opj_j2k_t *j2k) {
1938         int tileno;
1939
1940         if(!j2k) return;
1941         if(j2k->cp != NULL) {
1942                 opj_cp_t *cp = j2k->cp;
1943
1944                 if(cp->comment) {
1945                         opj_free(cp->comment);
1946                 }
1947                 if(cp->matrice) {
1948                         opj_free(cp->matrice);
1949                 }
1950                 for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
1951                         opj_free(cp->tcps[tileno].tccps);
1952                 }
1953                 opj_free(cp->tcps);
1954                 opj_free(cp);
1955         }
1956
1957         opj_free(j2k);
1958 }
1959
1960 void j2k_setup_encoder(opj_j2k_t *j2k, opj_cparameters_t *parameters, opj_image_t *image) {
1961         int i, j, tileno, numpocs_tile;
1962         opj_cp_t *cp = NULL;
1963
1964         if(!j2k || !parameters || ! image) {
1965                 return;
1966         }
1967
1968         /* create and initialize the coding parameters structure */
1969         cp = (opj_cp_t*) opj_calloc(1, sizeof(opj_cp_t));
1970
1971         /* keep a link to cp so that we can destroy it later in j2k_destroy_compress */
1972         j2k->cp = cp;
1973
1974         /* set default values for cp */
1975         cp->tw = 1;
1976         cp->th = 1;
1977
1978         /* 
1979         copy user encoding parameters 
1980         */
1981         cp->cinema = parameters->cp_cinema;
1982         cp->max_comp_size =     parameters->max_comp_size;
1983         cp->rsiz   = parameters->cp_rsiz;
1984         cp->disto_alloc = parameters->cp_disto_alloc;
1985         cp->fixed_alloc = parameters->cp_fixed_alloc;
1986         cp->fixed_quality = parameters->cp_fixed_quality;
1987
1988         /* mod fixed_quality */
1989         if(parameters->cp_matrice) {
1990                 size_t array_size = parameters->tcp_numlayers * parameters->numresolution * 3 * sizeof(int);
1991                 cp->matrice = (int *) opj_malloc(array_size);
1992                 memcpy(cp->matrice, parameters->cp_matrice, array_size);
1993         }
1994
1995         /* tiles */
1996         cp->tdx = parameters->cp_tdx;
1997         cp->tdy = parameters->cp_tdy;
1998
1999         /* tile offset */
2000         cp->tx0 = parameters->cp_tx0;
2001         cp->ty0 = parameters->cp_ty0;
2002
2003         /* comment string */
2004         if(parameters->cp_comment) {
2005                 cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1);
2006                 if(cp->comment) {
2007                         strcpy(cp->comment, parameters->cp_comment);
2008                 }
2009         }
2010
2011         /*
2012         calculate other encoding parameters
2013         */
2014
2015         if (parameters->tile_size_on) {
2016                 cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx);
2017                 cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy);
2018         } else {
2019                 cp->tdx = image->x1 - cp->tx0;
2020                 cp->tdy = image->y1 - cp->ty0;
2021         }
2022
2023         if(parameters->tp_on){
2024                 cp->tp_flag = parameters->tp_flag;
2025                 cp->tp_on = 1;
2026         }
2027         
2028         cp->img_size = 0;
2029         for(i=0;i<image->numcomps ;i++){
2030         cp->img_size += (image->comps[i].w *image->comps[i].h * image->comps[i].prec);
2031         }
2032
2033
2034 #ifdef USE_JPWL
2035         /*
2036         calculate JPWL encoding parameters
2037         */
2038
2039         if (parameters->jpwl_epc_on) {
2040                 int i;
2041
2042                 /* set JPWL on */
2043                 cp->epc_on = OPJ_TRUE;
2044                 cp->info_on = OPJ_FALSE; /* no informative technique */
2045
2046                 /* set EPB on */
2047                 if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) {
2048                         cp->epb_on = OPJ_TRUE;
2049                         
2050                         cp->hprot_MH = parameters->jpwl_hprot_MH;
2051                         for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
2052                                 cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i];
2053                                 cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i];
2054                         }
2055                         /* if tile specs are not specified, copy MH specs */
2056                         if (cp->hprot_TPH[0] == -1) {
2057                                 cp->hprot_TPH_tileno[0] = 0;
2058                                 cp->hprot_TPH[0] = parameters->jpwl_hprot_MH;
2059                         }
2060                         for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) {
2061                                 cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i];
2062                                 cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i];
2063                                 cp->pprot[i] = parameters->jpwl_pprot[i];
2064                         }
2065                 }
2066
2067                 /* set ESD writing */
2068                 if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) {
2069                         cp->esd_on = OPJ_TRUE;
2070
2071                         cp->sens_size = parameters->jpwl_sens_size;
2072                         cp->sens_addr = parameters->jpwl_sens_addr;
2073                         cp->sens_range = parameters->jpwl_sens_range;
2074
2075                         cp->sens_MH = parameters->jpwl_sens_MH;
2076                         for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
2077                                 cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i];
2078                                 cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i];
2079                         }
2080                 }
2081
2082                 /* always set RED writing to false: we are at the encoder */
2083                 cp->red_on = OPJ_FALSE;
2084
2085         } else {
2086                 cp->epc_on = OPJ_FALSE;
2087         }
2088 #endif /* USE_JPWL */
2089
2090
2091         /* initialize the mutiple tiles */
2092         /* ---------------------------- */
2093         cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
2094
2095         for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
2096                 opj_tcp_t *tcp = &cp->tcps[tileno];
2097                 tcp->numlayers = parameters->tcp_numlayers;
2098                 for (j = 0; j < tcp->numlayers; j++) {
2099                         if(cp->cinema){
2100                                 if (cp->fixed_quality) {
2101                                         tcp->distoratio[j] = parameters->tcp_distoratio[j];
2102                                 }
2103                                 tcp->rates[j] = parameters->tcp_rates[j];
2104                         }else{
2105                                 if (cp->fixed_quality) {        /* add fixed_quality */
2106                                         tcp->distoratio[j] = parameters->tcp_distoratio[j];
2107                                 } else {
2108                                         tcp->rates[j] = parameters->tcp_rates[j];
2109                                 }
2110                         }
2111                 }
2112                 tcp->csty = parameters->csty;
2113                 tcp->prg = parameters->prog_order;
2114                 tcp->mct = parameters->tcp_mct; 
2115
2116                 numpocs_tile = 0;
2117                 tcp->POC = 0;
2118                 if (parameters->numpocs) {
2119                         /* initialisation of POC */
2120                         tcp->POC = 1;
2121                         for (i = 0; i < parameters->numpocs; i++) {
2122                                 if((tileno == parameters->POC[i].tile - 1) || (parameters->POC[i].tile == -1)) {
2123                                         opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];
2124                                         tcp_poc->resno0         = parameters->POC[numpocs_tile].resno0;
2125                                         tcp_poc->compno0        = parameters->POC[numpocs_tile].compno0;
2126                                         tcp_poc->layno1         = parameters->POC[numpocs_tile].layno1;
2127                                         tcp_poc->resno1         = parameters->POC[numpocs_tile].resno1;
2128                                         tcp_poc->compno1        = parameters->POC[numpocs_tile].compno1;
2129                                         tcp_poc->prg1           = parameters->POC[numpocs_tile].prg1;
2130                                         tcp_poc->tile           = parameters->POC[numpocs_tile].tile;
2131                                         numpocs_tile++;
2132                                 }
2133                         }
2134                         tcp->numpocs = numpocs_tile -1 ;
2135                 }else{ 
2136                         tcp->numpocs = 0;
2137                 }
2138
2139                 tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
2140
2141                 for (i = 0; i < image->numcomps; i++) {
2142                         opj_tccp_t *tccp = &tcp->tccps[i];
2143                         tccp->csty = parameters->csty & 0x01;   /* 0 => one precinct || 1 => custom precinct  */
2144                         tccp->numresolutions = parameters->numresolution;
2145                         tccp->cblkw = int_floorlog2(parameters->cblockw_init);
2146                         tccp->cblkh = int_floorlog2(parameters->cblockh_init);
2147                         tccp->cblksty = parameters->mode;
2148                         tccp->qmfbid = parameters->irreversible ? 0 : 1;
2149                         tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT : J2K_CCP_QNTSTY_NOQNT;
2150                         tccp->numgbits = 2;
2151                         if (i == parameters->roi_compno) {
2152                                 tccp->roishift = parameters->roi_shift;
2153                         } else {
2154                                 tccp->roishift = 0;
2155                         }
2156
2157                         if(parameters->cp_cinema)
2158                         {
2159                                 //Precinct size for lowest frequency subband=128
2160                                 tccp->prcw[0] = 7;
2161                                 tccp->prch[0] = 7;
2162                                 //Precinct size at all other resolutions = 256
2163                                 for (j = 1; j < tccp->numresolutions; j++) {
2164                                         tccp->prcw[j] = 8;
2165                                         tccp->prch[j] = 8;
2166                                 }
2167                         }else{
2168                                 if (parameters->csty & J2K_CCP_CSTY_PRT) {
2169                                         int p = 0;
2170                                         for (j = tccp->numresolutions - 1; j >= 0; j--) {
2171                                                 if (p < parameters->res_spec) {
2172                                                         
2173                                                         if (parameters->prcw_init[p] < 1) {
2174                                                                 tccp->prcw[j] = 1;
2175                                                         } else {
2176                                                                 tccp->prcw[j] = int_floorlog2(parameters->prcw_init[p]);
2177                                                         }
2178                                                         
2179                                                         if (parameters->prch_init[p] < 1) {
2180                                                                 tccp->prch[j] = 1;
2181                                                         }else {
2182                                                                 tccp->prch[j] = int_floorlog2(parameters->prch_init[p]);
2183                                                         }
2184
2185                                                 } else {
2186                                                         int res_spec = parameters->res_spec;
2187                                                         int size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1));
2188                                                         int size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1));
2189                                                         
2190                                                         if (size_prcw < 1) {
2191                                                                 tccp->prcw[j] = 1;
2192                                                         } else {
2193                                                                 tccp->prcw[j] = int_floorlog2(size_prcw);
2194                                                         }
2195                                                         
2196                                                         if (size_prch < 1) {
2197                                                                 tccp->prch[j] = 1;
2198                                                         } else {
2199                                                                 tccp->prch[j] = int_floorlog2(size_prch);
2200                                                         }
2201                                                 }
2202                                                 p++;
2203                                                 /*printf("\nsize precinct for level %d : %d,%d\n", j,tccp->prcw[j], tccp->prch[j]); */
2204                                         }       //end for
2205                                 } else {
2206                                         for (j = 0; j < tccp->numresolutions; j++) {
2207                                                 tccp->prcw[j] = 15;
2208                                                 tccp->prch[j] = 15;
2209                                         }
2210                                 }
2211                         }
2212
2213                         dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec);
2214                 }
2215         }
2216 }
2217
2218 opj_bool j2k_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
2219         int tileno, compno;
2220         opj_cp_t *cp = NULL;
2221
2222         opj_tcd_t *tcd = NULL;  /* TCD component */
2223
2224         j2k->cio = cio; 
2225         j2k->image = image;
2226
2227         cp = j2k->cp;
2228
2229         /* INDEX >> */
2230         j2k->cstr_info = cstr_info;
2231         if (cstr_info) {
2232                 int compno;
2233                 cstr_info->tile = (opj_tile_info_t *) opj_malloc(cp->tw * cp->th * sizeof(opj_tile_info_t));
2234                 cstr_info->image_w = image->x1 - image->x0;
2235                 cstr_info->image_h = image->y1 - image->y0;
2236                 cstr_info->prog = (&cp->tcps[0])->prg;
2237                 cstr_info->tw = cp->tw;
2238                 cstr_info->th = cp->th;
2239                 cstr_info->tile_x = cp->tdx;    /* new version parser */
2240                 cstr_info->tile_y = cp->tdy;    /* new version parser */
2241                 cstr_info->tile_Ox = cp->tx0;   /* new version parser */
2242                 cstr_info->tile_Oy = cp->ty0;   /* new version parser */
2243                 cstr_info->numcomps = image->numcomps;
2244                 cstr_info->numlayers = (&cp->tcps[0])->numlayers;
2245                 cstr_info->numdecompos = (int*) opj_malloc(image->numcomps * sizeof(int));
2246                 for (compno=0; compno < image->numcomps; compno++) {
2247                         cstr_info->numdecompos[compno] = (&cp->tcps[0])->tccps->numresolutions - 1;
2248                 }
2249                 cstr_info->D_max = 0.0;         /* ADD Marcela */
2250                 cstr_info->main_head_start = cio_tell(cio); /* position of SOC */
2251                 cstr_info->maxmarknum = 100;
2252                 cstr_info->marker = (opj_marker_info_t *) opj_malloc(cstr_info->maxmarknum * sizeof(opj_marker_info_t));
2253                 cstr_info->marknum = 0;
2254         }
2255         /* << INDEX */
2256
2257         j2k_write_soc(j2k);
2258         j2k_write_siz(j2k);
2259         j2k_write_cod(j2k);
2260         j2k_write_qcd(j2k);
2261
2262         if(cp->cinema){
2263                 for (compno = 1; compno < image->numcomps; compno++) {
2264                         j2k_write_coc(j2k, compno);
2265                         j2k_write_qcc(j2k, compno);
2266                 }
2267         }
2268
2269         for (compno = 0; compno < image->numcomps; compno++) {
2270                 opj_tcp_t *tcp = &cp->tcps[0];
2271                 if (tcp->tccps[compno].roishift)
2272                         j2k_write_rgn(j2k, compno, 0);
2273         }
2274         if (cp->comment != NULL) {
2275                 j2k_write_com(j2k);
2276         }
2277
2278         j2k->totnum_tp = j2k_calculate_tp(cp,image->numcomps,image,j2k);
2279         /* TLM Marker*/
2280         if(cp->cinema){
2281                 j2k_write_tlm(j2k);
2282                 if (cp->cinema == CINEMA4K_24) {
2283                         j2k_write_poc(j2k);
2284                 }
2285         }
2286
2287         /* uncomment only for testing JPSEC marker writing */
2288         /* j2k_write_sec(j2k); */
2289
2290         /* INDEX >> */
2291         if(cstr_info) {
2292                 cstr_info->main_head_end = cio_tell(cio) - 1;
2293         }
2294         /* << INDEX */
2295         /**** Main Header ENDS here ***/
2296
2297         /* create the tile encoder */
2298         tcd = tcd_create(j2k->cinfo);
2299
2300         /* encode each tile */
2301         for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
2302                 int pino;
2303                 int tilepartno=0;
2304                 /* UniPG>> */
2305                 int acc_pack_num = 0;
2306                 /* <<UniPG */
2307
2308
2309                 opj_tcp_t *tcp = &cp->tcps[tileno];
2310                 opj_event_msg(j2k->cinfo, EVT_INFO, "tile number %d / %d\n", tileno + 1, cp->tw * cp->th);
2311
2312                 j2k->curtileno = tileno;
2313                 j2k->cur_tp_num = 0;
2314                 tcd->cur_totnum_tp = j2k->cur_totnum_tp[j2k->curtileno];
2315                 /* initialisation before tile encoding  */
2316                 if (tileno == 0) {
2317                         tcd_malloc_encode(tcd, image, cp, j2k->curtileno);
2318                 } else {
2319                         tcd_init_encode(tcd, image, cp, j2k->curtileno);
2320                 }
2321
2322                 /* INDEX >> */
2323                 if(cstr_info) {
2324                         cstr_info->tile[j2k->curtileno].start_pos = cio_tell(cio) + j2k->pos_correction;
2325                 }
2326                 /* << INDEX */
2327
2328                 for(pino = 0; pino <= tcp->numpocs; pino++) {
2329                         int tot_num_tp;
2330                         tcd->cur_pino=pino;
2331
2332                         /*Get number of tile parts*/
2333                         tot_num_tp = j2k_get_num_tp(cp,pino,tileno);
2334                         tcd->tp_pos = cp->tp_pos;
2335
2336                         for(tilepartno = 0; tilepartno < tot_num_tp ; tilepartno++){
2337                                 j2k->tp_num = tilepartno;
2338                                 /* INDEX >> */
2339                                 if(cstr_info)
2340                                         cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_start_pos =
2341                                         cio_tell(cio) + j2k->pos_correction;
2342                                 /* << INDEX */
2343                                 j2k_write_sot(j2k);
2344
2345                                 if(j2k->cur_tp_num == 0 && cp->cinema == 0){
2346                                         for (compno = 1; compno < image->numcomps; compno++) {
2347                                                 j2k_write_coc(j2k, compno);
2348                                                 j2k_write_qcc(j2k, compno);
2349                                         }
2350                                         if (cp->tcps[tileno].numpocs) {
2351                                                 j2k_write_poc(j2k);
2352                                         }
2353                                 }
2354
2355                                 /* INDEX >> */
2356                                 if(cstr_info)
2357                                         cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_header =
2358                                         cio_tell(cio) + j2k->pos_correction + 1;
2359                                 /* << INDEX */
2360
2361                                 j2k_write_sod(j2k, tcd);
2362
2363                                 /* INDEX >> */
2364                                 if(cstr_info) {
2365                                         cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_pos =
2366                                                 cio_tell(cio) + j2k->pos_correction - 1;
2367                                         cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_start_pack =
2368                                                 acc_pack_num;
2369                                         cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_numpacks =
2370                                                 cstr_info->packno - acc_pack_num;
2371                                         acc_pack_num = cstr_info->packno;
2372                                 }
2373                                 /* << INDEX */
2374
2375                                 j2k->cur_tp_num++;
2376                         }                       
2377                 }
2378                 if(cstr_info) {
2379                         cstr_info->tile[j2k->curtileno].end_pos = cio_tell(cio) + j2k->pos_correction - 1;
2380                 }
2381
2382
2383                 /*
2384                 if (tile->PPT) { // BAD PPT !!! 
2385                 FILE *PPT_file;
2386                 int i;
2387                 PPT_file=fopen("PPT","rb");
2388                 fprintf(stderr,"%c%c%c%c",255,97,tile->len_ppt/256,tile->len_ppt%256);
2389                 for (i=0;i<tile->len_ppt;i++) {
2390                 unsigned char elmt;
2391                 fread(&elmt, 1, 1, PPT_file);
2392                 fwrite(&elmt,1,1,f);
2393                 }
2394                 fclose(PPT_file);
2395                 unlink("PPT");
2396                 }
2397                 */
2398
2399         }
2400
2401         /* destroy the tile encoder */
2402         tcd_free_encode(tcd);
2403         tcd_destroy(tcd);
2404
2405         opj_free(j2k->cur_totnum_tp);
2406
2407         j2k_write_eoc(j2k);
2408
2409         if(cstr_info) {
2410                 cstr_info->codestream_size = cio_tell(cio) + j2k->pos_correction;
2411                 /* UniPG>> */
2412                 /* The following adjustment is done to adjust the codestream size */
2413                 /* if SOD is not at 0 in the buffer. Useful in case of JP2, where */
2414                 /* the first bunch of bytes is not in the codestream              */
2415                 cstr_info->codestream_size -= cstr_info->main_head_start;
2416                 /* <<UniPG */
2417         }
2418
2419 #ifdef USE_JPWL
2420         /*
2421         preparation of JPWL marker segments
2422         */
2423         if(cp->epc_on) {
2424
2425                 /* encode according to JPWL */
2426                 jpwl_encode(j2k, cio, image);
2427
2428         }
2429 #endif /* USE_JPWL */
2430
2431         return OPJ_TRUE;
2432 }
2433
2434
2435
2436
2437
2438