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