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