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