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