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