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