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