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