Fix leak & invalid behavior of opj_jp2_read_ihdr (#818)
[openjpeg.git] / src / lib / openjpwl / jpwl_lib.c
1 /*
2  * The copyright in this software is being made available under the 2-clauses 
3  * BSD License, included below. This software may be subject to other third 
4  * party and contributor rights, including patent rights, and no such rights
5  * are granted under this license.
6  *
7  * Copyright (c) 2001-2003, David Janssens
8  * Copyright (c) 2002-2003, Yannick Verschueren
9  * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
10  * Copyright (c) 2005, Herve Drolon, FreeImage Team
11  * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
12  * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy
13  * All rights reserved.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
25  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
28  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  */
36
37 #ifdef USE_JPWL
38
39 #include "opj_includes.h"
40 #include <limits.h>
41
42 /** Minimum and maximum values for the double->pfp conversion */
43 #define MIN_V1 0.0
44 #define MAX_V1 17293822569102704640.0
45 #define MIN_V2 0.000030517578125
46 #define MAX_V2 131040.0
47
48 /** conversion between a double precision floating point
49 number and the corresponding pseudo-floating point used 
50 to represent sensitivity values
51 @param V the double precision value
52 @param bytes the number of bytes of the representation
53 @return the pseudo-floating point value (cast accordingly)
54 */
55 unsigned short int jpwl_double_to_pfp(double V, int bytes);
56
57 /** conversion between a pseudo-floating point used 
58 to represent sensitivity values and the corresponding
59 double precision floating point number  
60 @param em the pseudo-floating point value (cast accordingly)
61 @param bytes the number of bytes of the representation
62 @return the double precision value
63 */
64 double jpwl_pfp_to_double(unsigned short int em, int bytes);
65
66         /*-------------------------------------------------------------*/
67
68 int jpwl_markcomp(const void *arg1, const void *arg2)
69 {
70    /* Compare the two markers' positions */
71    double diff = (((jpwl_marker_t *) arg1)->dpos - ((jpwl_marker_t *) arg2)->dpos);
72
73    if (diff == 0.0)
74            return (0);
75    else if (diff < 0)
76            return (-1);
77    else
78            return (+1);
79 }
80
81 int jpwl_epbs_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num,
82                                   opj_bool latest, opj_bool packed, opj_bool insideMH, int *idx, int hprot,
83                                   double place_pos, int tileno,
84                                   unsigned long int pre_len, unsigned long int post_len) {
85
86         jpwl_epb_ms_t *epb_mark = NULL;
87
88         int k_pre, k_post, n_pre, n_post;
89         
90         unsigned long int L1, L2, dL4, max_postlen, epbs_len = 0;
91
92         /* We find RS(n,k) for EPB parms and pre-data, if any */
93         if (insideMH && (*idx == 0)) {
94                 /* First EPB in MH */ 
95                 k_pre = 64;
96                 n_pre = 160;
97         } else if (!insideMH && (*idx == 0)) {
98                 /* First EPB in TH */
99                 k_pre = 25;
100                 n_pre = 80;
101         } else {
102                 /* Following EPBs in MH or TH */
103                 k_pre = 13;
104                 n_pre = 40;
105         };
106
107         /* Find lengths, Figs. B3 and B4 */
108         /* size of pre data: pre_buf(pre_len) + EPB(2) + Lepb(2) + Depb(1) + LDPepb(4) + Pepb(4) */
109         L1 = pre_len + 13;
110
111         /* size of pre-data redundancy */
112         /*   (redundancy per codeword)       *     (number of codewords, rounded up)   */
113         L2 = (n_pre - k_pre) * (unsigned long int) ceil((double) L1 / (double) k_pre);
114
115         /* Find protection type for post data and its associated redundancy field length*/
116         if ((hprot == 16) || (hprot == 32)) {
117                 /* there is a CRC for post-data */
118                 k_post = post_len;
119                 n_post = post_len + (hprot >> 3);
120                 /*L3 = hprot >> 3;*/ /* 2 (CRC-16) or 4 (CRC-32) bytes */
121
122         } else if ((hprot >= 37) && (hprot <= 128)) {
123                 /* there is a RS for post-data */
124                 k_post = 32;
125                 n_post = hprot;
126
127         } else {
128                 /* Use predefined codes */
129                 n_post = n_pre;
130                 k_post = k_pre;
131         };
132
133         /* Create the EPB(s) */
134         while (post_len > 0) {
135
136                 /* maximum postlen in order to respect EPB size
137                 (we use JPWL_MAXIMUM_EPB_ROOM instead of 65535 for keeping room for EPB parms)*/
138                 /*      (message word size)    *            (number of containable parity words)  */
139                 max_postlen = k_post * (unsigned long int) floor((double) JPWL_MAXIMUM_EPB_ROOM / (double) (n_post - k_post));
140
141                 /* maximum postlen in order to respect EPB size */
142                 if (*idx == 0)
143                         /* (we use (JPWL_MAXIMUM_EPB_ROOM - L2) instead of 65535 for keeping room for EPB parms + pre-data) */
144                         /*      (message word size)    *                   (number of containable parity words)  */
145                         max_postlen = k_post * (unsigned long int) floor((double) (JPWL_MAXIMUM_EPB_ROOM - L2) / (double) (n_post - k_post));
146
147                 else
148                         /* (we use JPWL_MAXIMUM_EPB_ROOM instead of 65535 for keeping room for EPB parms) */
149                         /*      (message word size)    *            (number of containable parity words)  */
150                         max_postlen = k_post * (unsigned long int) floor((double) JPWL_MAXIMUM_EPB_ROOM / (double) (n_post - k_post));
151
152                 /* null protection case */
153                 /* the max post length can be as large as the LDPepb field can host */
154                 if (hprot == 0)
155                         max_postlen = INT_MAX;
156                 
157                 /* length to use */
158                 dL4 = min(max_postlen, post_len);
159
160                 if ((epb_mark = jpwl_epb_create(
161                         j2k, /* this encoder handle */
162                         latest ? (dL4 < max_postlen) : OPJ_FALSE, /* is it the latest? */
163                         packed, /* is it packed? */
164                         tileno, /* we are in TPH */
165                         *idx, /* its index */
166                         hprot, /* protection type parameters of following data */
167                         0, /* pre-data: nothing for now */
168                         dL4 /* post-data: the stub computed previously */
169                         ))) {
170                         
171                         /* Add this marker to the 'insertanda' list */
172                         if (*jwmarker_num < JPWL_MAX_NO_MARKERS) {
173                                 jwmarker[*jwmarker_num].id = J2K_MS_EPB; /* its type */
174                                 jwmarker[*jwmarker_num].m.epbmark = epb_mark; /* the EPB */
175                                 jwmarker[*jwmarker_num].pos = (int) place_pos; /* after SOT */
176                                 jwmarker[*jwmarker_num].dpos = place_pos + 0.0000001 * (double)(*idx); /* not very first! */
177                                 jwmarker[*jwmarker_num].len = epb_mark->Lepb; /* its length */
178                                 jwmarker[*jwmarker_num].len_ready = OPJ_TRUE; /* ready */
179                                 jwmarker[*jwmarker_num].pos_ready = OPJ_TRUE; /* ready */
180                                 jwmarker[*jwmarker_num].parms_ready = OPJ_TRUE; /* ready */
181                                 jwmarker[*jwmarker_num].data_ready = OPJ_FALSE; /* not ready */
182                                 (*jwmarker_num)++;
183                         }
184
185                         /* increment epb index */
186                         (*idx)++;
187
188                         /* decrease postlen */
189                         post_len -= dL4;
190
191                         /* increase the total length of EPBs */
192                         epbs_len += epb_mark->Lepb + 2;
193
194                 } else {
195                         /* ooops, problems */
196                         opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH EPB for UEP in tile %d\n", tileno);                          
197                 };
198         }
199
200         return epbs_len;
201 }
202
203
204 jpwl_epb_ms_t *jpwl_epb_create(opj_j2k_t *j2k, opj_bool latest, opj_bool packed, int tileno, int idx, int hprot,
205                                                   unsigned long int pre_len, unsigned long int post_len) {
206
207         jpwl_epb_ms_t *epb = NULL;
208         /*unsigned short int data_len = 0;*/
209         unsigned short int L2, L3;
210         unsigned long int L1, L4;
211         /*unsigned char *predata_in = NULL;*/
212
213         opj_bool insideMH = (tileno == -1);
214
215         /* Alloc space */
216         if (!(epb = (jpwl_epb_ms_t *) opj_malloc((size_t) 1 * sizeof (jpwl_epb_ms_t)))) {
217                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for one EPB MS\n");
218                 return NULL;
219         };
220
221         /* We set RS(n,k) for EPB parms and pre-data, if any */
222         if (insideMH && (idx == 0)) {
223                 /* First EPB in MH */ 
224                 epb->k_pre = 64;
225                 epb->n_pre = 160;
226         } else if (!insideMH && (idx == 0)) {
227                 /* First EPB in TH */
228                 epb->k_pre = 25;
229                 epb->n_pre = 80;
230         } else {
231                 /* Following EPBs in MH or TH */
232                 epb->k_pre = 13;
233                 epb->n_pre = 40;
234         };
235
236         /* Find lengths, Figs. B3 and B4 */
237         /* size of pre data: pre_buf(pre_len) + EPB(2) + Lepb(2) + Depb(1) + LDPepb(4) + Pepb(4) */
238         L1 = pre_len + 13;
239         epb->pre_len = pre_len;
240
241         /* size of pre-data redundancy */
242         /*   (redundancy per codeword)       *               (number of codewords, rounded up)   */
243         L2 = (epb->n_pre - epb->k_pre) * (unsigned short int) ceil((double) L1 / (double) epb->k_pre);
244
245         /* length of post-data */
246         L4 = post_len;
247         epb->post_len = post_len;
248
249         /* Find protection type for post data and its associated redundancy field length*/
250         if ((hprot == 16) || (hprot == 32)) {
251                 /* there is a CRC for post-data */
252                 epb->Pepb = 0x10000000 | ((unsigned long int) hprot >> 5); /* 0=CRC-16, 1=CRC-32 */
253                 epb->k_post = post_len;
254                 epb->n_post = post_len + (hprot >> 3);
255                 /*L3 = hprot >> 3;*/ /* 2 (CRC-16) or 4 (CRC-32) bytes */
256
257         } else if ((hprot >= 37) && (hprot <= 128)) {
258                 /* there is a RS for post-data */
259                 epb->Pepb = 0x20000020 | (((unsigned long int) hprot & 0x000000FF) << 8);
260                 epb->k_post = 32;
261                 epb->n_post = hprot;
262
263         } else if (hprot == 1) {
264                 /* Use predefined codes */
265                 epb->Pepb = (unsigned long int) 0x00000000;
266                 epb->n_post = epb->n_pre;
267                 epb->k_post = epb->k_pre;
268         
269         } else if (hprot == 0) {
270                 /* Placeholder EPB: only protects its parameters, no protection method */
271                 epb->Pepb = (unsigned long int) 0xFFFFFFFF;
272                 epb->n_post = 1;
273                 epb->k_post = 1;
274         
275         } else {
276                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Invalid protection value for EPB h = %d\n", hprot);                               
277                 return NULL;
278         }
279
280         epb->hprot = hprot;
281
282         /*   (redundancy per codeword)          *                (number of codewords, rounded up) */
283         L3 = (epb->n_post - epb->k_post) * (unsigned short int) ceil((double) L4 / (double) epb->k_post);
284
285         /* private fields */
286         epb->tileno = tileno;
287
288         /* Fill some fields of the EPB */
289
290         /* total length of the EPB MS (less the EPB marker itself): */
291         /* Lepb(2) + Depb(1) + LDPepb(4) + Pepb(4) + pre_redundancy + post-redundancy */
292         epb->Lepb = 11 + L2 + L3;
293
294         /* EPB style */
295         epb->Depb = ((packed & 0x0001) << 7) | ((latest & 0x0001) << 6) | (idx & 0x003F);
296
297         /* length of data protected by EPB: */
298         epb->LDPepb = L1 + L4;
299
300         return epb;
301 }
302
303 void jpwl_epb_write(opj_j2k_t *j2k, jpwl_epb_ms_t *epb, unsigned char *buf) {
304
305         /* Marker */
306         *(buf++) = (unsigned char) (J2K_MS_EPB >> 8); 
307         *(buf++) = (unsigned char) (J2K_MS_EPB >> 0); 
308
309         /* Lepb */
310         *(buf++) = (unsigned char) (epb->Lepb >> 8); 
311         *(buf++) = (unsigned char) (epb->Lepb >> 0); 
312
313         /* Depb */
314         *(buf++) = (unsigned char) (epb->Depb >> 0); 
315
316         /* LDPepb */
317         *(buf++) = (unsigned char) (epb->LDPepb >> 24); 
318         *(buf++) = (unsigned char) (epb->LDPepb >> 16); 
319         *(buf++) = (unsigned char) (epb->LDPepb >> 8); 
320         *(buf++) = (unsigned char) (epb->LDPepb >> 0); 
321
322         /* Pepb */
323         *(buf++) = (unsigned char) (epb->Pepb >> 24); 
324         *(buf++) = (unsigned char) (epb->Pepb >> 16); 
325         *(buf++) = (unsigned char) (epb->Pepb >> 8); 
326         *(buf++) = (unsigned char) (epb->Pepb >> 0); 
327
328         /* Data */
329         /*memcpy(buf, epb->data, (size_t) epb->Lepb - 11);*/
330         memset(buf, 0, (size_t) epb->Lepb - 11);
331
332         /* update markers struct */
333         j2k_add_marker(j2k->cstr_info, J2K_MS_EPB, -1, epb->Lepb + 2);
334
335 }
336
337
338 jpwl_epc_ms_t *jpwl_epc_create(opj_j2k_t *j2k, opj_bool esd_on, opj_bool red_on, opj_bool epb_on, opj_bool info_on) {
339
340         jpwl_epc_ms_t *epc = NULL;
341
342         /* Alloc space */
343         if (!(epc = (jpwl_epc_ms_t *) opj_malloc((size_t) 1 * sizeof (jpwl_epc_ms_t)))) {
344                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for EPC MS\n");
345                 return NULL;
346         };
347
348         /* Set the EPC parameters */
349         epc->esd_on = esd_on;
350         epc->epb_on = epb_on;
351         epc->red_on = red_on;
352         epc->info_on = info_on;
353
354         /* Fill the EPC fields with default values */
355         epc->Lepc = 9;
356         epc->Pcrc = 0x0000;
357         epc->DL = 0x00000000;
358         epc->Pepc = ((j2k->cp->esd_on & 0x0001) << 4) | ((j2k->cp->red_on & 0x0001) << 5) |
359                 ((j2k->cp->epb_on & 0x0001) << 6) | ((j2k->cp->info_on & 0x0001) << 7);
360
361         return (epc);
362 }
363
364 opj_bool jpwl_epb_fill(opj_j2k_t *j2k, jpwl_epb_ms_t *epb, unsigned char *buf, unsigned char *post_buf) {
365
366         unsigned long int L1, L2, L3, L4;
367         int remaining;
368         unsigned long int P, NN_P;
369
370         /* Operating buffer */
371         static unsigned char codeword[NN], *parityword;
372
373         unsigned char *L1_buf, *L2_buf;
374         /* these ones are static, since we need to keep memory of
375          the exact place from one call to the other */
376         static unsigned char *L3_buf, *L4_buf;
377
378         /* some consistency check */
379         if (!buf) {
380                 opj_event_msg(j2k->cinfo, EVT_ERROR, "There is no operating buffer for EPBs\n");
381                 return OPJ_FALSE;
382         }
383
384         if (!post_buf && !L4_buf) {
385                 opj_event_msg(j2k->cinfo, EVT_ERROR, "There is no operating buffer for EPBs data\n");
386                 return OPJ_FALSE;
387         }
388
389         /*
390          * Compute parity bytes on pre-data, ALWAYS present (at least only for EPB parms)
391          */
392
393         /* Initialize RS structures */
394         P = epb->n_pre - epb->k_pre;
395         NN_P = NN - P;
396         memset(codeword, 0, NN);
397         parityword = codeword + NN_P;
398         init_rs(NN_P);
399
400         /* pre-data begins pre_len bytes before of EPB buf */
401         L1_buf = buf - epb->pre_len;
402         L1 = epb->pre_len + 13;
403
404         /* redundancy for pre-data begins immediately after EPB parms */
405         L2_buf = buf + 13;
406         L2 = (epb->n_pre - epb->k_pre) * (unsigned short int) ceil((double) L1 / (double) epb->k_pre);
407
408         /* post-data
409            the position of L4 buffer can be:
410              1) passed as a parameter: in that case use it
411              2) null: in that case use the previous (static) one
412         */
413         if (post_buf)
414                 L4_buf = post_buf;
415         L4 = epb->post_len;
416
417         /* post-data redundancy begins immediately after pre-data redundancy */
418         L3_buf = L2_buf + L2;
419         L3 = (epb->n_post - epb->k_post) * (unsigned short int) ceil((double) L4 / (double) epb->k_post);
420
421         /* let's check whether EPB length is sufficient to contain all these data */
422         if (epb->Lepb < (11 + L2 + L3))
423                 opj_event_msg(j2k->cinfo, EVT_ERROR, "There is no room in EPB data field for writing redundancy data\n");
424         /*printf("Env. %d, nec. %d (%d + %d)\n", epb->Lepb - 11, L2 + L3, L2, L3);*/
425
426         /* Compute redundancy of pre-data message words */
427         remaining = L1;
428         while (remaining) {
429
430                 /* copy message data into codeword buffer */
431                 if (remaining < epb->k_pre) {
432                         /* the last message word is zero-padded */
433                         memset(codeword, 0, NN);
434                         memcpy(codeword, L1_buf, remaining);
435                         L1_buf += remaining;
436                         remaining = 0;
437
438                 } else {
439                         memcpy(codeword, L1_buf, epb->k_pre);
440                         L1_buf += epb->k_pre;
441                         remaining -= epb->k_pre;
442
443                 }
444
445                 /* Encode the buffer and obtain parity bytes */
446                 if (encode_rs(codeword, parityword))
447                         opj_event_msg(j2k->cinfo, EVT_WARNING,
448                                 "Possible encoding error in codeword @ position #%d\n", (L1_buf - buf) / epb->k_pre);
449
450                 /* copy parity bytes only in redundancy buffer */
451                 memcpy(L2_buf, parityword, P); 
452
453                 /* advance parity buffer */
454                 L2_buf += P;
455         }
456
457         /*
458          * Compute parity bytes on post-data, may be absent if there are no data
459          */
460         /*printf("Hprot is %d (tileno=%d, k_pre=%d, n_pre=%d, k_post=%d, n_post=%d, pre_len=%d, post_len=%d)\n",
461                 epb->hprot, epb->tileno, epb->k_pre, epb->n_pre, epb->k_post, epb->n_post, epb->pre_len,
462                 epb->post_len);*/
463         if (epb->hprot < 0) {
464
465                 /* there should be no EPB */
466                 
467         } else if (epb->hprot == 0) {
468
469                 /* no protection for the data */
470                 /* advance anyway */
471                 L4_buf += epb->post_len;
472
473         } else if (epb->hprot == 16) {
474
475                 /* CRC-16 */
476                 unsigned short int mycrc = 0x0000;
477
478                 /* compute the CRC field (excluding itself) */
479                 remaining = L4;
480                 while (remaining--)
481                         jpwl_updateCRC16(&mycrc, *(L4_buf++));
482
483                 /* write the CRC field */
484                 *(L3_buf++) = (unsigned char) (mycrc >> 8);
485                 *(L3_buf++) = (unsigned char) (mycrc >> 0);
486
487         } else if (epb->hprot == 32) {
488
489                 /* CRC-32 */
490                 unsigned long int mycrc = 0x00000000;
491
492                 /* compute the CRC field (excluding itself) */
493                 remaining = L4;
494                 while (remaining--)
495                         jpwl_updateCRC32(&mycrc, *(L4_buf++));
496
497                 /* write the CRC field */
498                 *(L3_buf++) = (unsigned char) (mycrc >> 24);
499                 *(L3_buf++) = (unsigned char) (mycrc >> 16);
500                 *(L3_buf++) = (unsigned char) (mycrc >> 8);
501                 *(L3_buf++) = (unsigned char) (mycrc >> 0);
502
503         } else {
504
505                 /* RS */
506
507                 /* Initialize RS structures */
508                 P = epb->n_post - epb->k_post;
509                 NN_P = NN - P;
510                 memset(codeword, 0, NN);
511                 parityword = codeword + NN_P;
512                 init_rs(NN_P);
513
514                 /* Compute redundancy of post-data message words */
515                 remaining = L4;
516                 while (remaining) {
517
518                         /* copy message data into codeword buffer */
519                         if (remaining < epb->k_post) {
520                                 /* the last message word is zero-padded */
521                                 memset(codeword, 0, NN);
522                                 memcpy(codeword, L4_buf, remaining);
523                                 L4_buf += remaining;
524                                 remaining = 0;
525
526                         } else {
527                                 memcpy(codeword, L4_buf, epb->k_post);
528                                 L4_buf += epb->k_post;
529                                 remaining -= epb->k_post;
530
531                         }
532
533                         /* Encode the buffer and obtain parity bytes */
534                         if (encode_rs(codeword, parityword))
535                                 opj_event_msg(j2k->cinfo, EVT_WARNING,
536                                         "Possible encoding error in codeword @ position #%d\n", (L4_buf - buf) / epb->k_post);
537
538                         /* copy parity bytes only in redundancy buffer */
539                         memcpy(L3_buf, parityword, P); 
540
541                         /* advance parity buffer */
542                         L3_buf += P;
543                 }
544
545         }
546
547         return OPJ_TRUE;
548 }
549
550
551 opj_bool jpwl_correct(opj_j2k_t *j2k) {
552
553         opj_cio_t *cio = j2k->cio;
554         opj_bool status;
555         static opj_bool mh_done = OPJ_FALSE;
556         int mark_pos, id, len, skips, sot_pos;
557         unsigned long int Psot = 0;
558
559         /* go back to marker position */
560         mark_pos = cio_tell(cio) - 2;
561         cio_seek(cio, mark_pos);
562
563         if ((j2k->state == J2K_STATE_MHSOC) && !mh_done) {
564
565                 int mark_val = 0, skipnum = 0;
566
567                 /*
568                   COLOR IMAGE
569                   first thing to do, if we are here, is to look whether
570                   51 (skipnum) positions ahead there is an EPB, in case of MH
571                 */
572                 /*
573                   B/W IMAGE
574                   first thing to do, if we are here, is to look whether
575                   45 (skipnum) positions ahead there is an EPB, in case of MH
576                 */
577                 /*       SIZ   SIZ_FIELDS     SIZ_COMPS               FOLLOWING_MARKER */
578                 skipnum = 2  +     38     + 3 * j2k->cp->exp_comps  +         2;
579                 if ((cio->bp + skipnum) < cio->end) {
580
581                         cio_skip(cio, skipnum);
582
583                         /* check that you are not going beyond the end of codestream */
584
585                         /* call EPB corrector */
586                         status = jpwl_epb_correct(j2k,     /* J2K decompressor handle */
587                                                                           cio->bp, /* pointer to EPB in codestream buffer */
588                                                                           0,       /* EPB type: MH */
589                                                                           skipnum,      /* length of pre-data */
590                                                                           -1,      /* length of post-data: -1 means auto */
591                                                                           NULL,
592                                                                           NULL
593                                                                          );
594
595                         /* read the marker value */
596                         mark_val = (*(cio->bp) << 8) | *(cio->bp + 1);
597
598                         if (status && (mark_val == J2K_MS_EPB)) {
599                                 /* we found it! */
600                                 mh_done = OPJ_TRUE;
601                                 return OPJ_TRUE;
602                         }
603
604                         /* Disable correction in case of missing or bad head EPB */
605                         /* We can't do better! */
606                         /* PATCHED: 2008-01-25 */
607                         /* MOVED UP: 2008-02-01 */
608                         if (!status) {
609                                 j2k->cp->correct = OPJ_FALSE;
610                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "Couldn't find the MH EPB: disabling JPWL\n");
611                         }
612
613                 }
614
615         }
616
617         if (OPJ_TRUE /*(j2k->state == J2K_STATE_TPHSOT) || (j2k->state == J2K_STATE_TPH)*/) {
618                 /* else, look if 12 positions ahead there is an EPB, in case of TPH */
619                 cio_seek(cio, mark_pos);
620                 if ((cio->bp + 12) < cio->end) {
621
622                         cio_skip(cio, 12);
623
624                         /* call EPB corrector */
625                         status = jpwl_epb_correct(j2k,     /* J2K decompressor handle */
626                                                                           cio->bp, /* pointer to EPB in codestream buffer */
627                                                                           1,       /* EPB type: TPH */
628                                                                           12,      /* length of pre-data */
629                                                                           -1,      /* length of post-data: -1 means auto */
630                                                                           NULL,
631                                                                           NULL
632                                                                          );
633                         if (status)
634                                 /* we found it! */
635                                 return OPJ_TRUE;
636                 }
637         }
638
639         return OPJ_FALSE;
640
641         /* for now, don't use this code */
642
643         /* else, look if here is an EPB, in case of other */
644         if (mark_pos > 64) {
645                 /* it cannot stay before the first MH EPB */
646                 cio_seek(cio, mark_pos);
647                 cio_skip(cio, 0);
648
649                 /* call EPB corrector */
650                 status = jpwl_epb_correct(j2k,     /* J2K decompressor handle */
651                                                                   cio->bp, /* pointer to EPB in codestream buffer */
652                                                                   2,       /* EPB type: TPH */
653                                                                   0,       /* length of pre-data */
654                                                                   -1,      /* length of post-data: -1 means auto */
655                                                                   NULL,
656                                                                   NULL
657                                                                  );
658                 if (status)
659                         /* we found it! */
660                         return OPJ_TRUE;
661         }
662
663         /* nope, no EPBs probably, or they are so damaged that we can give up */
664         return OPJ_FALSE;
665         
666         return OPJ_TRUE;
667
668         /* AN ATTEMPT OF PARSER */
669         /* NOT USED ACTUALLY    */
670
671         /* go to the beginning of the file */
672         cio_seek(cio, 0);
673
674         /* let's begin */
675         j2k->state = J2K_STATE_MHSOC;
676
677         /* cycle all over the markers */
678         while (cio_tell(cio) < cio->length) {
679
680                 /* read the marker */
681                 mark_pos = cio_tell(cio);
682                 id = cio_read(cio, 2);
683
684                 /* details */
685                 printf("Marker@%d: %X\n", cio_tell(cio) - 2, id);
686
687                 /* do an action in response to the read marker */
688                 switch (id) {
689
690                 /* short markers */
691
692                         /* SOC */
693                 case J2K_MS_SOC:
694                         j2k->state = J2K_STATE_MHSIZ;
695                         len = 0;
696                         skips = 0;
697                         break;
698
699                         /* EOC */
700                 case J2K_MS_EOC:
701                         j2k->state = J2K_STATE_MT;
702                         len = 0;
703                         skips = 0;
704                         break;
705
706                         /* particular case of SOD */
707                 case J2K_MS_SOD:
708                         len = Psot - (mark_pos - sot_pos) - 2;
709                         skips = len;
710                         break;
711
712                 /* long markers */
713
714                         /* SOT */
715                 case J2K_MS_SOT:
716                         j2k->state = J2K_STATE_TPH;
717                         sot_pos = mark_pos; /* position of SOT */
718                         len = cio_read(cio, 2); /* read the length field */
719                         cio_skip(cio, 2); /* this field is unnecessary */
720                         Psot = cio_read(cio, 4); /* tile length */
721                         skips = len - 8;
722                         break;
723
724                         /* remaining */
725                 case J2K_MS_SIZ:
726                         j2k->state = J2K_STATE_MH;
727                         /* read the length field */
728                         len = cio_read(cio, 2);
729                         skips = len - 2;
730                         break;
731
732                         /* remaining */
733                 default:
734                         /* read the length field */
735                         len = cio_read(cio, 2);
736                         skips = len - 2;
737                         break;
738
739                 }
740
741                 /* skip to marker's end */
742                 cio_skip(cio, skips);   
743
744         }
745
746
747 }
748
749 opj_bool jpwl_epb_correct(opj_j2k_t *j2k, unsigned char *buffer, int type, int pre_len, int post_len, int *conn,
750                                           unsigned char **L4_bufp) {
751
752         /* Operating buffer */
753         unsigned char codeword[NN], *parityword;
754
755         unsigned long int P, NN_P;
756         unsigned long int L1, L4;
757         int remaining, n_pre, k_pre, n_post, k_post;
758
759         int status, tt;
760
761         int orig_pos = cio_tell(j2k->cio);
762
763         unsigned char *L1_buf, *L2_buf;
764         unsigned char *L3_buf, *L4_buf;
765
766         unsigned long int LDPepb, Pepb;
767         unsigned short int Lepb;
768         unsigned char Depb;
769         char str1[25] = "";
770         int myconn, errnum = 0;
771         opj_bool errflag = OPJ_FALSE;
772         
773         opj_cio_t *cio = j2k->cio;
774
775         /* check for common errors */
776         if (!buffer) {
777                 opj_event_msg(j2k->cinfo, EVT_ERROR, "The EPB pointer is a NULL buffer\n");
778                 return OPJ_FALSE;
779         }
780         
781         /* set bignesses */
782         L1 = pre_len + 13;
783
784         /* pre-data correction */
785         switch (type) {
786
787         case 0:
788                 /* MH EPB */
789                 k_pre = 64;
790                 n_pre = 160;
791                 break;
792
793         case 1:
794                 /* TPH EPB */
795                 k_pre = 25;
796                 n_pre = 80;
797                 break;
798
799         case 2:
800                 /* other EPBs */
801                 k_pre = 13;
802                 n_pre = 40;
803                 break;
804
805         case 3:
806                 /* automatic setup */
807                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Auto. setup not yet implemented\n");
808                 return OPJ_FALSE;
809                 break;
810
811         default:
812                 /* unknown type */
813                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Unknown expected EPB type\n");
814                 return OPJ_FALSE;
815                 break;
816
817         }
818
819         /* Initialize RS structures */
820         P = n_pre - k_pre;
821         NN_P = NN - P;
822         tt = (int) floor((float) P / 2.0F); /* correction capability of the code */
823         memset(codeword, 0, NN);
824         parityword = codeword + NN_P;
825         init_rs(NN_P);
826
827         /* Correct pre-data message words */
828         L1_buf = buffer - pre_len;
829         L2_buf = buffer + 13;
830         remaining = L1;
831         while (remaining) {
832  
833                 /* always zero-pad codewords */
834                 /* (this is required, since after decoding the zeros in the long codeword
835                     could change, and keep unchanged in subsequent calls) */
836                 memset(codeword, 0, NN);
837
838                 /* copy codeword buffer into message bytes */
839                 if (remaining < k_pre)
840                         memcpy(codeword, L1_buf, remaining);
841                 else
842                         memcpy(codeword, L1_buf, k_pre);
843
844                 /* copy redundancy buffer in parity bytes */
845                 memcpy(parityword, L2_buf, P); 
846
847                 /* Decode the buffer and possibly obtain corrected bytes */
848                 status = eras_dec_rs(codeword, NULL, 0);
849                 if (status == -1) {
850                         /*if (conn == NULL)
851                                 opj_event_msg(j2k->cinfo, EVT_WARNING,
852                                         "Possible decoding error in codeword @ position #%d\n", (L1_buf - buffer) / k_pre);*/
853                         errflag = OPJ_TRUE;
854                         /* we can try to safely get out from the function:
855                           if we are here, either this is not an EPB or the first codeword
856                           is too damaged to be helpful */
857                         /*return OPJ_FALSE;*/
858
859                 } else if (status == 0) {
860                         /*if (conn == NULL)
861                                 opj_event_msg(j2k->cinfo, EVT_INFO, "codeword is correctly decoded\n");*/
862
863                 } else if (status <= tt) {
864                         /* it has corrected 0 <= errs <= tt */
865                         /*if (conn == NULL)
866                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "%d errors corrected in codeword\n", status);*/
867                         errnum += status;
868
869                 } else {
870                         /*if (conn == NULL)
871                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "EPB correction capability exceeded\n");
872                         return OPJ_FALSE;*/
873                         errflag = OPJ_TRUE;
874                 }
875
876
877                 /* advance parity buffer */
878                 if ((status >= 0) && (status <= tt))
879                         /* copy back corrected parity only if all is OK */
880                         memcpy(L2_buf, parityword, P);
881                 L2_buf += P;
882
883                 /* advance message buffer */
884                 if (remaining < k_pre) {
885                         if ((status >= 0) && (status <= tt))
886                                 /* copy back corrected data only if all is OK */
887                                 memcpy(L1_buf, codeword, remaining);
888                         L1_buf += remaining;
889                         remaining = 0;
890
891                 } else {
892                         if ((status >= 0) && (status <= tt))
893                                 /* copy back corrected data only if all is OK */
894                                 memcpy(L1_buf, codeword, k_pre);
895                         L1_buf += k_pre;
896                         remaining -= k_pre;
897
898                 }
899         }
900
901         /* print summary */
902         if (!conn) {
903
904                 /*if (errnum)
905                         opj_event_msg(j2k->cinfo, EVT_INFO, "+ %d symbol errors corrected (Ps=%.1e)\n", errnum,
906                                 (float) errnum / ((float) n_pre * (float) L1 / (float) k_pre));*/
907                 if (errflag) {
908                         /*opj_event_msg(j2k->cinfo, EVT_INFO, "+ there were unrecoverable errors\n");*/
909                         return OPJ_FALSE;
910                 }
911
912         }
913
914         /* presumably, now, EPB parameters are correct */
915         /* let's get them */
916
917         /* Simply read the EPB parameters */
918         if (conn)
919                 cio->bp = buffer;
920         cio_skip(cio, 2); /* the marker */
921         Lepb = cio_read(cio, 2);
922         Depb = cio_read(cio, 1);
923         LDPepb = cio_read(cio, 4);
924         Pepb = cio_read(cio, 4);
925
926         /* What does Pepb tells us about the protection method? */
927         if (((Pepb & 0xF0000000) >> 28) == 0)
928                 sprintf(str1, "pred"); /* predefined */
929         else if (((Pepb & 0xF0000000) >> 28) == 1)
930                 sprintf(str1, "crc-%lu", 16 * ((Pepb & 0x00000001) + 1)); /* CRC mode */
931         else if (((Pepb & 0xF0000000) >> 28) == 2)
932                 sprintf(str1, "rs(%lu,32)", (Pepb & 0x0000FF00) >> 8); /* RS mode */
933         else if (Pepb == 0xFFFFFFFF)
934                 sprintf(str1, "nometh"); /* RS mode */
935         else
936                 sprintf(str1, "unknown"); /* unknown */
937
938         /* Now we write them to screen */
939         if (!conn && post_len)
940                 opj_event_msg(j2k->cinfo, EVT_INFO,
941                         "EPB(%d): (%sl, %sp, %u), %lu, %s\n",
942                         cio_tell(cio) - 13,
943                         (Depb & 0x40) ? "" : "n", /* latest EPB or not? */
944                         (Depb & 0x80) ? "" : "n", /* packed or unpacked EPB? */
945                         (Depb & 0x3F), /* EPB index value */
946                         LDPepb, /*length of the data protected by the EPB */
947                         str1); /* protection method */
948
949
950         /* well, we need to investigate how long is the connected length of packed EPBs */
951         myconn = Lepb + 2;
952         if ((Depb & 0x40) == 0) /* not latest in header */
953                 jpwl_epb_correct(j2k,      /* J2K decompressor handle */
954                                              buffer + Lepb + 2,   /* pointer to next EPB in codestream buffer */
955                                              2,     /* EPB type: should be of other type */
956                                              0,  /* only EPB fields */
957                                              0, /* do not look after */
958                                                  &myconn,
959                                                  NULL
960                                              );
961         if (conn)
962                 *conn += myconn;
963
964         /*if (!conn)
965                 printf("connected = %d\n", myconn);*/
966
967         /*cio_seek(j2k->cio, orig_pos);
968         return OPJ_TRUE;*/
969
970         /* post-data
971            the position of L4 buffer is at the end of currently connected EPBs
972         */
973         if (!(L4_bufp))
974                 L4_buf = buffer + myconn;
975         else if (!(*L4_bufp))
976                 L4_buf = buffer + myconn;
977         else
978                 L4_buf = *L4_bufp;
979         if (post_len == -1) 
980                 L4 = LDPepb - pre_len - 13;
981         else if (post_len == 0)
982                 L4 = 0;
983         else
984                 L4 = post_len;
985
986         L3_buf = L2_buf;
987
988         /* Do a further check here on the read parameters */
989         if (L4 > (unsigned long) cio_numbytesleft(j2k->cio))
990                 /* overflow */
991                 return OPJ_FALSE;
992
993         /* we are ready for decoding the remaining data */
994         if (((Pepb & 0xF0000000) >> 28) == 1) {
995                 /* CRC here */
996                 if ((16 * ((Pepb & 0x00000001) + 1)) == 16) {
997
998                         /* CRC-16 */
999                         unsigned short int mycrc = 0x0000, filecrc = 0x0000;
1000
1001                         /* compute the CRC field */
1002                         remaining = L4;
1003                         while (remaining--)
1004                                 jpwl_updateCRC16(&mycrc, *(L4_buf++));
1005
1006                         /* read the CRC field */
1007                         filecrc = *(L3_buf++) << 8;
1008                         filecrc |= *(L3_buf++);
1009
1010                         /* check the CRC field */
1011                         if (mycrc == filecrc) {
1012                                 if (conn == NULL)
1013                                         opj_event_msg(j2k->cinfo, EVT_INFO, "- CRC is OK\n");
1014                         } else {
1015                                 if (conn == NULL)
1016                                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- CRC is KO (r=%d, c=%d)\n", filecrc, mycrc);
1017                                 errflag = OPJ_TRUE;
1018                         }       
1019                 }
1020
1021                 if ((16 * ((Pepb & 0x00000001) + 1)) == 32) {
1022
1023                         /* CRC-32 */
1024                         unsigned long int mycrc = 0x00000000, filecrc = 0x00000000;
1025
1026                         /* compute the CRC field */
1027                         remaining = L4;
1028                         while (remaining--)
1029                                 jpwl_updateCRC32(&mycrc, *(L4_buf++));
1030
1031                         /* read the CRC field */
1032                         filecrc = *(L3_buf++) << 24;
1033                         filecrc |= *(L3_buf++) << 16;
1034                         filecrc |= *(L3_buf++) << 8;
1035                         filecrc |= *(L3_buf++);
1036
1037                         /* check the CRC field */
1038                         if (mycrc == filecrc) {
1039                                 if (conn == NULL)
1040                                         opj_event_msg(j2k->cinfo, EVT_INFO, "- CRC is OK\n");
1041                         } else {
1042                                 if (conn == NULL)
1043                                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- CRC is KO (r=%d, c=%d)\n", filecrc, mycrc);
1044                                 errflag = OPJ_TRUE;
1045                         }
1046                 }
1047
1048         } else if (Pepb == 0xFFFFFFFF) {
1049                 /* no method */
1050
1051                 /* advance without doing anything */
1052                 remaining = L4;
1053                 while (remaining--)
1054                         L4_buf++;
1055
1056         } else if ((((Pepb & 0xF0000000) >> 28) == 2) || (((Pepb & 0xF0000000) >> 28) == 0)) {
1057                 /* RS coding here */
1058
1059                 if (((Pepb & 0xF0000000) >> 28) == 0) {
1060
1061                         k_post = k_pre;
1062                         n_post = n_pre;
1063
1064                 } else {
1065
1066                         k_post = 32;
1067                         n_post = (Pepb & 0x0000FF00) >> 8;
1068                 }
1069
1070                 /* Initialize RS structures */
1071                 P = n_post - k_post;
1072                 NN_P = NN - P;
1073                 tt = (int) floor((float) P / 2.0F); /* again, correction capability */
1074                 memset(codeword, 0, NN);
1075                 parityword = codeword + NN_P;
1076                 init_rs(NN_P);
1077
1078                 /* Correct post-data message words */
1079                 /*L4_buf = buffer + Lepb + 2;*/
1080                 L3_buf = L2_buf;
1081                 remaining = L4;
1082                 while (remaining) {
1083  
1084                         /* always zero-pad codewords */
1085                         /* (this is required, since after decoding the zeros in the long codeword
1086                                 could change, and keep unchanged in subsequent calls) */
1087                         memset(codeword, 0, NN);
1088
1089                         /* copy codeword buffer into message bytes */
1090                         if (remaining < k_post)
1091                                 memcpy(codeword, L4_buf, remaining);
1092                         else
1093                                 memcpy(codeword, L4_buf, k_post);
1094
1095                         /* copy redundancy buffer in parity bytes */
1096                         memcpy(parityword, L3_buf, P); 
1097
1098                         /* Decode the buffer and possibly obtain corrected bytes */
1099                         status = eras_dec_rs(codeword, NULL, 0);
1100                         if (status == -1) {
1101                                 /*if (conn == NULL)
1102                                         opj_event_msg(j2k->cinfo, EVT_WARNING,
1103                                                 "Possible decoding error in codeword @ position #%d\n", (L4_buf - (buffer + Lepb + 2)) / k_post);*/
1104                                 errflag = OPJ_TRUE;
1105
1106                         } else if (status == 0) {
1107                                 /*if (conn == NULL)
1108                                         opj_event_msg(j2k->cinfo, EVT_INFO, "codeword is correctly decoded\n");*/
1109
1110                         } else if (status <= tt) {
1111                                 /*if (conn == NULL)
1112                                         opj_event_msg(j2k->cinfo, EVT_WARNING, "%d errors corrected in codeword\n", status);*/
1113                                 errnum += status;
1114
1115                         } else {
1116                                 /*if (conn == NULL)
1117                                         opj_event_msg(j2k->cinfo, EVT_WARNING, "EPB correction capability exceeded\n");
1118                                 return OPJ_FALSE;*/
1119                                 errflag = OPJ_TRUE;
1120                         }
1121
1122
1123                         /* advance parity buffer */
1124                         if ((status >= 0) && (status <= tt))
1125                                 /* copy back corrected data only if all is OK */
1126                                 memcpy(L3_buf, parityword, P);
1127                         L3_buf += P;
1128
1129                         /* advance message buffer */
1130                         if (remaining < k_post) {
1131                                 if ((status >= 0) && (status <= tt))
1132                                         /* copy back corrected data only if all is OK */
1133                                         memcpy(L4_buf, codeword, remaining);
1134                                 L4_buf += remaining;
1135                                 remaining = 0;
1136
1137                         } else {
1138                                 if ((status >= 0) && (status <= tt))
1139                                         /* copy back corrected data only if all is OK */
1140                                         memcpy(L4_buf, codeword, k_post);
1141                                 L4_buf += k_post;
1142                                 remaining -= k_post;
1143
1144                         }
1145                 }
1146         }
1147
1148         /* give back the L4_buf address */
1149         if (L4_bufp)
1150                 *L4_bufp = L4_buf;
1151
1152         /* print summary */
1153         if (!conn) {
1154
1155                 if (errnum)
1156                         opj_event_msg(j2k->cinfo, EVT_INFO, "- %d symbol errors corrected (Ps=%.1e)\n", errnum,
1157                                 (float) errnum / (float) LDPepb);
1158                 if (errflag)
1159                         opj_event_msg(j2k->cinfo, EVT_INFO, "- there were unrecoverable errors\n");
1160
1161         }
1162
1163         cio_seek(j2k->cio, orig_pos);
1164
1165         return OPJ_TRUE;
1166 }
1167
1168 void jpwl_epc_write(opj_j2k_t *j2k, jpwl_epc_ms_t *epc, unsigned char *buf) {
1169
1170         /* Marker */
1171         *(buf++) = (unsigned char) (J2K_MS_EPC >> 8); 
1172         *(buf++) = (unsigned char) (J2K_MS_EPC >> 0); 
1173
1174         /* Lepc */
1175         *(buf++) = (unsigned char) (epc->Lepc >> 8); 
1176         *(buf++) = (unsigned char) (epc->Lepc >> 0); 
1177
1178         /* Pcrc */
1179         *(buf++) = (unsigned char) (epc->Pcrc >> 8); 
1180         *(buf++) = (unsigned char) (epc->Pcrc >> 0);
1181
1182         /* DL */
1183         *(buf++) = (unsigned char) (epc->DL >> 24); 
1184         *(buf++) = (unsigned char) (epc->DL >> 16); 
1185         *(buf++) = (unsigned char) (epc->DL >> 8); 
1186         *(buf++) = (unsigned char) (epc->DL >> 0); 
1187
1188         /* Pepc */
1189         *(buf++) = (unsigned char) (epc->Pepc >> 0); 
1190
1191         /* Data */
1192         /*memcpy(buf, epc->data, (size_t) epc->Lepc - 9);*/
1193         memset(buf, 0, (size_t) epc->Lepc - 9);
1194
1195         /* update markers struct */
1196         j2k_add_marker(j2k->cstr_info, J2K_MS_EPC, -1, epc->Lepc + 2);
1197
1198 }
1199
1200 int jpwl_esds_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num,
1201                                   int comps, unsigned char addrm, unsigned char ad_size,
1202                                   unsigned char senst, unsigned char se_size,
1203                                   double place_pos, int tileno) {
1204
1205         return 0;
1206 }
1207
1208 jpwl_esd_ms_t *jpwl_esd_create(opj_j2k_t *j2k, int comp, 
1209         unsigned char addrm, unsigned char ad_size,
1210         unsigned char senst, int se_size, int tileno,
1211         unsigned long int svalnum, void *sensval) {
1212
1213         jpwl_esd_ms_t *esd = NULL;
1214
1215         /* Alloc space */
1216         if (!(esd = (jpwl_esd_ms_t *) opj_malloc((size_t) 1 * sizeof (jpwl_esd_ms_t)))) {
1217                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for ESD MS\n");
1218                 return NULL;
1219         };
1220
1221         /* if relative sensitivity, activate byte range mode */
1222         if (senst == 0)
1223                 addrm = 1;
1224
1225         /* size of sensval's ... */
1226         if ((ad_size != 0) && (ad_size != 2) && (ad_size != 4)) {
1227                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Address size %d for ESD MS is forbidden\n", ad_size);
1228                 return NULL;
1229         }
1230         if ((se_size != 1) && (se_size != 2)) {
1231                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Sensitivity size %d for ESD MS is forbidden\n", se_size);
1232                 return NULL;
1233         }
1234         
1235         /* ... depends on the addressing mode */
1236         switch (addrm) {
1237
1238         /* packet mode */
1239         case (0):
1240                 ad_size = 0; /* as per the standard */
1241                 esd->sensval_size = (unsigned int)se_size; 
1242                 break;
1243
1244         /* byte range */
1245         case (1):
1246                 /* auto sense address size */
1247                 if (ad_size == 0)
1248                         /* if there are more than 66% of (2^16 - 1) bytes, switch to 4 bytes
1249                          (we keep space for possible EPBs being inserted) */
1250                         ad_size = (j2k->cstr_info->codestream_size > (1 * 65535 / 3)) ? 4 : 2;
1251                 esd->sensval_size = ad_size + ad_size + se_size; 
1252                 break;
1253
1254         /* packet range */
1255         case (2):
1256                 /* auto sense address size */
1257                 if (ad_size == 0)
1258                         /* if there are more than 2^16 - 1 packets, switch to 4 bytes */
1259                         ad_size = (j2k->cstr_info->packno > 65535) ? 4 : 2;
1260                 esd->sensval_size = ad_size + ad_size + se_size; 
1261                 break;
1262
1263         case (3):
1264                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Address mode %d for ESD MS is unimplemented\n", addrm);
1265                 return NULL;
1266
1267         default:
1268                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Address mode %d for ESD MS is forbidden\n", addrm);
1269                 return NULL;
1270         }
1271
1272         /* set or unset sensitivity values */
1273         if (svalnum <= 0) {
1274
1275                 switch (senst) {
1276
1277                 /* just based on the portions of a codestream */
1278                 case (0):
1279                         /* MH + no. of THs + no. of packets */
1280                         svalnum = 1 + (j2k->cstr_info->tw * j2k->cstr_info->th) * (1 + j2k->cstr_info->packno);
1281                         break;
1282
1283                 /* all the ones that are based on the packets */
1284                 default:
1285                         if (tileno < 0)
1286                                 /* MH: all the packets and all the tiles info is written */
1287                                 svalnum = j2k->cstr_info->tw * j2k->cstr_info->th * j2k->cstr_info->packno;
1288                         else
1289                                 /* TPH: only that tile info is written */
1290                                 svalnum = j2k->cstr_info->packno;
1291                         break;
1292
1293                 }
1294         }               
1295
1296         /* fill private fields */
1297         esd->senst = senst;
1298         esd->ad_size = ad_size;
1299         esd->se_size = se_size;
1300         esd->addrm = addrm;
1301         esd->svalnum = svalnum;
1302         esd->numcomps = j2k->image->numcomps;
1303         esd->tileno = tileno;
1304         
1305         /* Set the ESD parameters */
1306         /* length, excluding data field */
1307         if (esd->numcomps < 257)
1308                 esd->Lesd = 4 + (unsigned short int) (esd->svalnum * esd->sensval_size);
1309         else
1310                 esd->Lesd = 5 + (unsigned short int) (esd->svalnum * esd->sensval_size);
1311
1312         /* component data field */
1313         if (comp >= 0)
1314                 esd->Cesd = comp;
1315         else
1316                 /* we are averaging */
1317                 esd->Cesd = 0;
1318
1319         /* Pesd field */
1320         esd->Pesd = 0x00;
1321         esd->Pesd |= (esd->addrm & 0x03) << 6; /* addressing mode */
1322         esd->Pesd |= (esd->senst & 0x07) << 3; /* sensitivity type */
1323         esd->Pesd |= ((esd->se_size >> 1) & 0x01) << 2; /* sensitivity size */
1324         esd->Pesd |= ((esd->ad_size >> 2) & 0x01) << 1; /* addressing size */
1325         esd->Pesd |= (comp < 0) ? 0x01 : 0x00; /* averaging components */
1326
1327         /* if pointer to sensval is NULL, we can fill data field by ourselves */
1328         if (!sensval) {
1329
1330                 /* old code moved to jpwl_esd_fill() */
1331                 esd->data = NULL;
1332
1333         } else {
1334                         /* we set the data field as the sensitivity values poinnter passed to the function */
1335                         esd->data = (unsigned char *) sensval;
1336         }
1337
1338         return (esd);
1339 }
1340
1341 opj_bool jpwl_esd_fill(opj_j2k_t *j2k, jpwl_esd_ms_t *esd, unsigned char *buf) {
1342
1343         int i;
1344         unsigned long int vv;
1345         unsigned long int addr1 = 0L, addr2 = 0L;
1346         double dvalue = 0.0, Omax2, tmp, TSE = 0.0, MSE, oldMSE = 0.0, PSNR, oldPSNR = 0.0;
1347         unsigned short int pfpvalue;
1348         unsigned long int addrmask = 0x00000000;
1349         opj_bool doneMH = OPJ_FALSE, doneTPH = OPJ_FALSE;
1350
1351         /* sensitivity values in image info are as follows:
1352                 - for each tile, distotile is the starting distortion for that tile, sum of all components
1353                 - for each packet in a tile, disto is the distortion reduction caused by that packet to that tile
1354                 - the TSE for a single tile should be given by   distotile - sum(disto)  , for all components
1355                 - the MSE for a single tile is given by     TSE / nbpix    , for all components
1356                 - the PSNR for a single tile is given by   10*log10( Omax^2 / MSE)    , for all components
1357                   (Omax is given by    2^bpp - 1    for unsigned images and by    2^(bpp - 1) - 1    for signed images
1358         */
1359
1360         /* browse all components and find Omax */
1361         Omax2 = 0.0;
1362         for (i = 0; i < j2k->image->numcomps; i++) {
1363                 tmp = pow(2.0, (double) (j2k->image->comps[i].sgnd ?
1364                         (j2k->image->comps[i].bpp - 1) : (j2k->image->comps[i].bpp))) - 1;
1365                 if (tmp > Omax2)
1366                         Omax2 = tmp;
1367         }
1368         Omax2 = Omax2 * Omax2;
1369
1370         /* if pointer of esd->data is not null, simply write down all the values byte by byte */
1371         if (esd->data) {
1372                 for (i = 0; i < (int) esd->svalnum; i++)
1373                         *(buf++) = esd->data[i]; 
1374                 return OPJ_TRUE;
1375         }
1376
1377         /* addressing mask */
1378         if (esd->ad_size == 2)
1379                 addrmask = 0x0000FFFF; /* two bytes */
1380         else
1381                 addrmask = 0xFFFFFFFF; /* four bytes */
1382
1383         /* set on precise point where sensitivity starts */
1384         if (esd->numcomps < 257)
1385                 buf += 6;
1386         else
1387                 buf += 7;
1388
1389         /* let's fill the data fields */
1390         for (vv = (esd->tileno < 0) ? 0 : (j2k->cstr_info->packno * esd->tileno); vv < esd->svalnum; vv++) {
1391
1392                 int thistile = vv / j2k->cstr_info->packno, thispacket = vv % j2k->cstr_info->packno;
1393
1394                 /* skip for the hack some lines below */
1395                 if (thistile == j2k->cstr_info->tw * j2k->cstr_info->th)
1396                         break;
1397
1398                 /* starting tile distortion */
1399                 if (thispacket == 0) {
1400                         TSE = j2k->cstr_info->tile[thistile].distotile;
1401                         oldMSE = TSE / j2k->cstr_info->tile[thistile].numpix;
1402                         oldPSNR = 10.0 * log10(Omax2 / oldMSE);
1403                 }
1404
1405                 /* TSE */
1406                 TSE -= j2k->cstr_info->tile[thistile].packet[thispacket].disto;
1407
1408                 /* MSE */
1409                 MSE = TSE / j2k->cstr_info->tile[thistile].numpix;
1410
1411                 /* PSNR */
1412                 PSNR = 10.0 * log10(Omax2 / MSE);
1413
1414                 /* fill the address range */
1415                 switch (esd->addrm) {
1416
1417                 /* packet mode */
1418                 case (0):
1419                         /* nothing, there is none */
1420                         break;
1421
1422                 /* byte range */
1423                 case (1):
1424                         /* start address of packet */
1425                         addr1 = (j2k->cstr_info->tile[thistile].packet[thispacket].start_pos) & addrmask;
1426                         /* end address of packet */
1427                         addr2 = (j2k->cstr_info->tile[thistile].packet[thispacket].end_pos) & addrmask;
1428                         break;
1429
1430                 /* packet range */
1431                 case (2):
1432                         /* not implemented here */
1433                         opj_event_msg(j2k->cinfo, EVT_WARNING, "Addressing mode packet_range is not implemented\n");
1434                         break;
1435
1436                 /* unknown addressing method */
1437                 default:
1438                         /* not implemented here */
1439                         opj_event_msg(j2k->cinfo, EVT_WARNING, "Unknown addressing mode\n");
1440                         break;
1441
1442                 }
1443
1444                 /* hack for writing relative sensitivity of MH and TPHs */
1445                 if ((esd->senst == 0) && (thispacket == 0)) {
1446
1447                         /* possible MH */
1448                         if ((thistile == 0) && !doneMH) {
1449                                 /* we have to manage MH addresses */
1450                                 addr1 = 0; /* start of MH */
1451                                 addr2 = j2k->cstr_info->main_head_end; /* end of MH */
1452                                 /* set special dvalue for this MH */
1453                                 dvalue = -10.0;
1454                                 doneMH = OPJ_TRUE; /* don't come here anymore */
1455                                 vv--; /* wrap back loop counter */
1456
1457                         } else if (!doneTPH) {
1458                                 /* we have to manage TPH addresses */
1459                                 addr1 = j2k->cstr_info->tile[thistile].start_pos;
1460                                 addr2 = j2k->cstr_info->tile[thistile].end_header;
1461                                 /* set special dvalue for this TPH */
1462                                 dvalue = -1.0;
1463                                 doneTPH = OPJ_TRUE; /* don't come here till the next tile */
1464                                 vv--; /* wrap back loop counter */
1465                         }
1466
1467                 } else
1468                         doneTPH = OPJ_FALSE; /* reset TPH counter */
1469
1470                 /* write the addresses to the buffer */
1471                 switch (esd->ad_size) {
1472
1473                 case (0):
1474                         /* do nothing */
1475                         break;
1476
1477                 case (2):
1478                         /* two bytes */
1479                         *(buf++) = (unsigned char) (addr1 >> 8); 
1480                         *(buf++) = (unsigned char) (addr1 >> 0); 
1481                         *(buf++) = (unsigned char) (addr2 >> 8); 
1482                         *(buf++) = (unsigned char) (addr2 >> 0); 
1483                         break;
1484
1485                 case (4):
1486                         /* four bytes */
1487                         *(buf++) = (unsigned char) (addr1 >> 24); 
1488                         *(buf++) = (unsigned char) (addr1 >> 16); 
1489                         *(buf++) = (unsigned char) (addr1 >> 8); 
1490                         *(buf++) = (unsigned char) (addr1 >> 0); 
1491                         *(buf++) = (unsigned char) (addr2 >> 24); 
1492                         *(buf++) = (unsigned char) (addr2 >> 16); 
1493                         *(buf++) = (unsigned char) (addr2 >> 8); 
1494                         *(buf++) = (unsigned char) (addr2 >> 0); 
1495                         break;
1496
1497                 default:
1498                         /* do nothing */
1499                         break;
1500                 }
1501
1502
1503                 /* let's fill the value field */
1504                 switch (esd->senst) {
1505
1506                 /* relative sensitivity */
1507                 case (0):
1508                         /* we just write down the packet ordering */
1509                         if (dvalue == -10)
1510                                 /* MH */
1511                                 dvalue = MAX_V1 + 1000.0; /* this will cause pfpvalue set to 0xFFFF */
1512                         else if (dvalue == -1)
1513                                 /* TPH */
1514                                 dvalue = MAX_V1 + 1000.0; /* this will cause pfpvalue set to 0xFFFF */
1515                         else
1516                                 /* packet: first is most important, and then in decreasing order
1517                                 down to the last, which counts for 1 */
1518                                 dvalue = jpwl_pfp_to_double((unsigned short) (j2k->cstr_info->packno - thispacket), esd->se_size);
1519                         break;
1520
1521                 /* MSE */
1522                 case (1):
1523                         /* !!! WRONG: let's put here disto field of packets !!! */
1524                         dvalue = MSE;
1525                         break;
1526
1527                 /* MSE reduction */
1528                 case (2):
1529                         dvalue = oldMSE - MSE;
1530                         oldMSE = MSE;
1531                         break;
1532
1533                 /* PSNR */
1534                 case (3):
1535                         dvalue = PSNR;
1536                         break;
1537
1538                 /* PSNR increase */
1539                 case (4):
1540                         dvalue = PSNR - oldPSNR;
1541                         oldPSNR = PSNR;
1542                         break;
1543
1544                 /* MAXERR */
1545                 case (5):
1546                         dvalue = 0.0;
1547                         opj_event_msg(j2k->cinfo, EVT_WARNING, "MAXERR sensitivity mode is not implemented\n");
1548                         break;
1549
1550                 /* TSE */
1551                 case (6):
1552                         dvalue = TSE;
1553                         break;
1554
1555                 /* reserved */
1556                 case (7):
1557                         dvalue = 0.0;
1558                         opj_event_msg(j2k->cinfo, EVT_WARNING, "Reserved sensitivity mode is not implemented\n");
1559                         break;
1560
1561                 default:
1562                         dvalue = 0.0;
1563                         break;
1564                 }
1565
1566                 /* compute the pseudo-floating point value */
1567                 pfpvalue = jpwl_double_to_pfp(dvalue, esd->se_size);
1568
1569                 /* write the pfp value to the buffer */
1570                 switch (esd->se_size) {
1571
1572                 case (1):
1573                         /* one byte */
1574                         *(buf++) = (unsigned char) (pfpvalue >> 0); 
1575                         break;
1576
1577                 case (2):
1578                         /* two bytes */
1579                         *(buf++) = (unsigned char) (pfpvalue >> 8); 
1580                         *(buf++) = (unsigned char) (pfpvalue >> 0); 
1581                         break;
1582                 }
1583
1584         }
1585
1586         return OPJ_TRUE;
1587 }
1588
1589 opj_bool jpwl_esd_write(opj_j2k_t *j2k, jpwl_esd_ms_t *esd, unsigned char *buf) {
1590
1591         /* Marker */
1592         *(buf++) = (unsigned char) (J2K_MS_ESD >> 8); 
1593         *(buf++) = (unsigned char) (J2K_MS_ESD >> 0); 
1594
1595         /* Lesd */
1596         *(buf++) = (unsigned char) (esd->Lesd >> 8); 
1597         *(buf++) = (unsigned char) (esd->Lesd >> 0); 
1598
1599         /* Cesd */
1600         if (esd->numcomps >= 257)
1601                 *(buf++) = (unsigned char) (esd->Cesd >> 8); 
1602         *(buf++) = (unsigned char) (esd->Cesd >> 0); 
1603
1604         /* Pesd */
1605         *(buf++) = (unsigned char) (esd->Pesd >> 0); 
1606
1607         /* Data */
1608         if (esd->numcomps < 257)
1609                 memset(buf, 0xAA, (size_t) esd->Lesd - 4);
1610                 /*memcpy(buf, esd->data, (size_t) esd->Lesd - 4);*/
1611         else
1612                 memset(buf, 0xAA, (size_t) esd->Lesd - 5);
1613                 /*memcpy(buf, esd->data, (size_t) esd->Lesd - 5);*/
1614
1615         /* update markers struct */
1616         j2k_add_marker(j2k->cstr_info, J2K_MS_ESD, -1, esd->Lesd + 2);
1617
1618         return OPJ_TRUE;
1619 }
1620
1621 unsigned short int jpwl_double_to_pfp(double V, int bytes) {
1622
1623         unsigned short int em, e, m;
1624
1625         switch (bytes) {
1626
1627         case (1):
1628
1629                 if (V < MIN_V1) {
1630                         e = 0x0000;
1631                         m = 0x0000;
1632                 } else if (V > MAX_V1) {
1633                         e = 0x000F;
1634                         m = 0x000F;
1635                 } else {
1636                         e = (unsigned short int) (floor(log(V) * 1.44269504088896) / 4.0);
1637                         m = (unsigned short int) (0.5 + (V / (pow(2.0, (double) (4 * e)))));
1638                 }
1639                 em = ((e & 0x000F) << 4) + (m & 0x000F);                
1640                 break;
1641
1642         case (2):
1643
1644                 if (V < MIN_V2) {
1645                         e = 0x0000;
1646                         m = 0x0000;
1647                 } else if (V > MAX_V2) {
1648                         e = 0x001F;
1649                         m = 0x07FF;
1650                 } else {
1651                         e = (unsigned short int) floor(log(V) * 1.44269504088896) + 15;
1652                         m = (unsigned short int) (0.5 + 2048.0 * ((V / (pow(2.0, (double) e - 15.0))) - 1.0));
1653                 }
1654                 em = ((e & 0x001F) << 11) + (m & 0x07FF);
1655                 break;
1656
1657         default:
1658
1659                 em = 0x0000;
1660                 break;
1661         };
1662
1663         return em;
1664 }
1665
1666 double jpwl_pfp_to_double(unsigned short int em, int bytes) {
1667
1668         double V;
1669
1670         switch (bytes) {
1671
1672         case 1:
1673                 V = (double) (em & 0x0F) * pow(2.0, (double) (em & 0xF0));
1674                 break;
1675
1676         case 2:
1677
1678                 V = pow(2.0, (double) ((em & 0xF800) >> 11) - 15.0) * (1.0 + (double) (em & 0x07FF) / 2048.0);
1679                 break;
1680
1681         default:
1682                 V = 0.0;
1683                 break;
1684
1685         }
1686
1687         return V;
1688
1689 }
1690
1691 opj_bool jpwl_update_info(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int jwmarker_num) {
1692
1693         int mm;
1694         unsigned long int addlen;
1695
1696         opj_codestream_info_t *info = j2k->cstr_info;
1697         int tileno, tpno, packno, numtiles = info->th * info->tw, numpacks = info->packno;
1698
1699         if (!j2k || !jwmarker ) {
1700                 opj_event_msg(j2k->cinfo, EVT_ERROR, "J2K handle or JPWL markers list badly allocated\n");
1701                 return OPJ_FALSE;
1702         }
1703
1704         /* main_head_end: how many markers are there before? */
1705         addlen = 0;
1706         for (mm = 0; mm < jwmarker_num; mm++)
1707                 if (jwmarker[mm].pos < (unsigned long int) info->main_head_end)
1708                         addlen += jwmarker[mm].len + 2;
1709         info->main_head_end += addlen;
1710
1711         /* codestream_size: always increment with all markers */
1712         addlen = 0;
1713         for (mm = 0; mm < jwmarker_num; mm++)
1714                 addlen += jwmarker[mm].len + 2;
1715         info->codestream_size += addlen;
1716
1717         /* navigate through all the tiles */
1718         for (tileno = 0; tileno < numtiles; tileno++) {
1719
1720                 /* start_pos: increment with markers before SOT */
1721                 addlen = 0;
1722                 for (mm = 0; mm < jwmarker_num; mm++)
1723                         if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].start_pos)
1724                                 addlen += jwmarker[mm].len + 2;
1725                 info->tile[tileno].start_pos += addlen;
1726
1727                 /* end_header: increment with markers before of it */
1728                 addlen = 0;
1729                 for (mm = 0; mm < jwmarker_num; mm++)
1730                         if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].end_header)
1731                                 addlen += jwmarker[mm].len + 2;
1732                 info->tile[tileno].end_header += addlen;
1733
1734                 /* end_pos: increment with markers before the end of this tile */
1735                 /* code is disabled, since according to JPWL no markers can be beyond TPH */
1736                 addlen = 0;
1737                 for (mm = 0; mm < jwmarker_num; mm++)
1738                         if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].end_pos)
1739                                 addlen += jwmarker[mm].len + 2;
1740                 info->tile[tileno].end_pos += addlen;
1741
1742                 /* navigate through all the tile parts */
1743                 for (tpno = 0; tpno < info->tile[tileno].num_tps; tpno++) {
1744
1745                         /* start_pos: increment with markers before SOT */
1746                         addlen = 0;
1747                         for (mm = 0; mm < jwmarker_num; mm++)
1748                                 if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].tp[tpno].tp_start_pos)
1749                                         addlen += jwmarker[mm].len + 2;
1750                         info->tile[tileno].tp[tpno].tp_start_pos += addlen;
1751
1752                         /* end_header: increment with markers before of it */
1753                         addlen = 0;
1754                         for (mm = 0; mm < jwmarker_num; mm++)
1755                                 if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].tp[tpno].tp_end_header)
1756                                         addlen += jwmarker[mm].len + 2;
1757                         info->tile[tileno].tp[tpno].tp_end_header += addlen;
1758
1759                         /* end_pos: increment with markers before the end of this tile part */
1760                         addlen = 0;
1761                         for (mm = 0; mm < jwmarker_num; mm++)
1762                                 if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].tp[tpno].tp_end_pos)
1763                                         addlen += jwmarker[mm].len + 2;
1764                         info->tile[tileno].tp[tpno].tp_end_pos += addlen;
1765
1766                 }
1767
1768                 /* navigate through all the packets in this tile */
1769                 for (packno = 0; packno < numpacks; packno++) {
1770                         
1771                         /* start_pos: increment with markers before the packet */
1772                         /* disabled for the same reason as before */
1773                         addlen = 0;
1774                         for (mm = 0; mm < jwmarker_num; mm++)
1775                                 if (jwmarker[mm].pos <= (unsigned long int) info->tile[tileno].packet[packno].start_pos)
1776                                         addlen += jwmarker[mm].len + 2;
1777                         info->tile[tileno].packet[packno].start_pos += addlen;
1778
1779                         /* end_ph_pos: increment with markers before the packet */
1780                         /* disabled for the same reason as before */
1781                         /*addlen = 0;
1782                         for (mm = 0; mm < jwmarker_num; mm++)
1783                                 if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].packet[packno].end_ph_pos)
1784                                         addlen += jwmarker[mm].len + 2;*/
1785                         info->tile[tileno].packet[packno].end_ph_pos += addlen;
1786
1787                         /* end_pos: increment if marker is before the end of packet */
1788                         /* disabled for the same reason as before */
1789                         /*addlen = 0;
1790                         for (mm = 0; mm < jwmarker_num; mm++)
1791                                 if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].packet[packno].end_pos)
1792                                         addlen += jwmarker[mm].len + 2;*/
1793                         info->tile[tileno].packet[packno].end_pos += addlen;
1794
1795                 }
1796         }
1797
1798         /* reorder the markers list */
1799
1800         return OPJ_TRUE;
1801 }
1802
1803 #endif /* USE_JPWL */