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