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