WIP: update t1, t2, tcd to use same strut as in V2
[openjpeg.git] / libopenjpeg / t2.c
1 /*
2  * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
3  * Copyright (c) 2002-2007, Professor Benoit Macq
4  * Copyright (c) 2001-2003, David Janssens
5  * Copyright (c) 2002-2003, Yannick Verschueren
6  * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
7  * Copyright (c) 2005, Herve Drolon, FreeImage Team
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 /** @defgroup T2 T2 - Implementation of a tier-2 coding */
35 /*@{*/
36
37 /** @name Local static functions */
38 /*@{*/
39
40 static void t2_putcommacode(opj_bio_t *bio, int n);
41 static int t2_getcommacode(opj_bio_t *bio);
42 /**
43 Variable length code for signalling delta Zil (truncation point)
44 @param bio Bit Input/Output component
45 @param n delta Zil
46 */
47 static void t2_putnumpasses(opj_bio_t *bio, int n);
48 static int t2_getnumpasses(opj_bio_t *bio);
49 /**
50 Encode a packet of a tile to a destination buffer
51 @param tile Tile for which to write the packets
52 @param tcp Tile coding parameters
53 @param pi Packet identity
54 @param dest Destination buffer
55 @param len Length of the destination buffer
56 @param cstr_info Codestream information structure 
57 @param tileno Number of the tile encoded
58 @return 
59 */
60 static int t2_encode_packet(opj_tcd_tile_t *tile, opj_tcp_t *tcp, opj_pi_iterator_t *pi, unsigned char *dest, int len, opj_codestream_info_t *cstr_info, int tileno);
61 /**
62 @param cblk
63 @param index
64 @param cblksty
65 @param first
66 */
67 static void t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first);
68 /**
69 Decode a packet of a tile from a source buffer
70 @param t2 T2 handle
71 @param src Source buffer
72 @param len Length of the source buffer
73 @param tile Tile for which to write the packets
74 @param tcp Tile coding parameters
75 @param pi Packet identity
76 @param pack_info Packet information
77 @return 
78 */
79 static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_tile_t *tile, 
80                                                                                                                 opj_tcp_t *tcp, opj_pi_iterator_t *pi, opj_packet_info_t *pack_info);
81
82
83 /**
84 Decode a packet of a tile from a source buffer
85 @param t2 T2 handle
86 @param src Source buffer
87 @param len Length of the source buffer
88 @param tile Tile for which to write the packets
89 @param tcp Tile coding parameters
90 @param pi Packet identity
91 @return
92 */
93 static opj_bool t2_decode_packet_v2(
94                                                          opj_t2_v2_t* p_t2,
95                                                          opj_tcd_tile_v2_t *p_tile,
96                              opj_tcp_v2_t *p_tcp,
97                                                          opj_pi_iterator_t *p_pi,
98                                                          OPJ_BYTE *p_src,
99                                                          OPJ_UINT32 * p_data_read,
100                                                          OPJ_UINT32 p_max_length,
101                                                          opj_packet_info_t *p_pack_info);
102
103 static opj_bool t2_skip_packet(
104                                                          opj_t2_v2_t* p_t2,
105                                                          opj_tcd_tile_v2_t *p_tile,
106                              opj_tcp_v2_t *p_tcp,
107                                                          opj_pi_iterator_t *p_pi,
108                                                          OPJ_BYTE *p_src,
109                                                          OPJ_UINT32 * p_data_read,
110                                                          OPJ_UINT32 p_max_length,
111                                                          opj_packet_info_t *p_pack_info);
112
113 static opj_bool t2_read_packet_header(
114                                                          opj_t2_v2_t* p_t2,
115                                                          opj_tcd_tile_v2_t *p_tile,
116                              opj_tcp_v2_t *p_tcp,
117                                                          opj_pi_iterator_t *p_pi,
118                                                          opj_bool * p_is_data_present,
119                                                          OPJ_BYTE *p_src_data,
120                                                          OPJ_UINT32 * p_data_read,
121                                                          OPJ_UINT32 p_max_length,
122                                                          opj_packet_info_t *p_pack_info);
123
124 static opj_bool t2_read_packet_data(
125                                                          opj_t2_v2_t* p_t2,
126                                                          opj_tcd_tile_v2_t *p_tile,
127                                                          opj_pi_iterator_t *p_pi,
128                                                          OPJ_BYTE *p_src_data,
129                                                          OPJ_UINT32 * p_data_read,
130                                                          OPJ_UINT32 p_max_length,
131                                                          opj_packet_info_t *pack_info);
132
133 static opj_bool t2_skip_packet_data(
134                                                          opj_t2_v2_t* p_t2,
135                                                          opj_tcd_tile_v2_t *p_tile,
136                                                          opj_pi_iterator_t *p_pi,
137                                                          OPJ_UINT32 * p_data_read,
138                                                          OPJ_UINT32 p_max_length,
139                                                          opj_packet_info_t *pack_info);
140
141 /**
142 @param seg
143 @param cblksty
144 @param first
145 */
146 static opj_bool t2_init_seg_v2( opj_tcd_cblk_dec_v2_t* cblk,
147                                                                 OPJ_UINT32 index,
148                                                                 OPJ_UINT32 cblksty,
149                                                                 OPJ_UINT32 first);
150
151 /*@}*/
152
153 /*@}*/
154
155 /* ----------------------------------------------------------------------- */
156
157 /* #define RESTART 0x04 */
158
159 static void t2_putcommacode(opj_bio_t *bio, int n) {
160         while (--n >= 0) {
161                 bio_write(bio, 1, 1);
162         }
163         bio_write(bio, 0, 1);
164 }
165
166 static int t2_getcommacode(opj_bio_t *bio) {
167         int n;
168         for (n = 0; bio_read(bio, 1); n++) {
169                 ;
170         }
171         return n;
172 }
173
174 static void t2_putnumpasses(opj_bio_t *bio, int n) {
175         if (n == 1) {
176                 bio_write(bio, 0, 1);
177         } else if (n == 2) {
178                 bio_write(bio, 2, 2);
179         } else if (n <= 5) {
180                 bio_write(bio, 0xc | (n - 3), 4);
181         } else if (n <= 36) {
182                 bio_write(bio, 0x1e0 | (n - 6), 9);
183         } else if (n <= 164) {
184                 bio_write(bio, 0xff80 | (n - 37), 16);
185         }
186 }
187
188 static int t2_getnumpasses(opj_bio_t *bio) {
189         int n;
190         if (!bio_read(bio, 1))
191                 return 1;
192         if (!bio_read(bio, 1))
193                 return 2;
194         if ((n = bio_read(bio, 2)) != 3)
195                 return (3 + n);
196         if ((n = bio_read(bio, 5)) != 31)
197                 return (6 + n);
198         return (37 + bio_read(bio, 7));
199 }
200
201 static int t2_encode_packet(opj_tcd_tile_t * tile, opj_tcp_t * tcp, opj_pi_iterator_t *pi, unsigned char *dest, int length, opj_codestream_info_t *cstr_info, int tileno) {
202         int bandno, cblkno;
203         unsigned char *c = dest;
204
205         int compno = pi->compno;        /* component value */
206         int resno  = pi->resno;         /* resolution level value */
207         int precno = pi->precno;        /* precinct value */
208         int layno  = pi->layno;         /* quality layer value */
209
210         opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
211         opj_tcd_resolution_t *res = &tilec->resolutions[resno];
212         
213         opj_bio_t *bio = NULL;  /* BIO component */
214         
215         /* <SOP 0xff91> */
216         if (tcp->csty & J2K_CP_CSTY_SOP) {
217                 c[0] = 255;
218                 c[1] = 145;
219                 c[2] = 0;
220                 c[3] = 4;
221                 c[4] = (unsigned char)((tile->packno % 65536) / 256);
222                 c[5] = (unsigned char)((tile->packno % 65536) % 256);
223                 c += 6;
224         }
225         /* </SOP> */
226         
227         if (!layno) {
228                 for (bandno = 0; bandno < res->numbands; bandno++) {
229                         opj_tcd_band_t *band = &res->bands[bandno];
230                         opj_tcd_precinct_t *prc = &band->precincts[precno];
231                         tgt_reset(prc->incltree);
232                         tgt_reset(prc->imsbtree);
233                         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
234                                 opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno];
235                                 cblk->numpasses = 0;
236                                 tgt_setvalue(prc->imsbtree, cblkno, band->numbps - cblk->numbps);
237                         }
238                 }
239         }
240         
241         bio = bio_create();
242         bio_init_enc(bio, c, length);
243         bio_write(bio, 1, 1);           /* Empty header bit */
244         
245         /* Writing Packet header */
246         for (bandno = 0; bandno < res->numbands; bandno++) {
247                 opj_tcd_band_t *band = &res->bands[bandno];
248                 opj_tcd_precinct_t *prc = &band->precincts[precno];
249                 for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
250                         opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno];
251                         opj_tcd_layer_t *layer = &cblk->layers[layno];
252                         if (!cblk->numpasses && layer->numpasses) {
253                                 tgt_setvalue(prc->incltree, cblkno, layno);
254                         }
255                 }
256                 for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
257                         opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno];
258                         opj_tcd_layer_t *layer = &cblk->layers[layno];
259                         int increment = 0;
260                         int nump = 0;
261                         int len = 0, passno;
262                         /* cblk inclusion bits */
263                         if (!cblk->numpasses) {
264                                 tgt_encode(bio, prc->incltree, cblkno, layno + 1);
265                         } else {
266                                 bio_write(bio, layer->numpasses != 0, 1);
267                         }
268                         /* if cblk not included, go to the next cblk  */
269                         if (!layer->numpasses) {
270                                 continue;
271                         }
272                         /* if first instance of cblk --> zero bit-planes information */
273                         if (!cblk->numpasses) {
274                                 cblk->numlenbits = 3;
275                                 tgt_encode(bio, prc->imsbtree, cblkno, 999);
276                         }
277                         /* number of coding passes included */
278                         t2_putnumpasses(bio, layer->numpasses);
279                         
280                         /* computation of the increase of the length indicator and insertion in the header     */
281                         for (passno = cblk->numpasses; passno < cblk->numpasses + layer->numpasses; passno++) {
282                                 opj_tcd_pass_t *pass = &cblk->passes[passno];
283                                 nump++;
284                                 len += pass->len;
285                                 if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
286                                         increment = int_max(increment, int_floorlog2(len) + 1 - (cblk->numlenbits + int_floorlog2(nump)));
287                                         len = 0;
288                                         nump = 0;
289                                 }
290                         }
291                         t2_putcommacode(bio, increment);
292
293                         /* computation of the new Length indicator */
294                         cblk->numlenbits += increment;
295
296                         /* insertion of the codeword segment length */
297                         for (passno = cblk->numpasses; passno < cblk->numpasses + layer->numpasses; passno++) {
298                                 opj_tcd_pass_t *pass = &cblk->passes[passno];
299                                 nump++;
300                                 len += pass->len;
301                                 if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
302                                         bio_write(bio, len, cblk->numlenbits + int_floorlog2(nump));
303                                         len = 0;
304                                         nump = 0;
305                                 }
306                         }
307                 }
308         }
309
310         if (bio_flush(bio)) {
311                 bio_destroy(bio);
312                 return -999;            /* modified to eliminate longjmp !! */
313         }
314
315         c += bio_numbytes(bio);
316         bio_destroy(bio);
317         
318         /* <EPH 0xff92> */
319         if (tcp->csty & J2K_CP_CSTY_EPH) {
320                 c[0] = 255;
321                 c[1] = 146;
322                 c += 2;
323         }
324         /* </EPH> */
325
326         /* << INDEX */
327         // End of packet header position. Currently only represents the distance to start of packet
328         // Will be updated later by incrementing with packet start value
329         if(cstr_info && cstr_info->index_write) {
330                 opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno];
331                 info_PK->end_ph_pos = (int)(c - dest);
332         }
333         /* INDEX >> */
334         
335         /* Writing the packet body */
336         
337         for (bandno = 0; bandno < res->numbands; bandno++) {
338                 opj_tcd_band_t *band = &res->bands[bandno];
339                 opj_tcd_precinct_t *prc = &band->precincts[precno];
340                 for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
341                         opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno];
342                         opj_tcd_layer_t *layer = &cblk->layers[layno];
343                         if (!layer->numpasses) {
344                                 continue;
345                         }
346                         if (c + layer->len > dest + length) {
347                                 return -999;
348                         }
349                         
350                         memcpy(c, layer->data, layer->len);
351                         cblk->numpasses += layer->numpasses;
352                         c += layer->len;
353                         /* << INDEX */ 
354                         if(cstr_info && cstr_info->index_write) {
355                                 opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno];
356                                 info_PK->disto += layer->disto;
357                                 if (cstr_info->D_max < info_PK->disto) {
358                                         cstr_info->D_max = info_PK->disto;
359                                 }
360                         }
361                         /* INDEX >> */
362                 }
363         }
364         
365         return (c - dest);
366 }
367
368 static void t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first) {
369         opj_tcd_seg_t* seg;
370         cblk->segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs, (index + 1) * sizeof(opj_tcd_seg_t));
371         seg = &cblk->segs[index];
372         seg->data = NULL;
373         seg->dataindex = 0;
374         seg->numpasses = 0;
375         seg->len = 0;
376         if (cblksty & J2K_CCP_CBLKSTY_TERMALL) {
377                 seg->maxpasses = 1;
378         }
379         else if (cblksty & J2K_CCP_CBLKSTY_LAZY) {
380                 if (first) {
381                         seg->maxpasses = 10;
382                 } else {
383                         seg->maxpasses = (((seg - 1)->maxpasses == 1) || ((seg - 1)->maxpasses == 10)) ? 2 : 1;
384                 }
385         } else {
386                 seg->maxpasses = 109;
387         }
388 }
389
390 static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_tile_t *tile, 
391                                                                                                                 opj_tcp_t *tcp, opj_pi_iterator_t *pi, opj_packet_info_t *pack_info) {
392         int bandno, cblkno;
393         unsigned char *c = src;
394
395         opj_cp_t *cp = t2->cp;
396
397         int compno = pi->compno;        /* component value */
398         int resno  = pi->resno;         /* resolution level value */
399         int precno = pi->precno;        /* precinct value */
400         int layno  = pi->layno;         /* quality layer value */
401
402         opj_tcd_resolution_t* res = &tile->comps[compno].resolutions[resno];
403
404         unsigned char *hd = NULL;
405         int present;
406         
407         opj_bio_t *bio = NULL;  /* BIO component */
408         
409         if (layno == 0) {
410                 for (bandno = 0; bandno < res->numbands; bandno++) {
411                         opj_tcd_band_t *band = &res->bands[bandno];
412                         opj_tcd_precinct_t *prc = &band->precincts[precno];
413                         
414                         if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)) continue;
415                         
416                         tgt_reset(prc->incltree);
417                         tgt_reset(prc->imsbtree);
418                         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
419                                 opj_tcd_cblk_dec_t* cblk = &prc->cblks.dec[cblkno];
420                                 cblk->numsegs = 0;
421                         }
422                 }
423         }
424         
425         /* SOP markers */
426         
427         if (tcp->csty & J2K_CP_CSTY_SOP) {
428                 if ((*c) != 0xff || (*(c + 1) != 0x91)) {
429                         opj_event_msg(t2->cinfo, EVT_WARNING, "Expected SOP marker\n");
430                 } else {
431                         c += 6;
432                 }
433                 
434                 /** TODO : check the Nsop value */
435         }
436         
437         /* 
438         When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
439         This part deal with this caracteristic
440         step 1: Read packet header in the saved structure
441         step 2: Return to codestream for decoding 
442         */
443
444         bio = bio_create();
445         
446         if (cp->ppm == 1) {             /* PPM */
447                 hd = cp->ppm_data;
448                 bio_init_dec(bio, hd, cp->ppm_len);
449         } else if (tcp->ppt == 1) {     /* PPT */
450                 hd = tcp->ppt_data;
451                 bio_init_dec(bio, hd, tcp->ppt_len);
452         } else {                        /* Normal Case */
453                 hd = c;
454                 bio_init_dec(bio, hd, src+len-hd);
455         }
456         
457         present = bio_read(bio, 1);
458         
459         if (!present) {
460                 bio_inalign(bio);
461                 hd += bio_numbytes(bio);
462                 bio_destroy(bio);
463                 
464                 /* EPH markers */
465                 
466                 if (tcp->csty & J2K_CP_CSTY_EPH) {
467                         if ((*hd) != 0xff || (*(hd + 1) != 0x92)) {
468                                 printf("Error : expected EPH marker\n");
469                         } else {
470                                 hd += 2;
471                         }
472                 }
473
474                 /* << INDEX */
475                 // End of packet header position. Currently only represents the distance to start of packet
476                 // Will be updated later by incrementing with packet start value
477                 if(pack_info) {
478                         pack_info->end_ph_pos = (int)(c - src);
479                 }
480                 /* INDEX >> */
481                 
482                 if (cp->ppm == 1) {             /* PPM case */
483                         cp->ppm_len += cp->ppm_data-hd;
484                         cp->ppm_data = hd;
485                         return (c - src);
486                 }
487                 if (tcp->ppt == 1) {    /* PPT case */
488                         tcp->ppt_len+=tcp->ppt_data-hd;
489                         tcp->ppt_data = hd;
490                         return (c - src);
491                 }
492                 
493                 return (hd - src);
494         }
495         
496         for (bandno = 0; bandno < res->numbands; bandno++) {
497                 opj_tcd_band_t *band = &res->bands[bandno];
498                 opj_tcd_precinct_t *prc = &band->precincts[precno];
499                 
500                 if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)) continue;
501                 
502                 for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
503                         int included, increment, n, segno;
504                         opj_tcd_cblk_dec_t* cblk = &prc->cblks.dec[cblkno];
505                         /* if cblk not yet included before --> inclusion tagtree */
506                         if (!cblk->numsegs) {
507                                 included = tgt_decode(bio, prc->incltree, cblkno, layno + 1);
508                                 /* else one bit */
509                         } else {
510                                 included = bio_read(bio, 1);
511                         }
512                         /* if cblk not included */
513                         if (!included) {
514                                 cblk->numnewpasses = 0;
515                                 continue;
516                         }
517                         /* if cblk not yet included --> zero-bitplane tagtree */
518                         if (!cblk->numsegs) {
519                                 int i, numimsbs;
520                                 for (i = 0; !tgt_decode(bio, prc->imsbtree, cblkno, i); i++) {
521                                         ;
522                                 }
523                                 numimsbs = i - 1;
524                                 cblk->numbps = band->numbps - numimsbs;
525                                 cblk->numlenbits = 3;
526                         }
527                         /* number of coding passes */
528                         cblk->numnewpasses = t2_getnumpasses(bio);
529                         increment = t2_getcommacode(bio);
530                         /* length indicator increment */
531                         cblk->numlenbits += increment;
532                         segno = 0;
533                         if (!cblk->numsegs) {
534                                 t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 1);
535                         } else {
536                                 segno = cblk->numsegs - 1;
537                                 if (cblk->segs[segno].numpasses == cblk->segs[segno].maxpasses) {
538                                         ++segno;
539                                         t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0);
540                                 }
541                         }
542                         n = cblk->numnewpasses;
543                         
544                         do {
545                                 cblk->segs[segno].numnewpasses = int_min(cblk->segs[segno].maxpasses - cblk->segs[segno].numpasses, n);
546                                 cblk->segs[segno].newlen = bio_read(bio, cblk->numlenbits + int_floorlog2(cblk->segs[segno].numnewpasses));
547                                 n -= cblk->segs[segno].numnewpasses;
548                                 if (n > 0) {
549                                         ++segno;
550                                         t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0);
551                                 }
552                         } while (n > 0);
553                 }
554         }
555         
556         if (bio_inalign(bio)) {
557                 bio_destroy(bio);
558                 return -999;
559         }
560         
561         hd += bio_numbytes(bio);
562         bio_destroy(bio);
563         
564         /* EPH markers */
565         if (tcp->csty & J2K_CP_CSTY_EPH) {
566                 if ((*hd) != 0xff || (*(hd + 1) != 0x92)) {
567                         opj_event_msg(t2->cinfo, EVT_ERROR, "Expected EPH marker\n");
568                         return -999;
569                 } else {
570                         hd += 2;
571                 }
572         }
573
574         /* << INDEX */
575         // End of packet header position. Currently only represents the distance to start of packet
576         // Will be updated later by incrementing with packet start value
577         if(pack_info) {
578                 pack_info->end_ph_pos = (int)(hd - src);
579         }
580         /* INDEX >> */
581         
582         if (cp->ppm==1) {
583                 cp->ppm_len+=cp->ppm_data-hd;
584                 cp->ppm_data = hd;
585         } else if (tcp->ppt == 1) {
586                 tcp->ppt_len+=tcp->ppt_data-hd;
587                 tcp->ppt_data = hd;
588         } else {
589                 c=hd;
590         }
591         
592         for (bandno = 0; bandno < res->numbands; bandno++) {
593                 opj_tcd_band_t *band = &res->bands[bandno];
594                 opj_tcd_precinct_t *prc = &band->precincts[precno];
595                 
596                 if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)) continue;
597                 
598                 for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
599                         opj_tcd_cblk_dec_t* cblk = &prc->cblks.dec[cblkno];
600                         opj_tcd_seg_t *seg = NULL;
601                         if (!cblk->numnewpasses)
602                                 continue;
603                         if (!cblk->numsegs) {
604                                 seg = &cblk->segs[0];
605                                 cblk->numsegs++;
606                                 cblk->len = 0;
607                         } else {
608                                 seg = &cblk->segs[cblk->numsegs - 1];
609                                 if (seg->numpasses == seg->maxpasses) {
610                                         seg++;
611                                         cblk->numsegs++;
612                                 }
613                         }
614                         
615                         do {
616                                 if (c + seg->newlen > src + len) {
617                                         return -999;
618                                 }
619
620 #ifdef USE_JPWL
621                         /* we need here a j2k handle to verify if making a check to
622                         the validity of cblocks parameters is selected from user (-W) */
623
624                                 /* let's check that we are not exceeding */
625                                 if ((cblk->len + seg->newlen) > 8192) {
626                                         opj_event_msg(t2->cinfo, EVT_WARNING,
627                                                 "JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
628                                                 seg->newlen, cblkno, precno, bandno, resno, compno);
629                                         if (!JPWL_ASSUME) {
630                                                 opj_event_msg(t2->cinfo, EVT_ERROR, "JPWL: giving up\n");
631                                                 return -999;
632                                         }
633                                         seg->newlen = 8192 - cblk->len;
634                                         opj_event_msg(t2->cinfo, EVT_WARNING, "      - truncating segment to %d\n", seg->newlen);
635                                         break;
636                                 };
637
638 #endif /* USE_JPWL */
639                                 
640                                 cblk->data = (unsigned char*) opj_realloc(cblk->data, (cblk->len + seg->newlen) * sizeof(unsigned char*));
641                                 memcpy(cblk->data + cblk->len, c, seg->newlen);
642                                 if (seg->numpasses == 0) {
643                                         seg->data = &cblk->data;
644                                         seg->dataindex = cblk->len;
645                                 }
646                                 c += seg->newlen;
647                                 cblk->len += seg->newlen;
648                                 seg->len += seg->newlen;
649                                 seg->numpasses += seg->numnewpasses;
650                                 cblk->numnewpasses -= seg->numnewpasses;
651                                 if (cblk->numnewpasses > 0) {
652                                         seg++;
653                                         cblk->numsegs++;
654                                 }
655                         } while (cblk->numnewpasses > 0);
656                 }
657         }
658         
659         return (c - src);
660 }
661
662 /* ----------------------------------------------------------------------- */
663
664 int t2_encode_packets(opj_t2_t* t2,int tileno, opj_tcd_tile_t *tile, int maxlayers, unsigned char *dest, int len, opj_codestream_info_t *cstr_info,int tpnum, int tppos,int pino, J2K_T2_MODE t2_mode, int cur_totnum_tp){
665         unsigned char *c = dest;
666         int e = 0;
667         int compno;
668         opj_pi_iterator_t *pi = NULL;
669         int poc;
670         opj_image_t *image = t2->image;
671         opj_cp_t *cp = t2->cp;
672         opj_tcp_t *tcp = &cp->tcps[tileno];
673         int pocno = cp->cinema == CINEMA4K_24? 2: 1;
674         int maxcomp = cp->max_comp_size > 0 ? image->numcomps : 1;
675         
676         pi = pi_initialise_encode(image, cp, tileno, t2_mode);
677         if(!pi) {
678                 /* TODO: throw an error */
679                 return -999;
680         }
681         
682         if(t2_mode == THRESH_CALC ){ /* Calculating threshold */
683                 for(compno = 0; compno < maxcomp; compno++ ){
684                         for(poc = 0; poc < pocno ; poc++){
685                                 int comp_len = 0;
686                                 int tpnum = compno;
687                                 if (pi_create_encode(pi, cp,tileno,poc,tpnum,tppos,t2_mode,cur_totnum_tp)) {
688                                         opj_event_msg(t2->cinfo, EVT_ERROR, "Error initializing Packet Iterator\n");
689                                         pi_destroy(pi, cp, tileno);
690                                         return -999;
691                                 }
692                                 while (pi_next(&pi[poc])) {
693                                         if (pi[poc].layno < maxlayers) {
694                                                 e = t2_encode_packet(tile, &cp->tcps[tileno], &pi[poc], c, dest + len - c, cstr_info, tileno);
695                                                 comp_len = comp_len + e;
696                                                 if (e == -999) {
697                                                         break;
698                                                 } else {
699                                                         c += e;
700                                                 }
701                                         }
702                                 }
703                                 if (e == -999) break;
704                                 if (cp->max_comp_size){
705                                         if (comp_len > cp->max_comp_size){
706                                                 e = -999;
707                                                 break;
708                                         }
709                                 }
710                         }
711                         if (e == -999)  break;
712                 }
713         }else{  /* t2_mode == FINAL_PASS  */
714                 pi_create_encode(pi, cp,tileno,pino,tpnum,tppos,t2_mode,cur_totnum_tp);
715                 while (pi_next(&pi[pino])) {
716                         if (pi[pino].layno < maxlayers) {
717                                 e = t2_encode_packet(tile, &cp->tcps[tileno], &pi[pino], c, dest + len - c, cstr_info, tileno);
718                                 if (e == -999) {
719                                         break;
720                                 } else {
721                                         c += e;
722                                 }
723                                 /* INDEX >> */
724                                 if(cstr_info) {
725                                         if(cstr_info->index_write) {
726                                                 opj_tile_info_t *info_TL = &cstr_info->tile[tileno];
727                                                 opj_packet_info_t *info_PK = &info_TL->packet[cstr_info->packno];
728                                                 if (!cstr_info->packno) {
729                                                         info_PK->start_pos = info_TL->end_header + 1;
730                                                 } else {
731                                                         info_PK->start_pos = ((cp->tp_on | tcp->POC)&& info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[cstr_info->packno - 1].end_pos + 1;
732                                                 }
733                                                 info_PK->end_pos = info_PK->start_pos + e - 1;
734                                                 info_PK->end_ph_pos += info_PK->start_pos - 1;  // End of packet header which now only represents the distance 
735                                                                                                                                                                                                                                                 // to start of packet is incremented by value of start of packet
736                                         }
737                                         
738                                         cstr_info->packno++;
739                                 }
740                                 /* << INDEX */
741                                 tile->packno++;
742                         }
743                 }
744         }
745         
746         pi_destroy(pi, cp, tileno);
747         
748         if (e == -999) {
749                 return e;
750         }
751         
752   return (c - dest);
753 }
754
755 int t2_decode_packets(opj_t2_t *t2, unsigned char *src, int len, int tileno, opj_tcd_tile_t *tile, opj_codestream_info_t *cstr_info) {
756         unsigned char *c = src;
757         opj_pi_iterator_t *pi;
758         int pino, e = 0;
759         int n = 0, curtp = 0;
760         int tp_start_packno;
761
762         opj_image_t *image = t2->image;
763         opj_cp_t *cp = t2->cp;
764         
765         /* create a packet iterator */
766         pi = pi_create_decode(image, cp, tileno);
767         if(!pi) {
768                 /* TODO: throw an error */
769                 return -999;
770         }
771
772         tp_start_packno = 0;
773         
774         for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++) {
775                 while (pi_next(&pi[pino])) {
776                         if ((cp->layer==0) || (cp->layer>=((pi[pino].layno)+1))) {
777                                 opj_packet_info_t *pack_info;
778                                 if (cstr_info)
779                                         pack_info = &cstr_info->tile[tileno].packet[cstr_info->packno];
780                                 else
781                                         pack_info = NULL;
782                                 e = t2_decode_packet(t2, c, src + len - c, tile, &cp->tcps[tileno], &pi[pino], pack_info);
783                         } else {
784                                 e = 0;
785                         }
786                         if(e == -999) return -999;
787                         /* progression in resolution */
788                         image->comps[pi[pino].compno].resno_decoded =   
789                                 (e > 0) ? 
790                                 int_max(pi[pino].resno, image->comps[pi[pino].compno].resno_decoded) 
791                                 : image->comps[pi[pino].compno].resno_decoded;
792                         n++;
793
794                         /* INDEX >> */
795                         if(cstr_info) {
796                                 opj_tile_info_t *info_TL = &cstr_info->tile[tileno];
797                                 opj_packet_info_t *info_PK = &info_TL->packet[cstr_info->packno];
798                                 if (!cstr_info->packno) {
799                                         info_PK->start_pos = info_TL->end_header + 1;
800                                 } else if (info_TL->packet[cstr_info->packno-1].end_pos >= (int)cstr_info->tile[tileno].tp[curtp].tp_end_pos){ // New tile part
801                                         info_TL->tp[curtp].tp_numpacks = cstr_info->packno - tp_start_packno; // Number of packets in previous tile-part
802           info_TL->tp[curtp].tp_start_pack = tp_start_packno;
803                                         tp_start_packno = cstr_info->packno;
804                                         curtp++;
805                                         info_PK->start_pos = cstr_info->tile[tileno].tp[curtp].tp_end_header+1;
806                                 } else {
807                                         info_PK->start_pos = (cp->tp_on && info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[cstr_info->packno - 1].end_pos + 1;
808                                 }
809                                 info_PK->end_pos = info_PK->start_pos + e - 1;
810                                 info_PK->end_ph_pos += info_PK->start_pos - 1;  // End of packet header which now only represents the distance 
811                                                                                                                                                                                                                                 // to start of packet is incremented by value of start of packet
812                                 cstr_info->packno++;
813                         }
814                         /* << INDEX */
815                         
816                         if (e == -999) {                /* ADD */
817                                 break;
818                         } else {
819                                 c += e;
820                         }                       
821                 }
822         }
823         /* INDEX >> */
824         if(cstr_info) {
825                 cstr_info->tile[tileno].tp[curtp].tp_numpacks = cstr_info->packno - tp_start_packno; // Number of packets in last tile-part
826     cstr_info->tile[tileno].tp[curtp].tp_start_pack = tp_start_packno;
827         }
828         /* << INDEX */
829
830         /* don't forget to release pi */
831         pi_destroy(pi, cp, tileno);
832         
833         if (e == -999) {
834                 return e;
835         }
836         
837         return (c - src);
838 }
839
840 opj_bool t2_decode_packets_v2(
841                                                 opj_t2_v2_t *p_t2,
842                                                 OPJ_UINT32 p_tile_no,
843                                                 struct opj_tcd_tile_v2 *p_tile,
844                                                 OPJ_BYTE *p_src,
845                                                 OPJ_UINT32 * p_data_read,
846                                                 OPJ_UINT32 p_max_len,
847                                                 struct opj_codestream_info_v2 *p_cstr_info)
848 {
849         OPJ_BYTE *l_current_data = p_src;
850         opj_pi_iterator_t *l_pi = 00;
851         OPJ_UINT32 pino;
852         opj_image_header_t *l_image = p_t2->image;
853         opj_cp_v2_t *l_cp = p_t2->cp;
854         opj_cp_v2_t *cp = p_t2->cp;
855         opj_tcp_v2_t *l_tcp = &(p_t2->cp->tcps[p_tile_no]);
856         OPJ_UINT32 l_nb_bytes_read;
857         OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;
858         opj_pi_iterator_t *l_current_pi = 00;
859         OPJ_UINT32 curtp = 0;
860         OPJ_UINT32 tp_start_packno;
861         opj_packet_info_t *l_pack_info = 00;
862         opj_image_comp_header_t* l_img_comp = 00;
863
864
865         if (p_cstr_info) {
866                 l_pack_info = p_cstr_info->tile[p_tile_no].packet;
867         }
868
869         /* create a packet iterator */
870         l_pi = pi_create_decode_v2(l_image, l_cp, p_tile_no);
871         if (!l_pi) {
872                 return OPJ_FALSE;
873         }
874
875         tp_start_packno = 0;
876         l_current_pi = l_pi;
877
878         for     (pino = 0; pino <= l_tcp->numpocs; ++pino) {
879
880                 while (pi_next(l_current_pi)) {
881
882                         if (l_tcp->num_layers_to_decode > l_current_pi->layno
883                                         && l_current_pi->resno < p_tile->comps[l_current_pi->compno].minimum_num_resolutions) {
884                                 l_nb_bytes_read = 0;
885
886                                 if (! t2_decode_packet_v2(p_t2,p_tile,l_tcp,l_current_pi,l_current_data,&l_nb_bytes_read,p_max_len,l_pack_info)) {
887                                         pi_destroy_v2(l_pi,l_nb_pocs);
888                                         return OPJ_FALSE;
889                                 }
890
891                                 l_img_comp = &(l_image->comps[l_current_pi->compno]);
892                                 l_img_comp->resno_decoded = uint_max(l_current_pi->resno, l_img_comp->resno_decoded);
893                         }
894                         else {
895                                 l_nb_bytes_read = 0;
896                                 if (! t2_skip_packet(p_t2,p_tile,l_tcp,l_current_pi,l_current_data,&l_nb_bytes_read,p_max_len,l_pack_info)) {
897                                         pi_destroy_v2(l_pi,l_nb_pocs);
898                                         return OPJ_FALSE;
899                                 }
900                         }
901
902                         l_current_data += l_nb_bytes_read;
903                         p_max_len -= l_nb_bytes_read;
904
905                         /* INDEX >> */
906                         if(p_cstr_info) {
907                                 opj_tile_info_v2_t *info_TL = &p_cstr_info->tile[p_tile_no];
908                                 opj_packet_info_t *info_PK = &info_TL->packet[p_cstr_info->packno];
909                                 if (!p_cstr_info->packno) {
910                                         info_PK->start_pos = info_TL->end_header + 1;
911                                 } else if (info_TL->packet[p_cstr_info->packno-1].end_pos >= (OPJ_INT32)p_cstr_info->tile[p_tile_no].tp[curtp].tp_end_pos){ // New tile part
912                                         info_TL->tp[curtp].tp_numpacks = p_cstr_info->packno - tp_start_packno; // Number of packets in previous tile-part
913                                         tp_start_packno = p_cstr_info->packno;
914                                         curtp++;
915                                         info_PK->start_pos = p_cstr_info->tile[p_tile_no].tp[curtp].tp_end_header+1;
916                                 } else {
917                                         info_PK->start_pos = (cp->m_specific_param.m_enc.m_tp_on && info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[p_cstr_info->packno - 1].end_pos + 1;
918                                 }
919                                 info_PK->end_pos = info_PK->start_pos + l_nb_bytes_read - 1;
920                                 info_PK->end_ph_pos += info_PK->start_pos - 1;  // End of packet header which now only represents the distance
921                                 ++p_cstr_info->packno;
922                         }
923                         /* << INDEX */
924                 }
925                 ++l_current_pi;
926         }
927         /* INDEX >> */
928         if
929                 (p_cstr_info) {
930                 p_cstr_info->tile[p_tile_no].tp[curtp].tp_numpacks = p_cstr_info->packno - tp_start_packno; // Number of packets in last tile-part
931         }
932         /* << INDEX */
933
934         /* don't forget to release pi */
935         pi_destroy_v2(l_pi,l_nb_pocs);
936         *p_data_read = l_current_data - p_src;
937         return OPJ_TRUE;
938 }
939
940 /* ----------------------------------------------------------------------- */
941
942 opj_t2_t* t2_create(opj_common_ptr cinfo, opj_image_t *image, opj_cp_t *cp) {
943         /* create the tcd structure */
944         opj_t2_t *t2 = (opj_t2_t*)opj_malloc(sizeof(opj_t2_t));
945         if(!t2) return NULL;
946         t2->cinfo = cinfo;
947         t2->image = image;
948         t2->cp = cp;
949
950         return t2;
951 }
952
953 /**
954  * Creates a Tier 2 handle
955  *
956  * @param       p_image         Source or destination image
957  * @param       p_cp            Image coding parameters.
958  * @return              a new T2 handle if successful, NULL otherwise.
959 */
960 opj_t2_v2_t* t2_create_v2(
961                                         opj_image_header_t *p_image,
962                                         opj_cp_v2_t *p_cp)
963 {
964         /* create the tcd structure */
965         opj_t2_v2_t *l_t2 = (opj_t2_v2_t*)opj_malloc(sizeof(opj_t2_v2_t));
966         if
967                 (!l_t2)
968         {
969                 return 00;
970         }
971         memset(l_t2,0,sizeof(opj_t2_t));
972         l_t2->image = p_image;
973         l_t2->cp = p_cp;
974         return l_t2;
975 }
976
977 void t2_destroy(opj_t2_t *t2) {
978         if(t2) {
979                 opj_free(t2);
980         }
981 }
982
983 void t2_destroy_v2(opj_t2_v2_t *t2) {
984         if(t2) {
985                 opj_free(t2);
986         }
987 }
988
989
990 static opj_bool t2_decode_packet_v2(
991                                                          opj_t2_v2_t* p_t2,
992                                                          opj_tcd_tile_v2_t *p_tile,
993                              opj_tcp_v2_t *p_tcp,
994                                                          opj_pi_iterator_t *p_pi,
995                                                          OPJ_BYTE *p_src,
996                                                          OPJ_UINT32 * p_data_read,
997                                                          OPJ_UINT32 p_max_length,
998                                                          opj_packet_info_t *p_pack_info)
999 {
1000         opj_bool l_read_data;
1001         OPJ_UINT32 l_nb_bytes_read = 0;
1002         OPJ_UINT32 l_nb_total_bytes_read = 0;
1003
1004         *p_data_read = 0;
1005
1006         if (! t2_read_packet_header(p_t2,p_tile,p_tcp,p_pi,&l_read_data,p_src,&l_nb_bytes_read,p_max_length,p_pack_info)) {
1007                 return OPJ_FALSE;
1008         }
1009
1010         p_src += l_nb_bytes_read;
1011         l_nb_total_bytes_read += l_nb_bytes_read;
1012         p_max_length -= l_nb_bytes_read;
1013
1014         /* we should read data for the packet */
1015         if (l_read_data) {
1016                 l_nb_bytes_read = 0;
1017
1018                 if (! t2_read_packet_data(p_t2,p_tile,p_pi,p_src,&l_nb_bytes_read,p_max_length,p_pack_info)) {
1019                         return OPJ_FALSE;
1020                 }
1021
1022                 l_nb_total_bytes_read += l_nb_bytes_read;
1023         }
1024
1025         *p_data_read = l_nb_total_bytes_read;
1026
1027         return OPJ_FALSE;
1028 }
1029
1030 static opj_bool t2_skip_packet(
1031                                                          opj_t2_v2_t* p_t2,
1032                                                          opj_tcd_tile_v2_t *p_tile,
1033                              opj_tcp_v2_t *p_tcp,
1034                                                          opj_pi_iterator_t *p_pi,
1035                                                          OPJ_BYTE *p_src,
1036                                                          OPJ_UINT32 * p_data_read,
1037                                                          OPJ_UINT32 p_max_length,
1038                                                          opj_packet_info_t *p_pack_info)
1039 {
1040         opj_bool l_read_data;
1041         OPJ_UINT32 l_nb_bytes_read = 0;
1042         OPJ_UINT32 l_nb_total_bytes_read = 0;
1043
1044         *p_data_read = 0;
1045
1046         if (! t2_read_packet_header(p_t2,p_tile,p_tcp,p_pi,&l_read_data,p_src,&l_nb_bytes_read,p_max_length,p_pack_info)) {
1047                 return OPJ_FALSE;
1048         }
1049
1050         p_src += l_nb_bytes_read;
1051         l_nb_total_bytes_read += l_nb_bytes_read;
1052         p_max_length -= l_nb_bytes_read;
1053
1054         /* we should read data for the packet */
1055         if (l_read_data) {
1056                 l_nb_bytes_read = 0;
1057
1058                 if (! t2_skip_packet_data(p_t2,p_tile,p_pi,&l_nb_bytes_read,p_max_length,p_pack_info)) {
1059                         return OPJ_FALSE;
1060                 }
1061
1062                 l_nb_total_bytes_read += l_nb_bytes_read;
1063         }
1064         *p_data_read = l_nb_total_bytes_read;
1065
1066         return OPJ_TRUE;
1067 }
1068
1069
1070
1071 static opj_bool t2_read_packet_header(
1072                                                          opj_t2_v2_t* p_t2,
1073                                                          opj_tcd_tile_v2_t *p_tile,
1074                              opj_tcp_v2_t *p_tcp,
1075                                                          opj_pi_iterator_t *p_pi,
1076                                                          opj_bool * p_is_data_present,
1077                                                          OPJ_BYTE *p_src_data,
1078                                                          OPJ_UINT32 * p_data_read,
1079                                                          OPJ_UINT32 p_max_length,
1080                                                          opj_packet_info_t *p_pack_info)
1081 {
1082         /* loop */
1083         OPJ_UINT32 bandno, cblkno;
1084         OPJ_UINT32 l_nb_code_blocks;
1085         OPJ_UINT32 l_remaining_length;
1086         OPJ_UINT32 l_header_length;
1087         OPJ_UINT32 * l_modified_length_ptr = 00;
1088         OPJ_BYTE *l_current_data = p_src_data;
1089         opj_cp_v2_t *l_cp = p_t2->cp;
1090         opj_bio_t *l_bio = 00;  /* BIO component */
1091         opj_tcd_band_v2_t *l_band = 00;
1092         opj_tcd_cblk_dec_v2_t* l_cblk = 00;
1093         opj_tcd_resolution_v2_t* l_res = &p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
1094
1095         OPJ_BYTE *l_header_data = 00;
1096         OPJ_BYTE **l_header_data_start = 00;
1097
1098         OPJ_UINT32 l_present;
1099
1100         if (p_pi->layno == 0) {
1101                 l_band = l_res->bands;
1102
1103                 /* reset tagtrees */
1104                 for (bandno = 0; bandno < l_res->numbands; ++bandno) {
1105                         opj_tcd_precinct_v2_t *l_prc = &l_band->precincts[p_pi->precno];
1106
1107                         if ( ! ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) ) {
1108                                 tgt_reset(l_prc->incltree);
1109                                 tgt_reset(l_prc->imsbtree);
1110                                 l_cblk = l_prc->cblks.dec;
1111
1112                                 l_nb_code_blocks = l_prc->cw * l_prc->ch;
1113                                 for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
1114                                         l_cblk->numsegs = 0;
1115                                         l_cblk->real_num_segs = 0;
1116                                         ++l_cblk;
1117                                 }
1118                         }
1119
1120                         ++l_band;
1121                 }
1122         }
1123
1124         /* SOP markers */
1125
1126         if (p_tcp->csty & J2K_CP_CSTY_SOP) {
1127                 if ((*l_current_data) != 0xff || (*(l_current_data + 1) != 0x91)) {
1128                         // TODO opj_event_msg(t2->cinfo->event_mgr, EVT_WARNING, "Expected SOP marker\n");
1129                 } else {
1130                         l_current_data += 6;
1131                 }
1132
1133                 /** TODO : check the Nsop value */
1134         }
1135
1136         /*
1137         When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
1138         This part deal with this caracteristic
1139         step 1: Read packet header in the saved structure
1140         step 2: Return to codestream for decoding
1141         */
1142
1143         l_bio = bio_create();
1144         if (! l_bio) {
1145                 return OPJ_FALSE;
1146         }
1147
1148         if (l_cp->ppm == 1) { /* PPM */
1149                 l_header_data_start = &l_cp->ppm_data;
1150                 l_header_data = *l_header_data_start;
1151                 l_modified_length_ptr = &(l_cp->ppm_len);
1152
1153         }
1154         else if (p_tcp->ppt == 1) { /* PPT */
1155                 l_header_data_start = &(p_tcp->ppt_data);
1156                 l_header_data = *l_header_data_start;
1157                 l_modified_length_ptr = &(p_tcp->ppt_len);
1158         }
1159         else {  /* Normal Case */
1160                 l_header_data_start = &(l_current_data);
1161                 l_header_data = *l_header_data_start;
1162                 l_remaining_length = p_src_data+p_max_length-l_header_data;
1163                 l_modified_length_ptr = &(l_remaining_length);
1164         }
1165
1166         bio_init_dec(l_bio, l_header_data,*l_modified_length_ptr);
1167
1168         l_present = bio_read(l_bio, 1);
1169         if (!l_present) {
1170                 bio_inalign(l_bio);
1171                 l_header_data += bio_numbytes(l_bio);
1172                 bio_destroy(l_bio);
1173
1174                 /* EPH markers */
1175                 if (p_tcp->csty & J2K_CP_CSTY_EPH) {
1176                         if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) {
1177                                 printf("Error : expected EPH marker\n");
1178                         } else {
1179                                 l_header_data += 2;
1180                         }
1181                 }
1182
1183                 l_header_length = (l_header_data - *l_header_data_start);
1184                 *l_modified_length_ptr -= l_header_length;
1185                 *l_header_data_start += l_header_length;
1186
1187                 /* << INDEX */
1188                 // End of packet header position. Currently only represents the distance to start of packet
1189                 // Will be updated later by incrementing with packet start value
1190                 if (p_pack_info) {
1191                         p_pack_info->end_ph_pos = (OPJ_INT32)(l_current_data - p_src_data);
1192                 }
1193                 /* INDEX >> */
1194
1195                 * p_is_data_present = OPJ_FALSE;
1196                 *p_data_read = l_current_data - p_src_data;
1197                 return OPJ_TRUE;
1198         }
1199
1200         l_band = l_res->bands;
1201         for (bandno = 0; bandno < l_res->numbands; ++bandno) {
1202                 opj_tcd_precinct_v2_t *l_prc = &(l_band->precincts[p_pi->precno]);
1203
1204                 if ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) {
1205                         ++l_band;
1206                         continue;
1207                 }
1208
1209                 l_nb_code_blocks = l_prc->cw * l_prc->ch;
1210                 l_cblk = l_prc->cblks.dec;
1211                 for (cblkno = 0; cblkno < l_nb_code_blocks; cblkno++) {
1212                         OPJ_UINT32 l_included,l_increment, l_segno;
1213                         OPJ_INT32 n;
1214
1215                         /* if cblk not yet included before --> inclusion tagtree */
1216                         if (!l_cblk->numsegs) {
1217                                 l_included = tgt_decode(l_bio, l_prc->incltree, cblkno, p_pi->layno + 1);
1218                                 /* else one bit */
1219                         }
1220                         else {
1221                                 l_included = bio_read(l_bio, 1);
1222                         }
1223
1224                         /* if cblk not included */
1225                         if (!l_included) {
1226                                 l_cblk->numnewpasses = 0;
1227                                 ++l_cblk;
1228                                 continue;
1229                         }
1230
1231                         /* if cblk not yet included --> zero-bitplane tagtree */
1232                         if (!l_cblk->numsegs) {
1233                                 OPJ_UINT32 i = 0;
1234
1235                                 while (!tgt_decode(l_bio, l_prc->imsbtree, cblkno, i)) {
1236                                         ++i;
1237                                 }
1238
1239                                 l_cblk->numbps = l_band->numbps + 1 - i;
1240                                 l_cblk->numlenbits = 3;
1241                         }
1242
1243                         /* number of coding passes */
1244                         l_cblk->numnewpasses = t2_getnumpasses(l_bio);
1245                         l_increment = t2_getcommacode(l_bio);
1246
1247                         /* length indicator increment */
1248                         l_cblk->numlenbits += l_increment;
1249                         l_segno = 0;
1250
1251                         if (!l_cblk->numsegs) {
1252                                 if (! t2_init_seg_v2(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 1)) {
1253                                         bio_destroy(l_bio);
1254                                         return OPJ_FALSE;
1255                                 }
1256                         }
1257                         else {
1258                                 l_segno = l_cblk->numsegs - 1;
1259                                 if (l_cblk->segs[l_segno].numpasses == l_cblk->segs[l_segno].maxpasses) {
1260                                         ++l_segno;
1261                                         if (! t2_init_seg_v2(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 0)) {
1262                                                 bio_destroy(l_bio);
1263                                                 return OPJ_FALSE;
1264                                         }
1265                                 }
1266                         }
1267                         n = l_cblk->numnewpasses;
1268
1269                         do {
1270                                 l_cblk->segs[l_segno].numnewpasses = int_min(l_cblk->segs[l_segno].maxpasses - l_cblk->segs[l_segno].numpasses, n);
1271                                 l_cblk->segs[l_segno].newlen = bio_read(l_bio, l_cblk->numlenbits + uint_floorlog2(l_cblk->segs[l_segno].numnewpasses));
1272
1273                                 n -= l_cblk->segs[l_segno].numnewpasses;
1274                                 if (n > 0) {
1275                                         ++l_segno;
1276
1277                                         if (! t2_init_seg_v2(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 0)) {
1278                                                 bio_destroy(l_bio);
1279                                                 return OPJ_FALSE;
1280                                         }
1281                                 }
1282                         } while (n > 0);
1283
1284                         ++l_cblk;
1285                 }
1286
1287                 ++l_band;
1288         }
1289
1290         if (bio_inalign(l_bio)) {
1291                 bio_destroy(l_bio);
1292                 return OPJ_FALSE;
1293         }
1294
1295         l_header_data += bio_numbytes(l_bio);
1296         bio_destroy(l_bio);
1297
1298         /* EPH markers */
1299         if (p_tcp->csty & J2K_CP_CSTY_EPH) {
1300                 if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) {
1301                         // TODO opj_event_msg(t2->cinfo->event_mgr, EVT_ERROR, "Expected EPH marker\n");
1302                 } else {
1303                         l_header_data += 2;
1304                 }
1305         }
1306
1307         l_header_length = (l_header_data - *l_header_data_start);
1308         *l_modified_length_ptr -= l_header_length;
1309         *l_header_data_start += l_header_length;
1310
1311         /* << INDEX */
1312         // End of packet header position. Currently only represents the distance to start of packet
1313         // Will be updated later by incrementing with packet start value
1314         if (p_pack_info) {
1315                 p_pack_info->end_ph_pos = (OPJ_INT32)(l_current_data - p_src_data);
1316         }
1317         /* INDEX >> */
1318
1319         *p_is_data_present = OPJ_TRUE;
1320         *p_data_read = l_current_data - p_src_data;
1321
1322         return OPJ_TRUE;
1323 }
1324
1325 static opj_bool t2_read_packet_data(
1326                                                          opj_t2_v2_t* p_t2,
1327                                                          opj_tcd_tile_v2_t *p_tile,
1328                                                          opj_pi_iterator_t *p_pi,
1329                                                          OPJ_BYTE *p_src_data,
1330                                                          OPJ_UINT32 * p_data_read,
1331                                                          OPJ_UINT32 p_max_length,
1332                                                          opj_packet_info_t *pack_info)
1333 {
1334         OPJ_UINT32 bandno, cblkno;
1335         OPJ_UINT32 l_nb_code_blocks;
1336         OPJ_BYTE *l_current_data = p_src_data;
1337         opj_tcd_band_v2_t *l_band = 00;
1338         opj_tcd_cblk_dec_v2_t* l_cblk = 00;
1339         opj_tcd_resolution_v2_t* l_res = &p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
1340
1341         l_band = l_res->bands;
1342         for (bandno = 0; bandno < l_res->numbands; ++bandno) {
1343                 opj_tcd_precinct_v2_t *l_prc = &l_band->precincts[p_pi->precno];
1344
1345                 if ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) {
1346                         ++l_band;
1347                         continue;
1348                 }
1349
1350                 l_nb_code_blocks = l_prc->cw * l_prc->ch;
1351                 l_cblk = l_prc->cblks.dec;
1352
1353                 for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
1354                         opj_tcd_seg_t *l_seg = 00;
1355
1356                         if (!l_cblk->numnewpasses) {
1357                                 /* nothing to do */
1358                                 ++l_cblk;
1359                                 continue;
1360                         }
1361
1362                         if (!l_cblk->numsegs) {
1363                                 l_seg = l_cblk->segs;
1364                                 ++l_cblk->numsegs;
1365                                 l_cblk->len = 0;
1366                         }
1367                         else {
1368                                 l_seg = &l_cblk->segs[l_cblk->numsegs - 1];
1369
1370                                 if (l_seg->numpasses == l_seg->maxpasses) {
1371                                         ++l_seg;
1372                                         ++l_cblk->numsegs;
1373                                 }
1374                         }
1375
1376                         do {
1377                                 if (l_current_data + l_seg->newlen > p_src_data + p_max_length) {
1378                                         return OPJ_FALSE;
1379                                 }
1380
1381 #ifdef USE_JPWL
1382                         /* we need here a j2k handle to verify if making a check to
1383                         the validity of cblocks parameters is selected from user (-W) */
1384
1385                                 /* let's check that we are not exceeding */
1386                                 if ((cblk->len + seg->newlen) > 8192) {
1387                                         opj_event_msg(t2->cinfo, EVT_WARNING,
1388                                                 "JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
1389                                                 seg->newlen, cblkno, precno, bandno, resno, compno);
1390                                         if (!JPWL_ASSUME) {
1391                                                 opj_event_msg(t2->cinfo, EVT_ERROR, "JPWL: giving up\n");
1392                                                 return -999;
1393                                         }
1394                                         seg->newlen = 8192 - cblk->len;
1395                                         opj_event_msg(t2->cinfo, EVT_WARNING, "      - truncating segment to %d\n", seg->newlen);
1396                                         break;
1397                                 };
1398
1399 #endif /* USE_JPWL */
1400
1401                                 memcpy(l_cblk->data + l_cblk->len, l_current_data, l_seg->newlen);
1402
1403                                 if (l_seg->numpasses == 0) {
1404                                         l_seg->data = &l_cblk->data;
1405                                         l_seg->dataindex = l_cblk->len;
1406                                 }
1407
1408                                 l_current_data += l_seg->newlen;
1409                                 l_seg->numpasses += l_seg->numnewpasses;
1410                                 l_cblk->numnewpasses -= l_seg->numnewpasses;
1411
1412                                 l_seg->real_num_passes = l_seg->numpasses;
1413                                 l_cblk->len += l_seg->newlen;
1414                                 l_seg->len += l_seg->newlen;
1415
1416                                 if (l_cblk->numnewpasses > 0) {
1417                                         ++l_seg;
1418                                         ++l_cblk->numsegs;
1419                                 }
1420                         } while (l_cblk->numnewpasses > 0);
1421
1422                         l_cblk->real_num_segs = l_cblk->numsegs;
1423                         ++l_cblk;
1424                 }
1425
1426                 ++l_band;
1427         }
1428
1429         *(p_data_read) = l_current_data - p_src_data;
1430
1431         return OPJ_TRUE;
1432 }
1433
1434 static opj_bool t2_skip_packet_data(
1435                                                          opj_t2_v2_t* p_t2,
1436                                                          opj_tcd_tile_v2_t *p_tile,
1437                                                          opj_pi_iterator_t *p_pi,
1438                                                          OPJ_UINT32 * p_data_read,
1439                                                          OPJ_UINT32 p_max_length,
1440                                                          opj_packet_info_t *pack_info)
1441 {
1442         OPJ_UINT32 bandno, cblkno;
1443         OPJ_UINT32 l_nb_code_blocks;
1444         opj_tcd_band_v2_t *l_band = 00;
1445         opj_tcd_cblk_dec_v2_t* l_cblk = 00;
1446         opj_tcd_resolution_v2_t* l_res = &p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
1447
1448         *p_data_read = 0;
1449         l_band = l_res->bands;
1450
1451         for (bandno = 0; bandno < l_res->numbands; ++bandno) {
1452                 opj_tcd_precinct_v2_t *l_prc = &l_band->precincts[p_pi->precno];
1453
1454                 if ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) {
1455                         ++l_band;
1456                         continue;
1457                 }
1458
1459                 l_nb_code_blocks = l_prc->cw * l_prc->ch;
1460                 l_cblk = l_prc->cblks.dec;
1461
1462                 for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
1463                         opj_tcd_seg_t *l_seg = 00;
1464
1465                         if (!l_cblk->numnewpasses) {
1466                                 /* nothing to do */
1467                                 ++l_cblk;
1468                                 continue;
1469                         }
1470
1471                         if (!l_cblk->numsegs) {
1472                                 l_seg = l_cblk->segs;
1473                                 ++l_cblk->numsegs;
1474                                 l_cblk->len = 0;
1475                         }
1476                         else {
1477                                 l_seg = &l_cblk->segs[l_cblk->numsegs - 1];
1478
1479                                 if (l_seg->numpasses == l_seg->maxpasses) {
1480                                         ++l_seg;
1481                                         ++l_cblk->numsegs;
1482                                 }
1483                         }
1484
1485                         do {
1486                                 if (* p_data_read + l_seg->newlen > p_max_length) {
1487                                         return OPJ_FALSE;
1488                                 }
1489
1490 #ifdef USE_JPWL
1491                         /* we need here a j2k handle to verify if making a check to
1492                         the validity of cblocks parameters is selected from user (-W) */
1493
1494                                 /* let's check that we are not exceeding */
1495                                 if ((cblk->len + seg->newlen) > 8192) {
1496                                         opj_event_msg(t2->cinfo, EVT_WARNING,
1497                                                 "JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
1498                                                 seg->newlen, cblkno, precno, bandno, resno, compno);
1499                                         if (!JPWL_ASSUME) {
1500                                                 opj_event_msg(t2->cinfo, EVT_ERROR, "JPWL: giving up\n");
1501                                                 return -999;
1502                                         }
1503                                         seg->newlen = 8192 - cblk->len;
1504                                         opj_event_msg(t2->cinfo, EVT_WARNING, "      - truncating segment to %d\n", seg->newlen);
1505                                         break;
1506                                 };
1507
1508 #endif /* USE_JPWL */
1509                                 *(p_data_read) += l_seg->newlen;
1510
1511                                 l_seg->numpasses += l_seg->numnewpasses;
1512                                 l_cblk->numnewpasses -= l_seg->numnewpasses;
1513                                 if (l_cblk->numnewpasses > 0)
1514                                 {
1515                                         ++l_seg;
1516                                         ++l_cblk->numsegs;
1517                                 }
1518                         } while (l_cblk->numnewpasses > 0);
1519
1520                         ++l_cblk;
1521                 }
1522
1523                 ++l_band;
1524         }
1525
1526         return OPJ_TRUE;
1527 }
1528
1529
1530 static opj_bool t2_init_seg_v2(opj_tcd_cblk_dec_v2_t* cblk, OPJ_UINT32 index, OPJ_UINT32 cblksty, OPJ_UINT32 first)
1531 {
1532         opj_tcd_seg_t* seg = 00;
1533         OPJ_UINT32 l_nb_segs = index + 1;
1534
1535         if (l_nb_segs > cblk->m_current_max_segs) {
1536                 cblk->m_current_max_segs += J2K_DEFAULT_NB_SEGS;
1537
1538                 cblk->segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs, cblk->m_current_max_segs * sizeof(opj_tcd_seg_t));
1539                 if(! cblk->segs) {
1540                         return OPJ_FALSE;
1541                 }
1542         }
1543
1544         seg = &cblk->segs[index];
1545         memset(seg,0,sizeof(opj_tcd_seg_t));
1546
1547         if (cblksty & J2K_CCP_CBLKSTY_TERMALL) {
1548                 seg->maxpasses = 1;
1549         }
1550         else if (cblksty & J2K_CCP_CBLKSTY_LAZY) {
1551                 if (first) {
1552                         seg->maxpasses = 10;
1553                 } else {
1554                         seg->maxpasses = (((seg - 1)->maxpasses == 1) || ((seg - 1)->maxpasses == 10)) ? 2 : 1;
1555                 }
1556         } else {
1557                 seg->maxpasses = 109;
1558         }
1559
1560         return OPJ_TRUE;
1561 }