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