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