[trunk] merge r1323 from branch 1.5 over to trunk
[openjpeg.git] / libopenjpeg / jpwl / jpwl.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, Herve 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 #include "opj_includes.h"
33
34 #ifdef USE_JPWL
35
36 /** @defgroup JPWL JPWL - JPEG-2000 Part11 (JPWL) codestream manager */
37 /*@{*/
38
39 /** @name Local static variables */
40 /*@{*/
41
42 /** number of JPWL prepared markers */
43 static int jwmarker_num;
44 /** properties of JPWL markers to insert */
45 static jpwl_marker_t jwmarker[JPWL_MAX_NO_MARKERS]; 
46
47 /*@}*/
48
49 /*@}*/
50
51 /** @name Local static functions */
52 /*@{*/
53
54 /** create an EPC marker segment
55 @param j2k J2K compressor handle
56 @param esd_on true if ESD is activated
57 @param red_on true if RED is activated
58 @param epb_on true if EPB is activated
59 @param info_on true if informative techniques are activated
60 @return returns the freshly created EPC
61 */
62 jpwl_epc_ms_t *jpwl_epc_create(opj_j2k_t *j2k, opj_bool esd_on, opj_bool red_on, opj_bool epb_on, opj_bool info_on);
63
64 /*@}*/
65
66 /** create an EPC marker segment
67 @param j2k J2K compressor handle
68 @param comps considered component (-1=average, 0/1/2/...=component no.)
69 @param addrm addressing mode (0=packet, 1=byte range, 2=packet range, 3=reserved)
70 @param ad_size size of addresses (2/4 bytes)
71 @param senst sensitivity type
72 @param se_size sensitivity values size (1/2 bytes)
73 @param tileno tile where this ESD lies (-1 means MH)
74 @param svalnum number of sensitivity values (if 0, they will be automatically filled)
75 @param sensval pointer to an array of sensitivity values (if NULL, they will be automatically filled)
76 @return returns the freshly created ESD
77 */
78 jpwl_esd_ms_t *jpwl_esd_create(opj_j2k_t *j2k, int comps, 
79         unsigned char addrm, unsigned char ad_size,
80         unsigned char senst, int se_size, int tileno,
81         unsigned long int svalnum, void *sensval);
82                         
83 /** this function is used to compare two JPWL markers based on
84 their relevant wishlist position
85 @param arg1 pointer to first marker
86 @param arg2 pointer to second marker
87 @return 1 if arg1>arg2, 0 if arg1=arg2, -1 if arg1<arg2
88 */
89 int jpwl_markcomp(const void *arg1, const void *arg2);
90
91 /** write an EPB MS to a buffer
92 @param j2k J2K compressor handle
93 @param epbmark pointer to the EPB MS
94 @param buf pointer to the memory buffer
95 */
96 void jpwl_epb_write(opj_j2k_t *j2k, jpwl_epb_ms_t *epbmark, unsigned char *buf);
97
98 /** write an EPC MS to a buffer
99 @param j2k J2K compressor handle
100 @param epcmark pointer to the EPC MS
101 @param buf pointer to the memory buffer
102 */
103 void jpwl_epc_write(opj_j2k_t *j2k, jpwl_epc_ms_t *epcmark, unsigned char *buf);
104
105 /** write an ESD MS to a buffer
106 @param j2k J2K compressor handle
107 @param esdmark pointer to the ESD MS
108 @param buf pointer to the memory buffer
109 */
110 void jpwl_esd_write(opj_j2k_t *j2k, jpwl_esd_ms_t *esdmark, unsigned char *buf);
111
112 /*-----------------------------------------------------------------*/
113
114 void jpwl_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image) {
115
116         int mm;
117
118         /* let's reset some settings */
119
120         /* clear the existing markers */
121         for (mm = 0; mm < jwmarker_num; mm++) {
122
123                 switch (jwmarker[mm].id) {
124
125                 case J2K_MS_EPB:
126                         opj_free(jwmarker[mm].m.epbmark);
127                         break;
128
129                 case J2K_MS_EPC:
130                         opj_free(jwmarker[mm].m.epcmark);
131                         break;
132
133                 case J2K_MS_ESD:
134                         opj_free(jwmarker[mm].m.esdmark);
135                         break;
136
137                 case J2K_MS_RED:
138                         opj_free(jwmarker[mm].m.redmark);
139                         break;
140
141                 default:
142                         break;
143                 }
144         }
145
146         /* clear the marker structure array */
147         memset(jwmarker, 0, sizeof(jpwl_marker_t) * JPWL_MAX_NO_MARKERS);
148
149         /* no more markers in the list */
150         jwmarker_num = 0;
151
152         /* let's begin creating a marker list, according to user wishes */
153         jpwl_prepare_marks(j2k, cio, image);
154
155         /* now we dump the JPWL markers on the codestream */
156         jpwl_dump_marks(j2k, cio, image);
157
158         /* do not know exactly what is this for,
159         but it gets called during index creation */
160         j2k->pos_correction = 0;
161
162 }
163
164 void j2k_add_marker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len) {
165
166         if (!cstr_info)
167                 return;
168
169         /* expand the list? */
170         if ((cstr_info->marknum + 1) > cstr_info->maxmarknum) {
171                 cstr_info->maxmarknum += 100;
172                 cstr_info->marker = (opj_marker_info_t*)opj_realloc(cstr_info->marker, cstr_info->maxmarknum * sizeof(opj_marker_info_t));
173         }
174
175         /* add the marker */
176         cstr_info->marker[cstr_info->marknum].type = type;
177         cstr_info->marker[cstr_info->marknum].pos = pos;
178         cstr_info->marker[cstr_info->marknum].len = len;
179         cstr_info->marknum++;
180
181 }
182
183 void jpwl_prepare_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image) {
184
185         unsigned short int socsiz_len = 0;
186         int ciopos = cio_tell(cio), soc_pos = j2k->cstr_info->main_head_start;
187         unsigned char *socp = NULL;
188
189         int tileno, acc_tpno, tpno, tilespec, hprot, sens, pprot, packspec, lastileno, packno;
190
191         jpwl_epb_ms_t *epb_mark;
192         jpwl_epc_ms_t *epc_mark;
193         jpwl_esd_ms_t *esd_mark;
194
195         /* find (SOC + SIZ) length */
196         /* I assume SIZ is always the first marker after SOC */
197         cio_seek(cio, soc_pos + 4);
198         socsiz_len = (unsigned short int) cio_read(cio, 2) + 4; /* add the 2 marks length itself */
199         cio_seek(cio, soc_pos + 0);
200         socp = cio_getbp(cio); /* pointer to SOC */
201
202         /* 
203          EPC MS for Main Header: if we are here it's required
204         */
205         /* create the EPC */
206         if ((epc_mark = jpwl_epc_create(
207                         j2k,
208                         j2k->cp->esd_on, /* is ESD present? */
209                         j2k->cp->red_on, /* is RED present? */
210                         j2k->cp->epb_on, /* is EPB present? */
211                         OPJ_FALSE /* are informative techniques present? */
212                 ))) {
213
214                 /* Add this marker to the 'insertanda' list */
215                 if (epc_mark) {
216                         jwmarker[jwmarker_num].id = J2K_MS_EPC; /* its type */
217                         jwmarker[jwmarker_num].m.epcmark = epc_mark; /* the EPC */
218                         jwmarker[jwmarker_num].pos = soc_pos + socsiz_len; /* after SIZ */
219                         jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos + 0.1; /* not so first */
220                         jwmarker[jwmarker_num].len = epc_mark->Lepc; /* its length */
221                         jwmarker[jwmarker_num].len_ready = OPJ_TRUE; /* ready */
222                         jwmarker[jwmarker_num].pos_ready = OPJ_TRUE; /* ready */
223                         jwmarker[jwmarker_num].parms_ready = OPJ_FALSE; /* not ready */
224                         jwmarker[jwmarker_num].data_ready = OPJ_TRUE; /* ready */
225                         jwmarker_num++;
226                 };
227
228                 opj_event_msg(j2k->cinfo, EVT_INFO,
229                         "MH  EPC : setting %s%s%s\n",
230                         j2k->cp->esd_on ? "ESD, " : "",
231                         j2k->cp->red_on ? "RED, " : "",
232                         j2k->cp->epb_on ? "EPB, " : ""
233                         );
234
235         } else {
236                 /* ooops, problems */
237                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create MH EPC\n");                              
238         };
239
240         /* 
241          ESD MS for Main Header
242         */
243         /* first of all, must MH have an ESD MS? */
244         if (j2k->cp->esd_on && (j2k->cp->sens_MH >= 0)) {
245
246                 /* Create the ESD */
247                 if ((esd_mark = jpwl_esd_create(
248                         j2k, /* this encoder handle */
249                         -1, /* we are averaging over all components */
250                         (unsigned char) j2k->cp->sens_range, /* range method */
251                         (unsigned char) j2k->cp->sens_addr, /* sensitivity addressing */
252                         (unsigned char) j2k->cp->sens_MH, /* sensitivity method */
253                         j2k->cp->sens_size, /* sensitivity size */
254                         -1, /* this ESD is in main header */
255                         0 /*j2k->cstr_info->num*/, /* number of packets in codestream */
256                         NULL /*sensval*/ /* pointer to sensitivity data of packets */
257                         ))) {
258                         
259                         /* Add this marker to the 'insertanda' list */
260                         if (jwmarker_num < JPWL_MAX_NO_MARKERS) {
261                                 jwmarker[jwmarker_num].id = J2K_MS_ESD; /* its type */
262                                 jwmarker[jwmarker_num].m.esdmark = esd_mark; /* the EPB */
263                                 jwmarker[jwmarker_num].pos = soc_pos + socsiz_len; /* we choose to place it after SIZ */
264                                 jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos + 0.2; /* not first at all! */
265                                 jwmarker[jwmarker_num].len = esd_mark->Lesd; /* its length */
266                                 jwmarker[jwmarker_num].len_ready = OPJ_TRUE; /* not ready, yet */
267                                 jwmarker[jwmarker_num].pos_ready = OPJ_TRUE; /* ready */
268                                 jwmarker[jwmarker_num].parms_ready = OPJ_TRUE; /* not ready */
269                                 jwmarker[jwmarker_num].data_ready = OPJ_FALSE; /* not ready */
270                                 jwmarker_num++;
271                         }
272
273                         opj_event_msg(j2k->cinfo, EVT_INFO,
274                                 "MH  ESDs: method %d\n",
275                                 j2k->cp->sens_MH
276                                 );
277
278                 } else {
279                         /* ooops, problems */
280                         opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create MH ESD\n");                              
281                 };
282
283         }
284
285         /* 
286          ESD MSs for Tile Part Headers 
287         */
288         /* cycle through tiles */
289         sens = -1; /* default spec: no ESD */
290         tilespec = 0; /* first tile spec */
291         acc_tpno = 0;
292         for (tileno = 0; tileno < j2k->cstr_info->tw * j2k->cstr_info->th; tileno++) {
293
294                 opj_event_msg(j2k->cinfo, EVT_INFO,
295                         "Tile %d has %d tile part(s)\n",
296                         tileno, j2k->cstr_info->tile[tileno].num_tps
297                         );
298
299                 /* for every tile part in the tile */
300                 for (tpno = 0; tpno < j2k->cstr_info->tile[tileno].num_tps; tpno++, acc_tpno++) {
301         
302                         int sot_len, Psot, Psotp, mm;
303                         unsigned long sot_pos, post_sod_pos;
304
305                         unsigned long int left_THmarks_len;
306
307                         /******* sot_pos = j2k->cstr_info->tile[tileno].start_pos; */
308                         sot_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos;
309                         cio_seek(cio, sot_pos + 2); 
310                         sot_len = cio_read(cio, 2); /* SOT Len */
311                         cio_skip(cio, 2);
312                         Psotp = cio_tell(cio);
313                         Psot = cio_read(cio, 4); /* tile length */
314
315                         /******* post_sod_pos = j2k->cstr_info->tile[tileno].end_header + 1; */
316                         post_sod_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_end_header + 1;
317                         left_THmarks_len = post_sod_pos - sot_pos;
318
319                         /* add all the lengths of the markers which are len-ready and stay within SOT and SOD */
320                         for (mm = 0; mm < jwmarker_num; mm++) {
321                                 if ((jwmarker[mm].pos >= sot_pos) && (jwmarker[mm].pos < post_sod_pos)) {
322                                         if (jwmarker[mm].len_ready)
323                                                 left_THmarks_len += jwmarker[mm].len + 2;
324                                         else {
325                                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "MS %x in %f is not len-ready: could not set up TH EPB\n",
326                                                         jwmarker[mm].id, jwmarker[mm].dpos);                            
327                                                 exit(1);
328                                         }
329                                 }
330                         }
331
332                         /******* if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->sens_TPH_tileno[tilespec] == tileno)) */
333                         if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->sens_TPH_tileno[tilespec] == acc_tpno))
334                                 /* we got a specification from this tile onwards */
335                                 sens = j2k->cp->sens_TPH[tilespec++];
336                 
337                         /* must this TPH have an ESD MS? */
338                         if (j2k->cp->esd_on && (sens >= 0)) {
339
340                                 /* Create the ESD */
341                                 if ((esd_mark = jpwl_esd_create(
342                                         j2k, /* this encoder handle */
343                                         -1, /* we are averaging over all components */
344                                         (unsigned char) j2k->cp->sens_range, /* range method */
345                                         (unsigned char) j2k->cp->sens_addr, /* sensitivity addressing size */
346                                         (unsigned char) sens, /* sensitivity method */
347                                         j2k->cp->sens_size, /* sensitivity value size */
348                                         tileno, /* this ESD is in a tile */
349                                         0, /* number of packets in codestream */
350                                         NULL /* pointer to sensitivity data of packets */
351                                         ))) {
352                                         
353                                         /* Add this marker to the 'insertanda' list */
354                                         if (jwmarker_num < JPWL_MAX_NO_MARKERS) {
355                                                 jwmarker[jwmarker_num].id = J2K_MS_ESD; /* its type */
356                                                 jwmarker[jwmarker_num].m.esdmark = esd_mark; /* the EPB */
357                                                 /****** jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].start_pos + sot_len + 2; */ /* after SOT */
358                                                 jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2; /* after SOT */
359                                                 jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos + 0.2; /* not first at all! */
360                                                 jwmarker[jwmarker_num].len = esd_mark->Lesd; /* its length */
361                                                 jwmarker[jwmarker_num].len_ready = OPJ_TRUE; /* ready, yet */
362                                                 jwmarker[jwmarker_num].pos_ready = OPJ_TRUE; /* ready */
363                                                 jwmarker[jwmarker_num].parms_ready = OPJ_TRUE; /* not ready */
364                                                 jwmarker[jwmarker_num].data_ready = OPJ_FALSE; /* ready */
365                                                 jwmarker_num++;
366                                         }
367
368                                         /* update Psot of the tile  */
369                                         cio_seek(cio, Psotp);
370                                         cio_write(cio, Psot + esd_mark->Lesd + 2, 4);
371
372                                         opj_event_msg(j2k->cinfo, EVT_INFO,
373                                                 /******* "TPH ESDs: tile %02d, method %d\n", */
374                                                 "TPH ESDs: tile %02d, part %02d, method %d\n",
375                                                 /******* tileno, */
376                                                 tileno, tpno,
377                                                 sens
378                                                 );
379
380                                 } else {
381                                         /* ooops, problems */
382                                         /***** opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH ESD #%d\n", tileno); */
383                                         opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH ESD #%d,%d\n", tileno, tpno);
384                                 };
385
386                         }
387                         
388                 }
389         
390         };
391
392         /* 
393          EPB MS for Main Header
394         */
395         /* first of all, must MH have an EPB MS? */
396         if (j2k->cp->epb_on && (j2k->cp->hprot_MH > 0)) {
397
398                 int mm;
399
400                 /* position of SOT */
401                 unsigned int sot_pos = j2k->cstr_info->main_head_end + 1;
402
403                 /* how much space is there between end of SIZ and beginning of SOT? */
404                 int left_MHmarks_len = sot_pos - socsiz_len;
405
406                 /* add all the lengths of the markers which are len-ready and stay within SOC and SOT */
407                 for (mm = 0; mm < jwmarker_num; mm++) {
408                         if ((jwmarker[mm].pos >=0) && (jwmarker[mm].pos < sot_pos)) {
409                                 if (jwmarker[mm].len_ready)
410                                         left_MHmarks_len += jwmarker[mm].len + 2;
411                                 else {
412                                         opj_event_msg(j2k->cinfo, EVT_ERROR, "MS %x in %f is not len-ready: could not set up MH EPB\n",
413                                                 jwmarker[mm].id, jwmarker[mm].dpos);                            
414                                         exit(1);
415                                 }
416                         }
417                 }
418
419                 /* Create the EPB */
420                 if ((epb_mark = jpwl_epb_create(
421                         j2k, /* this encoder handle */
422                         OPJ_TRUE, /* is it the latest? */
423                         OPJ_TRUE, /* is it packed? not for now */
424                         -1, /* we are in main header */
425                         0, /* its index is 0 (first) */
426                         j2k->cp->hprot_MH, /* protection type parameters of data */
427                         socsiz_len, /* pre-data: only SOC+SIZ */
428                         left_MHmarks_len /* post-data: from SOC to SOT, and all JPWL markers within */
429                         ))) {
430                         
431                         /* Add this marker to the 'insertanda' list */
432                         if (jwmarker_num < JPWL_MAX_NO_MARKERS) {
433                                 jwmarker[jwmarker_num].id = J2K_MS_EPB; /* its type */
434                                 jwmarker[jwmarker_num].m.epbmark = epb_mark; /* the EPB */
435                                 jwmarker[jwmarker_num].pos = soc_pos + socsiz_len; /* after SIZ */
436                                 jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos; /* first first first! */
437                                 jwmarker[jwmarker_num].len = epb_mark->Lepb; /* its length */
438                                 jwmarker[jwmarker_num].len_ready = OPJ_TRUE; /* ready */
439                                 jwmarker[jwmarker_num].pos_ready = OPJ_TRUE; /* ready */
440                                 jwmarker[jwmarker_num].parms_ready = OPJ_TRUE; /* ready */
441                                 jwmarker[jwmarker_num].data_ready = OPJ_FALSE; /* not ready */
442                                 jwmarker_num++;
443                         }
444
445                         opj_event_msg(j2k->cinfo, EVT_INFO,
446                                 "MH  EPB : prot. %d\n",
447                                 j2k->cp->hprot_MH
448                                 );
449
450                 } else {
451                         /* ooops, problems */
452                         opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create MH EPB\n");                              
453                 };
454         }
455
456         /* 
457          EPB MSs for Tile Parts
458         */
459         /* cycle through TPHs */
460         hprot = j2k->cp->hprot_MH; /* default spec */
461         tilespec = 0; /* first tile spec */
462         lastileno = 0;
463         packspec = 0;
464         pprot = -1;
465         acc_tpno = 0;
466         for (tileno = 0; tileno < j2k->cstr_info->tw * j2k->cstr_info->th; tileno++) {
467
468                 opj_event_msg(j2k->cinfo, EVT_INFO,
469                         "Tile %d has %d tile part(s)\n",
470                         tileno, j2k->cstr_info->tile[tileno].num_tps
471                         );
472
473                 /* for every tile part in the tile */
474                 for (tpno = 0; tpno < j2k->cstr_info->tile[tileno].num_tps; tpno++, acc_tpno++) { 
475                 
476                         int sot_len, Psot, Psotp, mm, epb_index = 0, prot_len = 0;
477                         unsigned long sot_pos, post_sod_pos;
478                         unsigned long int left_THmarks_len/*, epbs_len = 0*/;
479                         int startpack = 0, stoppack = j2k->cstr_info->packno;
480                         int first_tp_pack, last_tp_pack;
481                         jpwl_epb_ms_t *tph_epb = NULL;
482
483                         /****** sot_pos = j2k->cstr_info->tile[tileno].start_pos; */
484                         sot_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos;
485                         cio_seek(cio, sot_pos + 2); 
486                         sot_len = cio_read(cio, 2); /* SOT Len */
487                         cio_skip(cio, 2);
488                         Psotp = cio_tell(cio);
489                         Psot = cio_read(cio, 4); /* tile length */
490
491                         /* a-priori length of the data dwelling between SOT and SOD */
492                         /****** post_sod_pos = j2k->cstr_info->tile[tileno].end_header + 1; */
493                         post_sod_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_end_header + 1;
494                         left_THmarks_len = post_sod_pos - (sot_pos + sot_len + 2);
495
496                         /* add all the lengths of the JPWL markers which are len-ready and stay within SOT and SOD */
497                         for (mm = 0; mm < jwmarker_num; mm++) {
498                                 if ((jwmarker[mm].pos >= sot_pos) && (jwmarker[mm].pos < post_sod_pos)) {
499                                         if (jwmarker[mm].len_ready)
500                                                 left_THmarks_len += jwmarker[mm].len + 2;
501                                         else {
502                                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "MS %x in %f is not len-ready: could not set up TH EPB\n",
503                                                         jwmarker[mm].id, jwmarker[mm].dpos);                            
504                                                 exit(1);
505                                         }
506                                 }
507                         }
508
509                         /****** if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->hprot_TPH_tileno[tilespec] == tileno)) */
510                         if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->hprot_TPH_tileno[tilespec] == acc_tpno))
511                                 /* we got a specification from this tile part onwards */
512                                 hprot = j2k->cp->hprot_TPH[tilespec++];
513                 
514                         /* must this TPH have an EPB MS? */
515                         if (j2k->cp->epb_on && (hprot > 0)) {
516
517                                 /* Create the EPB */
518                                 if ((epb_mark = jpwl_epb_create(
519                                         j2k, /* this encoder handle */
520                                         OPJ_FALSE, /* is it the latest? in TPH, no for now (if huge data size in TPH, we'd need more) */
521                                         OPJ_TRUE, /* is it packed? yes for now */
522                                         tileno, /* we are in TPH */
523                                         epb_index++, /* its index is 0 (first) */
524                                         hprot, /* protection type parameters of following data */
525                                         sot_len + 2, /* pre-data length: only SOT */
526                                         left_THmarks_len /* post-data length: from SOT end to SOD inclusive */
527                                         ))) {
528                                         
529                                         /* Add this marker to the 'insertanda' list */
530                                         if (jwmarker_num < JPWL_MAX_NO_MARKERS) {
531                                                 jwmarker[jwmarker_num].id = J2K_MS_EPB; /* its type */
532                                                 jwmarker[jwmarker_num].m.epbmark = epb_mark; /* the EPB */
533                                                 /****** jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].start_pos + sot_len + 2; */ /* after SOT */
534                                                 jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2; /* after SOT */
535                                                 jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos; /* first first first! */
536                                                 jwmarker[jwmarker_num].len = epb_mark->Lepb; /* its length */
537                                                 jwmarker[jwmarker_num].len_ready = OPJ_TRUE; /* ready */
538                                                 jwmarker[jwmarker_num].pos_ready = OPJ_TRUE; /* ready */
539                                                 jwmarker[jwmarker_num].parms_ready = OPJ_TRUE; /* ready */
540                                                 jwmarker[jwmarker_num].data_ready = OPJ_FALSE; /* not ready */
541                                                 jwmarker_num++;
542                                         }
543
544                                         /* update Psot of the tile  */
545                                         Psot += epb_mark->Lepb + 2;
546
547                                         opj_event_msg(j2k->cinfo, EVT_INFO,
548                                                 /***** "TPH EPB : tile %02d, prot. %d\n", */
549                                                 "TPH EPB : tile %02d, part %02d, prot. %d\n",
550                                                 /***** tileno, */
551                                                 tileno, tpno,
552                                                 hprot
553                                                 );
554
555                                         /* save this TPH EPB address */
556                                         tph_epb = epb_mark;
557
558                                 } else {
559                                         /* ooops, problems */
560                                         /****** opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH EPB #%d\n", tileno); */
561                                         opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH EPB in #%d,d\n", tileno, tpno);
562                                 };
563
564                         }                               
565                 
566                         startpack = 0;
567                         /* EPB MSs for UEP packet data protection in Tile Parts */
568                         /****** for (packno = 0; packno < j2k->cstr_info->num; packno++) { */
569                         /*first_tp_pack = (tpno > 0) ? (first_tp_pack + j2k->cstr_info->tile[tileno].tp[tpno - 1].tp_numpacks) : 0;*/
570                         first_tp_pack = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pack;
571                         last_tp_pack = first_tp_pack + j2k->cstr_info->tile[tileno].tp[tpno].tp_numpacks - 1;
572                         for (packno = 0; packno < j2k->cstr_info->tile[tileno].tp[tpno].tp_numpacks; packno++) {
573
574                                 /******** if ((packspec < JPWL_MAX_NO_PACKSPECS) &&
575                                         (j2k->cp->pprot_tileno[packspec] == tileno) && (j2k->cp->pprot_packno[packspec] == packno)) { */
576                                 if ((packspec < JPWL_MAX_NO_PACKSPECS) &&
577                                         (j2k->cp->pprot_tileno[packspec] == acc_tpno) && (j2k->cp->pprot_packno[packspec] == packno)) {
578
579                                         /* we got a specification from this tile and packet onwards */
580                                         /* print the previous spec */
581                                         if (packno > 0) {
582                                                 stoppack = packno - 1;                          
583                                                 opj_event_msg(j2k->cinfo, EVT_INFO,
584                                                         /***** "UEP EPBs: tile %02d, packs. %02d-%02d (B %d-%d), prot. %d\n", */
585                                                         "UEP EPBs: tile %02d, part %02d, packs. %02d-%02d (B %d-%d), prot. %d\n",
586                                                         /***** tileno, */
587                                                         tileno, tpno,
588                                                         startpack,
589                                                         stoppack,
590                                                         /***** j2k->cstr_info->tile[tileno].packet[startpack].start_pos, */
591                                                         j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos,
592                                                         /***** j2k->cstr_info->tile[tileno].packet[stoppack].end_pos, */
593                                                         j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos,
594                                                         pprot);
595
596                                                 /***** prot_len = j2k->cstr_info->tile[tileno].packet[stoppack].end_pos + 1 -
597                                                         j2k->cstr_info->tile[tileno].packet[startpack].start_pos; */
598                                                 prot_len = j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos + 1 -
599                                                         j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos;
600
601                                                 /*
602                                                   particular case: if this is the last header and the last packet,
603                                                   then it is better to protect even the EOC marker
604                                                 */
605                                                 /****** if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) &&
606                                                         (stoppack == (j2k->cstr_info->num - 1))) */
607                                                 if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) &&
608                                                         (tpno == (j2k->cstr_info->tile[tileno].num_tps - 1)) &&
609                                                         (stoppack == last_tp_pack))
610                                                         /* add the EOC len */
611                                                         prot_len += 2;
612
613                                                 /* let's add the EPBs */
614                                                 Psot += jpwl_epbs_add(
615                                                         j2k, /* J2K handle */
616                                                         jwmarker, /* pointer to JPWL markers list */
617                                                         &jwmarker_num, /* pointer to the number of current markers */
618                                                         OPJ_FALSE, /* latest */
619                                                         OPJ_TRUE, /* packed */
620                                                         OPJ_FALSE, /* inside MH */
621                                                         &epb_index, /* pointer to EPB index */
622                                                         pprot, /* protection type */
623                                                         /****** (double) (j2k->cstr_info->tile[tileno].start_pos + sot_len + 2) + 0.0001, */ /* position */
624                                                         (double) (j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2) + 0.0001, /* position */
625                                                         tileno, /* number of tile */
626                                                         0, /* length of pre-data */
627                                                         prot_len /*4000*/ /* length of post-data */
628                                                         );
629                                         }
630
631                                         startpack = packno;
632                                         pprot = j2k->cp->pprot[packspec++];
633                                 }
634
635                                 //printf("Tile %02d, pack %02d ==> %d\n", tileno, packno, pprot);
636                 
637                         }
638
639                         /* we are at the end: print the remaining spec */
640                         stoppack = packno - 1;
641                         if (pprot >= 0) {
642
643                                 opj_event_msg(j2k->cinfo, EVT_INFO,
644                                         /**** "UEP EPBs: tile %02d, packs. %02d-%02d (B %d-%d), prot. %d\n", */
645                                         "UEP EPBs: tile %02d, part %02d, packs. %02d-%02d (B %d-%d), prot. %d\n",
646                                         /**** tileno, */
647                                         tileno, tpno,
648                                         startpack,
649                                         stoppack,
650                                         /***** j2k->image_info->tile[tileno].packet[startpack].start_pos,
651                                         j2k->image_info->tile[tileno].packet[stoppack].end_pos, */
652                                         j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos,
653                                         j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos,
654                                         pprot);
655
656                                 /***** prot_len = j2k->cstr_info->tile[tileno].packet[stoppack].end_pos + 1 -
657                                         j2k->cstr_info->tile[tileno].packet[startpack].start_pos; */
658                                 prot_len = j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos + 1 -
659                                         j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos;
660
661                                 /*
662                                   particular case: if this is the last header and the last packet,
663                                   then it is better to protect even the EOC marker
664                                 */
665                                 /***** if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) &&
666                                         (stoppack == (j2k->cstr_info->num - 1))) */
667                                 if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) &&
668                                         (tpno == (j2k->cstr_info->tile[tileno].num_tps - 1)) &&
669                                         (stoppack == last_tp_pack))
670                                         /* add the EOC len */
671                                         prot_len += 2;
672
673                                 /* let's add the EPBs */
674                                 Psot += jpwl_epbs_add(
675                                                         j2k, /* J2K handle */
676                                                         jwmarker, /* pointer to JPWL markers list */
677                                                         &jwmarker_num, /* pointer to the number of current markers */
678                                                         OPJ_TRUE, /* latest */
679                                                         OPJ_TRUE, /* packed */
680                                                         OPJ_FALSE, /* inside MH */
681                                                         &epb_index, /* pointer to EPB index */
682                                                         pprot, /* protection type */
683                                                         /***** (double) (j2k->cstr_info->tile[tileno].start_pos + sot_len + 2) + 0.0001,*/ /* position */
684                                                         (double) (j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2) + 0.0001, /* position */
685                                                         tileno, /* number of tile */
686                                                         0, /* length of pre-data */
687                                                         prot_len /*4000*/ /* length of post-data */
688                                                         );
689                         }
690
691                         /* we can now check if the TPH EPB was really the last one */
692                         if (tph_epb && (epb_index == 1)) {
693                                 /* set the TPH EPB to be the last one in current header */
694                                 tph_epb->Depb |= (unsigned char) ((OPJ_TRUE & 0x0001) << 6);
695                                 tph_epb = NULL;
696                         }
697
698                         /* write back Psot */
699                         cio_seek(cio, Psotp);
700                         cio_write(cio, Psot, 4);
701                 
702                 }
703
704         };
705
706         /* reset the position */
707         cio_seek(cio, ciopos);
708
709 }
710
711 void jpwl_dump_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image) {
712
713         int mm;
714         unsigned long int old_size = j2k->cstr_info->codestream_size;
715         unsigned long int new_size = old_size;
716         int /*ciopos = cio_tell(cio),*/ soc_pos = j2k->cstr_info->main_head_start;
717         unsigned char *jpwl_buf, *orig_buf;
718         unsigned long int orig_pos;
719         double epbcoding_time = 0.0, esdcoding_time = 0.0;
720
721         /* Order JPWL markers according to their wishlist position */
722         qsort((void *) jwmarker, (size_t) jwmarker_num, sizeof (jpwl_marker_t), jpwl_markcomp);
723
724         /* compute markers total size */ 
725         for (mm = 0; mm < jwmarker_num; mm++) {
726                 /*printf("%x, %d, %.10f, %d long\n", jwmarker[mm].id, jwmarker[mm].pos,
727                         jwmarker[mm].dpos, jwmarker[mm].len);*/
728                 new_size += jwmarker[mm].len + 2;
729         }
730
731         /* allocate a new buffer of proper size */
732         if (!(jpwl_buf = (unsigned char *) opj_malloc((size_t) (new_size + soc_pos) * sizeof(unsigned char)))) {
733                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for JPWL codestream buffer\n");
734                 exit(1);
735         };
736
737         /* copy the jp2 part, if any */
738         orig_buf = jpwl_buf;
739         memcpy(jpwl_buf, cio->buffer, soc_pos);
740         jpwl_buf += soc_pos;
741
742         /* cycle through markers */
743         orig_pos = soc_pos + 0; /* start from the beginning */
744         cio_seek(cio, soc_pos + 0); /* rewind the original */
745         for (mm = 0; mm < jwmarker_num; mm++) {
746
747                 /*
748                 need to copy a piece of the original codestream
749                 if there is such
750                 */
751                 memcpy(jpwl_buf, cio_getbp(cio), jwmarker[mm].pos - orig_pos);
752                 jpwl_buf += jwmarker[mm].pos - orig_pos;
753                 orig_pos = jwmarker[mm].pos;
754                 cio_seek(cio, orig_pos);
755
756                 /*
757                 then write down the marker
758                 */
759                 switch (jwmarker[mm].id) {
760
761                 case J2K_MS_EPB:
762                         jpwl_epb_write(j2k, jwmarker[mm].m.epbmark, jpwl_buf);
763                         break;
764
765                 case J2K_MS_EPC:
766                         jpwl_epc_write(j2k, jwmarker[mm].m.epcmark, jpwl_buf);
767                         break;
768
769                 case J2K_MS_ESD:
770                         jpwl_esd_write(j2k, jwmarker[mm].m.esdmark, jpwl_buf);
771                         break;
772
773                 case J2K_MS_RED:
774                         memset(jpwl_buf, 0, jwmarker[mm].len + 2); /* placeholder */
775                         break;
776
777                 default:
778                         break;
779                 };
780
781                 /* we update the markers struct */
782                 if (j2k->cstr_info)
783                         j2k->cstr_info->marker[j2k->cstr_info->marknum - 1].pos = (jpwl_buf - orig_buf);
784                 
785                 /* we set the marker dpos to the new position in the JPWL codestream */
786                 jwmarker[mm].dpos = (double) (jpwl_buf - orig_buf);
787
788                 /* advance JPWL buffer position */
789                 jpwl_buf += jwmarker[mm].len + 2;
790
791         }
792
793         /* finish remaining original codestream */
794         memcpy(jpwl_buf, cio_getbp(cio), old_size - (orig_pos - soc_pos));
795         jpwl_buf += old_size - (orig_pos - soc_pos);
796         cio_seek(cio, soc_pos + old_size);
797         
798         /*
799         update info file based on added markers
800         */
801         if (!jpwl_update_info(j2k, jwmarker, jwmarker_num))
802                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not update OPJ cstr_info structure\n");
803
804         /* now we need to repass some markers and fill their data fields */
805         
806         /* first of all, DL and Pcrc in EPCs */ 
807         for (mm = 0; mm < jwmarker_num; mm++) {
808
809                 /* find the EPCs */
810                 if (jwmarker[mm].id == J2K_MS_EPC) {
811
812                         int epc_pos = (int) jwmarker[mm].dpos, pp;
813                         unsigned short int mycrc = 0x0000;
814
815                         /* fix and fill the DL field */
816                         jwmarker[mm].m.epcmark->DL = new_size;
817                         orig_buf[epc_pos + 6] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 24);
818                         orig_buf[epc_pos + 7] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 16);
819                         orig_buf[epc_pos + 8] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 8);
820                         orig_buf[epc_pos + 9] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 0);
821
822                         /* compute the CRC field (excluding itself) */
823                         for (pp = 0; pp < 4; pp++)
824                                 jpwl_updateCRC16(&mycrc, orig_buf[epc_pos + pp]);
825                         for (pp = 6; pp < (jwmarker[mm].len + 2); pp++)
826                                 jpwl_updateCRC16(&mycrc, orig_buf[epc_pos + pp]);
827
828                         /* fix and fill the CRC */
829                         jwmarker[mm].m.epcmark->Pcrc = mycrc;
830                         orig_buf[epc_pos + 4] = (unsigned char) (jwmarker[mm].m.epcmark->Pcrc >> 8);
831                         orig_buf[epc_pos + 5] = (unsigned char) (jwmarker[mm].m.epcmark->Pcrc >> 0);
832
833                 }
834         }
835
836         /* then, sensitivity data in ESDs */ 
837         esdcoding_time = opj_clock();
838         for (mm = 0; mm < jwmarker_num; mm++) {
839
840                 /* find the ESDs */
841                 if (jwmarker[mm].id == J2K_MS_ESD) {
842
843                         /* remember that they are now in a new position (dpos) */
844                         int esd_pos = (int) jwmarker[mm].dpos;
845
846                         jpwl_esd_fill(j2k, jwmarker[mm].m.esdmark, &orig_buf[esd_pos]);
847                 
848                 }
849
850         }
851         esdcoding_time = opj_clock() - esdcoding_time;
852         if (j2k->cp->esd_on)
853                 opj_event_msg(j2k->cinfo, EVT_INFO, "ESDs sensitivities computed in %f s\n", esdcoding_time);
854
855         /* finally, RS or CRC parity in EPBs */ 
856         epbcoding_time = opj_clock();
857         for (mm = 0; mm < jwmarker_num; mm++) {
858
859                 /* find the EPBs */
860                 if (jwmarker[mm].id == J2K_MS_EPB) {
861
862                         /* remember that they are now in a new position (dpos) */
863                         int nn, accum_len;
864
865                         /* let's see how many EPBs are following this one, included itself */
866                         /* for this to work, we suppose that the markers are correctly ordered */
867                         /* and, overall, that they are in packed mode inside headers */
868                         accum_len = 0;
869                         for (nn = mm; (nn < jwmarker_num) && (jwmarker[nn].id == J2K_MS_EPB) &&
870                                 (jwmarker[nn].pos == jwmarker[mm].pos); nn++)
871                                 accum_len += jwmarker[nn].m.epbmark->Lepb + 2;
872
873                         /* fill the current (first) EPB with post-data starting from the computed position */
874                         jpwl_epb_fill(j2k, jwmarker[mm].m.epbmark, &orig_buf[(int) jwmarker[mm].dpos],
875                                 &orig_buf[(int) jwmarker[mm].dpos + accum_len]);
876                 
877                         /* fill the remaining EPBs in the header with post-data starting from the last position */
878                         for (nn = mm + 1; (nn < jwmarker_num) && (jwmarker[nn].id == J2K_MS_EPB) &&
879                                 (jwmarker[nn].pos == jwmarker[mm].pos); nn++)
880                                 jpwl_epb_fill(j2k, jwmarker[nn].m.epbmark, &orig_buf[(int) jwmarker[nn].dpos], NULL);
881
882                         /* skip all the processed EPBs */
883                         mm = nn - 1;
884                 }
885
886         }
887         epbcoding_time = opj_clock() - epbcoding_time;
888         if (j2k->cp->epb_on)
889                 opj_event_msg(j2k->cinfo, EVT_INFO, "EPBs redundancy computed in %f s\n", epbcoding_time);
890
891         /* free original cio buffer and set it to the JPWL one */
892         opj_free(cio->buffer);
893         cio->cinfo = cio->cinfo; /* no change */
894         cio->openmode = cio->openmode; /* no change */
895         cio->buffer = orig_buf;
896         cio->length = new_size + soc_pos;
897         cio->start = cio->buffer;
898         cio->end = cio->buffer + cio->length;
899         cio->bp = cio->buffer;
900         cio_seek(cio, soc_pos + new_size);
901
902 }
903
904
905 void j2k_read_epc(opj_j2k_t *j2k) {
906         unsigned long int DL, Lepcp, Pcrcp, l;
907         unsigned short int Lepc, Pcrc = 0x0000;
908         unsigned char Pepc;     
909         opj_cio_t *cio = j2k->cio;
910         const char *ans1;
911
912         /* Simply read the EPC parameters */
913         Lepcp = cio_tell(cio);
914         Lepc = cio_read(cio, 2);
915         Pcrcp = cio_tell(cio);
916         cio_skip(cio, 2); /* Pcrc */
917         DL = cio_read(cio, 4);
918         Pepc = cio_read(cio, 1);
919
920         /* compute Pcrc */
921         cio_seek(cio, Lepcp - 2);
922
923                 /* Marker */
924                 jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); 
925                 jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); 
926
927                 /* Length */
928                 jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); 
929                 jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); 
930
931                 /* skip Pcrc */
932                 cio_skip(cio, 2);
933
934                 /* read all remaining */
935                 for (l = 4; l < Lepc; l++)
936                         jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); 
937
938                 /* check Pcrc with the result */
939                 cio_seek(cio, Pcrcp);
940                 ans1 = (Pcrc == (unsigned short int) cio_read(cio, 2)) ? "crc-ok" : "crc-ko";
941
942         /* now we write them to screen */
943         opj_event_msg(j2k->cinfo, EVT_INFO, 
944                 "EPC(%u,%d): %s, DL=%d%s %s %s\n",
945                 Lepcp - 2,
946                 Lepc,
947                 ans1,
948                 DL, /* data length this EPC is referring to */
949                 (Pepc & 0x10) ? ", esd" : "", /* ESD is present */
950                 (Pepc & 0x20) ? ", red" : "", /* RED is present */
951                 (Pepc & 0x40) ? ", epb" : ""); /* EPB is present */
952
953         cio_seek(cio, Lepcp + Lepc);  
954 }
955
956 void j2k_write_epc(opj_j2k_t *j2k) {
957
958         unsigned long int DL, Lepcp, Pcrcp, l;
959         unsigned short int Lepc, Pcrc;
960         unsigned char Pepc;     
961
962         opj_cio_t *cio = j2k->cio;
963
964         cio_write(cio, J2K_MS_EPC, 2);  /* EPC */
965         Lepcp = cio_tell(cio);
966         cio_skip(cio, 2);
967
968         /* CRC-16 word of the EPC */
969         Pcrc = 0x0000; /* initialize */
970         Pcrcp = cio_tell(cio);
971         cio_write(cio, Pcrc, 2); /* Pcrc placeholder*/
972
973         /* data length of the EPC protection domain */
974         DL = 0x00000000; /* we leave this set to 0, as if the information is not available */
975         cio_write(cio, DL, 4);   /* DL */
976
977         /* jpwl capabilities */
978         Pepc = 0x00;
979         cio_write(cio, Pepc, 1); /* Pepc */
980
981         /* ID section */
982         /* no ID's, as of now */
983
984         Lepc = (unsigned short) (cio_tell(cio) - Lepcp);
985         cio_seek(cio, Lepcp);
986         cio_write(cio, Lepc, 2); /* Lepc */
987
988         /* compute Pcrc */
989         cio_seek(cio, Lepcp - 2);
990
991                 /* Marker */
992                 jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); 
993                 jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); 
994
995                 /* Length */
996                 jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); 
997                 jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); 
998
999                 /* skip Pcrc */
1000                 cio_skip(cio, 2);
1001
1002                 /* read all remaining */
1003                 for (l = 4; l < Lepc; l++)
1004                         jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); 
1005
1006                 /* fill Pcrc with the result */
1007                 cio_seek(cio, Pcrcp);
1008                 cio_write(cio, Pcrc, 2);
1009
1010         cio_seek(cio, Lepcp + Lepc);
1011
1012         /* marker struct update */
1013         j2k_add_marker(j2k->cstr_info, J2K_MS_EPC, Lepcp - 2, Lepc + 2);
1014
1015 }
1016
1017 void j2k_read_epb(opj_j2k_t *j2k) {
1018         unsigned long int LDPepb, Pepb;
1019         unsigned short int Lepb;
1020         unsigned char Depb;
1021         char str1[25] = "";
1022         opj_bool status;
1023         static opj_bool first_in_tph = OPJ_TRUE;
1024         int type, pre_len, post_len;
1025         static unsigned char *redund = NULL;
1026         
1027         opj_cio_t *cio = j2k->cio;
1028
1029         /* B/W = 45, RGB = 51 */
1030         /*           SIZ   SIZ_FIELDS     SIZ_COMPS               FOLLOWING_MARKER */
1031         int skipnum = 2  +     38     + 3 * j2k->cp->exp_comps  +         2;
1032
1033         if (j2k->cp->correct) {
1034
1035                 /* go back to EPB marker value */
1036                 cio_seek(cio, cio_tell(cio) - 2);
1037
1038                 /* we need to understand where we are */
1039                 if (j2k->state == J2K_STATE_MH) {
1040                         /* we are in MH */
1041                         type = 0; /* MH */
1042                         pre_len = skipnum; /* SOC+SIZ */
1043                         post_len = -1; /* auto */
1044
1045                 } else if ((j2k->state == J2K_STATE_TPH) && first_in_tph) {
1046                         /* we are in TPH */
1047                         type = 1; /* TPH */
1048                         pre_len = 12; /* SOC+SIZ */
1049                         first_in_tph = OPJ_FALSE;
1050                         post_len = -1; /* auto */
1051
1052                 } else {
1053                         /* we are elsewhere */
1054                         type = 2; /* other */
1055                         pre_len = 0; /* nada */
1056                         post_len = -1; /* auto */
1057
1058                 }
1059
1060                 /* call EPB corrector */
1061                 /*printf("before %x, ", redund);*/
1062                 status = jpwl_epb_correct(j2k,      /* J2K decompressor handle */
1063                                                                   cio->bp,  /* pointer to EPB in codestream buffer */
1064                                                                   type,     /* EPB type: MH */
1065                                                                   pre_len,  /* length of pre-data */
1066                                                                   post_len, /* length of post-data: -1 means auto */
1067                                                                   NULL,     /* do everything auto */
1068                                                                   &redund
1069                                                                  );
1070                 /*printf("after %x\n", redund);*/
1071
1072                 /* Read the (possibly corrected) EPB parameters */
1073                 cio_skip(cio, 2);
1074                 Lepb = cio_read(cio, 2);
1075                 Depb = cio_read(cio, 1);
1076                 LDPepb = cio_read(cio, 4);
1077                 Pepb = cio_read(cio, 4);
1078
1079                 if (!status) {
1080
1081                         opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL correction could not be performed\n");
1082
1083                         /* advance to EPB endpoint */
1084                         cio_skip(cio, Lepb + 2);  
1085
1086                         return;
1087                 }
1088
1089                 /* last in current header? */
1090                 if (Depb & 0x40) {
1091                         redund = NULL; /* reset the pointer to L4 buffer */
1092                         first_in_tph = OPJ_TRUE;
1093                 }
1094
1095                 /* advance to EPB endpoint */
1096                 cio_skip(cio, Lepb - 11);  
1097
1098         } else {
1099
1100                 /* Simply read the EPB parameters */
1101                 Lepb = cio_read(cio, 2);
1102                 Depb = cio_read(cio, 1);
1103                 LDPepb = cio_read(cio, 4);
1104                 Pepb = cio_read(cio, 4);
1105
1106                 /* What does Pepb tells us about the protection method? */
1107                 if (((Pepb & 0xF0000000) >> 28) == 0)
1108                         sprintf(str1, "pred"); /* predefined */
1109                 else if (((Pepb & 0xF0000000) >> 28) == 1)
1110                         sprintf(str1, "crc-%lu", 16 * ((Pepb & 0x00000001) + 1)); /* CRC mode */
1111                 else if (((Pepb & 0xF0000000) >> 28) == 2)
1112                         sprintf(str1, "rs(%lu,32)", (Pepb & 0x0000FF00) >> 8); /* RS mode */
1113                 else if (Pepb == 0xFFFFFFFF)
1114                         sprintf(str1, "nometh"); /* RS mode */
1115                 else
1116                         sprintf(str1, "unknown"); /* unknown */
1117
1118                 /* Now we write them to screen */
1119                 opj_event_msg(j2k->cinfo, EVT_INFO,
1120                         "EPB(%d): (%sl, %sp, %u), %lu, %s\n",
1121                         cio_tell(cio) - 13,
1122                         (Depb & 0x40) ? "" : "n", /* latest EPB or not? */
1123                         (Depb & 0x80) ? "" : "n", /* packed or unpacked EPB? */
1124                         (Depb & 0x3F), /* EPB index value */
1125                         LDPepb, /*length of the data protected by the EPB */
1126                         str1); /* protection method */
1127
1128                 cio_skip(cio, Lepb - 11);  
1129         }
1130 }
1131
1132 void j2k_write_epb(opj_j2k_t *j2k) {
1133         unsigned long int LDPepb, Pepb, Lepbp;
1134         unsigned short int Lepb;
1135         unsigned char Depb;
1136
1137         opj_cio_t *cio = j2k->cio;
1138
1139         cio_write(cio, J2K_MS_EPB, 2);  /* EPB */
1140         Lepbp = cio_tell(cio);
1141         cio_skip(cio, 2);
1142
1143         /* EPB style */
1144         Depb = 0x00; /* test */
1145         cio_write(cio, Depb, 1);   /* Depb */
1146
1147         /* length of the data to be protected by this EPB */
1148         LDPepb = 0x00000000; /* test */
1149         cio_write(cio, LDPepb, 4);   /* LDPepb */
1150
1151         /* next error correction tool */
1152         Pepb = 0x00000000; /* test */
1153         cio_write(cio, Pepb, 4);   /* Pepb */
1154
1155         /* EPB data */
1156         /* no data, as of now */
1157
1158         Lepb = (unsigned short) (cio_tell(cio) - Lepbp);
1159         cio_seek(cio, Lepbp);
1160         cio_write(cio, Lepb, 2);                /* Lepb */
1161
1162         cio_seek(cio, Lepbp + Lepb);
1163
1164         /* marker struct update */
1165         j2k_add_marker(j2k->cstr_info, J2K_MS_EPB, Lepbp - 2, Lepb + 2);
1166 }
1167
1168 void j2k_read_esd(opj_j2k_t *j2k) {
1169         unsigned short int Lesd, Cesd;
1170         unsigned char Pesd;
1171
1172         int cesdsize = (j2k->image->numcomps >= 257) ? 2 : 1;
1173
1174         char str1[4][4] = {"p", "br", "pr", "res"};
1175         char str2[8][8] = {"res", "mse", "mse-r", "psnr", "psnr-i", "maxerr", "tse", "res"};
1176         
1177         opj_cio_t *cio = j2k->cio;
1178
1179         /* Simply read the ESD parameters */
1180         Lesd = cio_read(cio, 2);
1181         Cesd = cio_read(cio, cesdsize);
1182         Pesd = cio_read(cio, 1);
1183
1184         /* Now we write them to screen */
1185         opj_event_msg(j2k->cinfo, EVT_INFO,
1186                 "ESD(%d): c%d, %s, %s, %s, %s, %s\n",
1187                 cio_tell(cio) - (5 + cesdsize),
1188                 Cesd, /* component number for this ESD */
1189                 str1[(Pesd & (unsigned char) 0xC0) >> 6], /* addressing mode */
1190                 str2[(Pesd & (unsigned char) 0x38) >> 3], /* sensitivity type */
1191                 ((Pesd & (unsigned char) 0x04) >> 2) ? "2Bs" : "1Bs",
1192                 ((Pesd & (unsigned char) 0x02) >> 1) ? "4Ba" : "2Ba",
1193                 (Pesd & (unsigned char) 0x01) ? "avgc" : "");
1194
1195         cio_skip(cio, Lesd - (3 + cesdsize));  
1196 }
1197
1198 void j2k_read_red(opj_j2k_t *j2k) {
1199         unsigned short int Lred;
1200         unsigned char Pred;
1201         char str1[4][4] = {"p", "br", "pr", "res"};
1202         
1203         opj_cio_t *cio = j2k->cio;
1204
1205         /* Simply read the RED parameters */
1206         Lred = cio_read(cio, 2);
1207         Pred = cio_read(cio, 1);
1208
1209         /* Now we write them to screen */
1210         opj_event_msg(j2k->cinfo, EVT_INFO,
1211                 "RED(%d): %s, %dc, %s, %s\n",
1212                 cio_tell(cio) - 5,
1213                 str1[(Pred & (unsigned char) 0xC0) >> 6], /* addressing mode */
1214                 (Pred & (unsigned char) 0x38) >> 3, /* corruption level */
1215                 ((Pred & (unsigned char) 0x02) >> 1) ? "4Ba" : "2Ba", /* address range */
1216                 (Pred & (unsigned char) 0x01) ? "errs" : "free"); /* error free? */
1217
1218         cio_skip(cio, Lred - 3);  
1219 }
1220
1221 opj_bool jpwl_check_tile(opj_j2k_t *j2k, opj_tcd_t *tcd, int tileno) {
1222
1223 #ifdef oerhgierhgvhreit4u
1224         /*
1225            we navigate through the tile and find possible invalid parameters:
1226        this saves a lot of crashes!!!!!
1227          */
1228         int compno, resno, precno, /*layno,*/ bandno, blockno;
1229         int numprecincts, numblocks;
1230
1231         /* this is the selected tile */
1232         opj_tcd_tile_t *tile = &(tcd->tcd_image->tiles[tileno]);
1233
1234         /* will keep the component */
1235         opj_tcd_tilecomp_t *comp = NULL;
1236
1237         /* will keep the resolution */
1238         opj_tcd_resolution_t *res;
1239
1240         /* will keep the subband */
1241         opj_tcd_band_t *band; 
1242
1243         /* will keep the precinct */
1244         opj_tcd_precinct_t *prec; 
1245
1246         /* will keep the codeblock */
1247         opj_tcd_cblk_t *block;
1248
1249         /* check all tile components */
1250         for (compno = 0; compno < tile->numcomps; compno++) {
1251                 comp = &(tile->comps[compno]);
1252
1253                 /* check all component resolutions */
1254                 for (resno = 0; resno < comp->numresolutions; resno++) {
1255                         res = &(comp->resolutions[resno]);
1256                         numprecincts = res->pw * res->ph;
1257
1258                         /* check all the subbands */
1259                         for (bandno = 0; bandno < res->numbands; bandno++) {
1260                                 band = &(res->bands[bandno]);
1261
1262                                 /* check all the precincts */
1263                                 for (precno = 0; precno < numprecincts; precno++) {
1264                                         prec = &(band->precincts[precno]);
1265                                         numblocks = prec->ch * prec->cw;
1266
1267                                         /* check all the codeblocks */
1268                                         for (blockno = 0; blockno < numblocks; blockno++) {
1269                                                 block = &(prec->cblks[blockno]);
1270
1271                                                 /* x-origin is invalid */
1272                                                 if ((block->x0 < prec->x0) || (block->x0 > prec->x1)) {
1273                                                         opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
1274                                                                 "JPWL: wrong x-cord of block origin %d => x-prec is (%d, %d)\n",
1275                                                                 block->x0, prec->x0, prec->x1);
1276                                                         if (!JPWL_ASSUME || JPWL_ASSUME)
1277                                                                 return OPJ_FALSE;
1278                                                 };
1279                                         }
1280                                 }                               
1281                         }
1282                 }
1283         }
1284
1285 #endif
1286
1287         return OPJ_TRUE;
1288 }
1289
1290 /*@}*/
1291
1292 #endif /* USE_JPWL */
1293
1294
1295 #ifdef USE_JPSEC
1296
1297 /** @defgroup JPSEC JPSEC - JPEG-2000 Part 8 (JPSEC) codestream manager */
1298 /*@{*/
1299
1300
1301 /** @name Local static functions */
1302 /*@{*/
1303
1304 void j2k_read_sec(opj_j2k_t *j2k) {
1305         unsigned short int Lsec;
1306         
1307         opj_cio_t *cio = j2k->cio;
1308
1309         /* Simply read the SEC length */
1310         Lsec = cio_read(cio, 2);
1311
1312         /* Now we write them to screen */
1313         opj_event_msg(j2k->cinfo, EVT_INFO,
1314                 "SEC(%d)\n",
1315                 cio_tell(cio) - 2
1316                 );
1317
1318         cio_skip(cio, Lsec - 2);  
1319 }
1320
1321 void j2k_write_sec(opj_j2k_t *j2k) {
1322         unsigned short int Lsec = 24;
1323         int i;
1324
1325         opj_cio_t *cio = j2k->cio;
1326
1327         cio_write(cio, J2K_MS_SEC, 2);  /* SEC */
1328         cio_write(cio, Lsec, 2);
1329
1330         /* write dummy data */
1331         for (i = 0; i < Lsec - 2; i++)
1332                 cio_write(cio, 0, 1);
1333 }
1334
1335 void j2k_read_insec(opj_j2k_t *j2k) {
1336         unsigned short int Linsec;
1337         
1338         opj_cio_t *cio = j2k->cio;
1339
1340         /* Simply read the INSEC length */
1341         Linsec = cio_read(cio, 2);
1342
1343         /* Now we write them to screen */
1344         opj_event_msg(j2k->cinfo, EVT_INFO,
1345                 "INSEC(%d)\n",
1346                 cio_tell(cio) - 2
1347                 );
1348
1349         cio_skip(cio, Linsec - 2);  
1350 }
1351
1352
1353 /*@}*/
1354
1355 /*@}*/
1356
1357 #endif /* USE_JPSEC */
1358