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