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