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