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