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