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