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