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