[trunk] support seeking in files larger than 2 GB
[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                                                 opj_codestream_index_t *p_cstr_index)
848 {
849         OPJ_BYTE *l_current_data = p_src;
850         opj_pi_iterator_t *l_pi = 00;
851         OPJ_UINT32 pino;
852         opj_image_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_t* l_img_comp = 00;
863
864 #ifdef TODO_MSD
865         if (p_cstr_index) {
866                 l_pack_info = p_cstr_index->tile_index[p_tile_no].packet;
867         }
868 #endif
869
870         /* create a packet iterator */
871         l_pi = pi_create_decode_v2(l_image, l_cp, p_tile_no);
872         if (!l_pi) {
873                 return OPJ_FALSE;
874         }
875
876         tp_start_packno = 0;
877         l_current_pi = l_pi;
878
879         for     (pino = 0; pino <= l_tcp->numpocs; ++pino) {
880
881                 /* if the resolution needed is to low, one dim of the tilec could be equal to zero
882                  * and no packets are used to encode this resolution and
883                  * l_current_pi->resno is always >= p_tile->comps[l_current_pi->compno].minimum_num_resolutions
884                  * and no l_img_comp->resno_decoded are computed
885                  */
886                 opj_bool* first_pass_failed = (opj_bool*)opj_malloc(l_image->numcomps * sizeof(opj_bool));
887                 memset(first_pass_failed, OPJ_TRUE, l_image->numcomps * sizeof(opj_bool));
888
889                 while (pi_next(l_current_pi)) {
890
891
892                         if (l_tcp->num_layers_to_decode > l_current_pi->layno
893                                         && l_current_pi->resno < p_tile->comps[l_current_pi->compno].minimum_num_resolutions) {
894                                 l_nb_bytes_read = 0;
895
896                                 first_pass_failed[l_current_pi->compno] = OPJ_FALSE;
897
898                                 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)) {
899                                         pi_destroy_v2(l_pi,l_nb_pocs);
900                                         return OPJ_FALSE;
901                                 }
902
903                                 l_img_comp = &(l_image->comps[l_current_pi->compno]);
904                                 l_img_comp->resno_decoded = uint_max(l_current_pi->resno, l_img_comp->resno_decoded);
905                         }
906                         else {
907                                 l_nb_bytes_read = 0;
908                                 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)) {
909                                         pi_destroy_v2(l_pi,l_nb_pocs);
910                                         return OPJ_FALSE;
911                                 }
912                         }
913
914                         if (first_pass_failed[l_current_pi->compno]) {
915                                 l_img_comp = &(l_image->comps[l_current_pi->compno]);
916                                 if (l_img_comp->resno_decoded == 0)
917                                         l_img_comp->resno_decoded = p_tile->comps[l_current_pi->compno].minimum_num_resolutions - 1;
918                         }
919
920                         l_current_data += l_nb_bytes_read;
921                         p_max_len -= l_nb_bytes_read;
922
923                         /* INDEX >> */
924 #ifdef TODO_MSD
925                         if(p_cstr_info) {
926                                 opj_tile_info_v2_t *info_TL = &p_cstr_info->tile[p_tile_no];
927                                 opj_packet_info_t *info_PK = &info_TL->packet[p_cstr_info->packno];
928                                 if (!p_cstr_info->packno) {
929                                         info_PK->start_pos = info_TL->end_header + 1;
930                                 } 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
931                                         info_TL->tp[curtp].tp_numpacks = p_cstr_info->packno - tp_start_packno; // Number of packets in previous tile-part
932                                         tp_start_packno = p_cstr_info->packno;
933                                         curtp++;
934                                         info_PK->start_pos = p_cstr_info->tile[p_tile_no].tp[curtp].tp_end_header+1;
935                                 } else {
936                                         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;
937                                 }
938                                 info_PK->end_pos = info_PK->start_pos + l_nb_bytes_read - 1;
939                                 info_PK->end_ph_pos += info_PK->start_pos - 1;  // End of packet header which now only represents the distance
940                                 ++p_cstr_info->packno;
941                         }
942 #endif
943                         /* << INDEX */
944                 }
945                 ++l_current_pi;
946
947                 opj_free(first_pass_failed);
948         }
949         /* INDEX >> */
950 #ifdef TODO_MSD
951         if
952                 (p_cstr_info) {
953                 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
954         }
955 #endif
956         /* << INDEX */
957
958         /* don't forget to release pi */
959         pi_destroy_v2(l_pi,l_nb_pocs);
960         *p_data_read = l_current_data - p_src;
961         return OPJ_TRUE;
962 }
963
964 /* ----------------------------------------------------------------------- */
965
966 opj_t2_t* t2_create(opj_common_ptr cinfo, opj_image_t *image, opj_cp_t *cp) {
967         /* create the tcd structure */
968         opj_t2_t *t2 = (opj_t2_t*)opj_malloc(sizeof(opj_t2_t));
969         if(!t2) return NULL;
970         t2->cinfo = cinfo;
971         t2->image = image;
972         t2->cp = cp;
973
974         return t2;
975 }
976
977 /**
978  * Creates a Tier 2 handle
979  *
980  * @param       p_image         Source or destination image
981  * @param       p_cp            Image coding parameters.
982  * @return              a new T2 handle if successful, NULL otherwise.
983 */
984 opj_t2_v2_t* t2_create_v2(      opj_image_t *p_image,
985                                                         opj_cp_v2_t *p_cp)
986 {
987         /* create the tcd structure */
988         opj_t2_v2_t *l_t2 = (opj_t2_v2_t*)opj_malloc(sizeof(opj_t2_v2_t));
989         if (!l_t2) {
990                 return NULL;
991         }
992         memset(l_t2,0,sizeof(opj_t2_v2_t));
993
994         l_t2->image = p_image;
995         l_t2->cp = p_cp;
996
997         return l_t2;
998 }
999
1000 void t2_destroy(opj_t2_t *t2) {
1001         if(t2) {
1002                 opj_free(t2);
1003         }
1004 }
1005
1006 void t2_destroy_v2(opj_t2_v2_t *t2) {
1007         if(t2) {
1008                 opj_free(t2);
1009         }
1010 }
1011
1012
1013 static opj_bool t2_decode_packet_v2(
1014                                                          opj_t2_v2_t* p_t2,
1015                                                          opj_tcd_tile_v2_t *p_tile,
1016                              opj_tcp_v2_t *p_tcp,
1017                                                          opj_pi_iterator_t *p_pi,
1018                                                          OPJ_BYTE *p_src,
1019                                                          OPJ_UINT32 * p_data_read,
1020                                                          OPJ_UINT32 p_max_length,
1021                                                          opj_packet_info_t *p_pack_info)
1022 {
1023         opj_bool l_read_data;
1024         OPJ_UINT32 l_nb_bytes_read = 0;
1025         OPJ_UINT32 l_nb_total_bytes_read = 0;
1026
1027         *p_data_read = 0;
1028
1029         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)) {
1030                 return OPJ_FALSE;
1031         }
1032
1033         p_src += l_nb_bytes_read;
1034         l_nb_total_bytes_read += l_nb_bytes_read;
1035         p_max_length -= l_nb_bytes_read;
1036
1037         /* we should read data for the packet */
1038         if (l_read_data) {
1039                 l_nb_bytes_read = 0;
1040
1041                 if (! t2_read_packet_data(p_t2,p_tile,p_pi,p_src,&l_nb_bytes_read,p_max_length,p_pack_info)) {
1042                         return OPJ_FALSE;
1043                 }
1044
1045                 l_nb_total_bytes_read += l_nb_bytes_read;
1046         }
1047
1048         *p_data_read = l_nb_total_bytes_read;
1049
1050         return OPJ_TRUE;
1051 }
1052
1053 static opj_bool t2_skip_packet(
1054                                                          opj_t2_v2_t* p_t2,
1055                                                          opj_tcd_tile_v2_t *p_tile,
1056                              opj_tcp_v2_t *p_tcp,
1057                                                          opj_pi_iterator_t *p_pi,
1058                                                          OPJ_BYTE *p_src,
1059                                                          OPJ_UINT32 * p_data_read,
1060                                                          OPJ_UINT32 p_max_length,
1061                                                          opj_packet_info_t *p_pack_info)
1062 {
1063         opj_bool l_read_data;
1064         OPJ_UINT32 l_nb_bytes_read = 0;
1065         OPJ_UINT32 l_nb_total_bytes_read = 0;
1066
1067         *p_data_read = 0;
1068
1069         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)) {
1070                 return OPJ_FALSE;
1071         }
1072
1073         p_src += l_nb_bytes_read;
1074         l_nb_total_bytes_read += l_nb_bytes_read;
1075         p_max_length -= l_nb_bytes_read;
1076
1077         /* we should read data for the packet */
1078         if (l_read_data) {
1079                 l_nb_bytes_read = 0;
1080
1081                 if (! t2_skip_packet_data(p_t2,p_tile,p_pi,&l_nb_bytes_read,p_max_length,p_pack_info)) {
1082                         return OPJ_FALSE;
1083                 }
1084
1085                 l_nb_total_bytes_read += l_nb_bytes_read;
1086         }
1087         *p_data_read = l_nb_total_bytes_read;
1088
1089         return OPJ_TRUE;
1090 }
1091
1092
1093
1094 static opj_bool t2_read_packet_header(
1095                                                          opj_t2_v2_t* p_t2,
1096                                                          opj_tcd_tile_v2_t *p_tile,
1097                              opj_tcp_v2_t *p_tcp,
1098                                                          opj_pi_iterator_t *p_pi,
1099                                                          opj_bool * p_is_data_present,
1100                                                          OPJ_BYTE *p_src_data,
1101                                                          OPJ_UINT32 * p_data_read,
1102                                                          OPJ_UINT32 p_max_length,
1103                                                          opj_packet_info_t *p_pack_info)
1104 {
1105         /* loop */
1106         OPJ_UINT32 bandno, cblkno;
1107         OPJ_UINT32 l_nb_code_blocks;
1108         OPJ_UINT32 l_remaining_length;
1109         OPJ_UINT32 l_header_length;
1110         OPJ_UINT32 * l_modified_length_ptr = 00;
1111         OPJ_BYTE *l_current_data = p_src_data;
1112         opj_cp_v2_t *l_cp = p_t2->cp;
1113         opj_bio_t *l_bio = 00;  /* BIO component */
1114         opj_tcd_band_v2_t *l_band = 00;
1115         opj_tcd_cblk_dec_v2_t* l_cblk = 00;
1116         opj_tcd_resolution_v2_t* l_res = &p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
1117
1118         OPJ_BYTE *l_header_data = 00;
1119         OPJ_BYTE **l_header_data_start = 00;
1120
1121         OPJ_UINT32 l_present;
1122
1123         if (p_pi->layno == 0) {
1124                 l_band = l_res->bands;
1125
1126                 /* reset tagtrees */
1127                 for (bandno = 0; bandno < l_res->numbands; ++bandno) {
1128                         opj_tcd_precinct_v2_t *l_prc = &l_band->precincts[p_pi->precno];
1129
1130                         if ( ! ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) ) {
1131                                 tgt_reset(l_prc->incltree);
1132                                 tgt_reset(l_prc->imsbtree);
1133                                 l_cblk = l_prc->cblks.dec;
1134
1135                                 l_nb_code_blocks = l_prc->cw * l_prc->ch;
1136                                 for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
1137                                         l_cblk->numsegs = 0;
1138                                         l_cblk->real_num_segs = 0;
1139                                         ++l_cblk;
1140                                 }
1141                         }
1142
1143                         ++l_band;
1144                 }
1145         }
1146
1147         /* SOP markers */
1148
1149         if (p_tcp->csty & J2K_CP_CSTY_SOP) {
1150                 if ((*l_current_data) != 0xff || (*(l_current_data + 1) != 0x91)) {
1151                         // TODO opj_event_msg(t2->cinfo->event_mgr, EVT_WARNING, "Expected SOP marker\n");
1152                 } else {
1153                         l_current_data += 6;
1154                 }
1155
1156                 /** TODO : check the Nsop value */
1157         }
1158
1159         /*
1160         When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
1161         This part deal with this caracteristic
1162         step 1: Read packet header in the saved structure
1163         step 2: Return to codestream for decoding
1164         */
1165
1166         l_bio = bio_create();
1167         if (! l_bio) {
1168                 return OPJ_FALSE;
1169         }
1170
1171         if (l_cp->ppm == 1) { /* PPM */
1172                 l_header_data_start = &l_cp->ppm_data;
1173                 l_header_data = *l_header_data_start;
1174                 l_modified_length_ptr = &(l_cp->ppm_len);
1175
1176         }
1177         else if (p_tcp->ppt == 1) { /* PPT */
1178                 l_header_data_start = &(p_tcp->ppt_data);
1179                 l_header_data = *l_header_data_start;
1180                 l_modified_length_ptr = &(p_tcp->ppt_len);
1181         }
1182         else {  /* Normal Case */
1183                 l_header_data_start = &(l_current_data);
1184                 l_header_data = *l_header_data_start;
1185                 l_remaining_length = p_src_data+p_max_length-l_header_data;
1186                 l_modified_length_ptr = &(l_remaining_length);
1187         }
1188
1189         bio_init_dec(l_bio, l_header_data,*l_modified_length_ptr);
1190
1191         l_present = bio_read(l_bio, 1);
1192         if (!l_present) {
1193                 bio_inalign(l_bio);
1194                 l_header_data += bio_numbytes(l_bio);
1195                 bio_destroy(l_bio);
1196
1197                 /* EPH markers */
1198                 if (p_tcp->csty & J2K_CP_CSTY_EPH) {
1199                         if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) {
1200                                 printf("Error : expected EPH marker\n");
1201                         } else {
1202                                 l_header_data += 2;
1203                         }
1204                 }
1205
1206                 l_header_length = (l_header_data - *l_header_data_start);
1207                 *l_modified_length_ptr -= l_header_length;
1208                 *l_header_data_start += l_header_length;
1209
1210                 /* << INDEX */
1211                 // End of packet header position. Currently only represents the distance to start of packet
1212                 // Will be updated later by incrementing with packet start value
1213                 if (p_pack_info) {
1214                         p_pack_info->end_ph_pos = (OPJ_INT32)(l_current_data - p_src_data);
1215                 }
1216                 /* INDEX >> */
1217
1218                 * p_is_data_present = OPJ_FALSE;
1219                 *p_data_read = l_current_data - p_src_data;
1220                 return OPJ_TRUE;
1221         }
1222
1223         l_band = l_res->bands;
1224         for (bandno = 0; bandno < l_res->numbands; ++bandno) {
1225                 opj_tcd_precinct_v2_t *l_prc = &(l_band->precincts[p_pi->precno]);
1226
1227                 if ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) {
1228                         ++l_band;
1229                         continue;
1230                 }
1231
1232                 l_nb_code_blocks = l_prc->cw * l_prc->ch;
1233                 l_cblk = l_prc->cblks.dec;
1234                 for (cblkno = 0; cblkno < l_nb_code_blocks; cblkno++) {
1235                         OPJ_UINT32 l_included,l_increment, l_segno;
1236                         OPJ_INT32 n;
1237
1238                         /* if cblk not yet included before --> inclusion tagtree */
1239                         if (!l_cblk->numsegs) {
1240                                 l_included = tgt_decode(l_bio, l_prc->incltree, cblkno, p_pi->layno + 1);
1241                                 /* else one bit */
1242                         }
1243                         else {
1244                                 l_included = bio_read(l_bio, 1);
1245                         }
1246
1247                         /* if cblk not included */
1248                         if (!l_included) {
1249                                 l_cblk->numnewpasses = 0;
1250                                 ++l_cblk;
1251                                 continue;
1252                         }
1253
1254                         /* if cblk not yet included --> zero-bitplane tagtree */
1255                         if (!l_cblk->numsegs) {
1256                                 OPJ_UINT32 i = 0;
1257
1258                                 while (!tgt_decode(l_bio, l_prc->imsbtree, cblkno, i)) {
1259                                         ++i;
1260                                 }
1261
1262                                 l_cblk->numbps = l_band->numbps + 1 - i;
1263                                 l_cblk->numlenbits = 3;
1264                         }
1265
1266                         /* number of coding passes */
1267                         l_cblk->numnewpasses = t2_getnumpasses(l_bio);
1268                         l_increment = t2_getcommacode(l_bio);
1269
1270                         /* length indicator increment */
1271                         l_cblk->numlenbits += l_increment;
1272                         l_segno = 0;
1273
1274                         if (!l_cblk->numsegs) {
1275                                 if (! t2_init_seg_v2(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 1)) {
1276                                         bio_destroy(l_bio);
1277                                         return OPJ_FALSE;
1278                                 }
1279                         }
1280                         else {
1281                                 l_segno = l_cblk->numsegs - 1;
1282                                 if (l_cblk->segs[l_segno].numpasses == l_cblk->segs[l_segno].maxpasses) {
1283                                         ++l_segno;
1284                                         if (! t2_init_seg_v2(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 0)) {
1285                                                 bio_destroy(l_bio);
1286                                                 return OPJ_FALSE;
1287                                         }
1288                                 }
1289                         }
1290                         n = l_cblk->numnewpasses;
1291
1292                         do {
1293                                 l_cblk->segs[l_segno].numnewpasses = int_min(l_cblk->segs[l_segno].maxpasses - l_cblk->segs[l_segno].numpasses, n);
1294                                 l_cblk->segs[l_segno].newlen = bio_read(l_bio, l_cblk->numlenbits + uint_floorlog2(l_cblk->segs[l_segno].numnewpasses));
1295
1296                                 n -= l_cblk->segs[l_segno].numnewpasses;
1297                                 if (n > 0) {
1298                                         ++l_segno;
1299
1300                                         if (! t2_init_seg_v2(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 0)) {
1301                                                 bio_destroy(l_bio);
1302                                                 return OPJ_FALSE;
1303                                         }
1304                                 }
1305                         } while (n > 0);
1306
1307                         ++l_cblk;
1308                 }
1309
1310                 ++l_band;
1311         }
1312
1313         if (bio_inalign(l_bio)) {
1314                 bio_destroy(l_bio);
1315                 return OPJ_FALSE;
1316         }
1317
1318         l_header_data += bio_numbytes(l_bio);
1319         bio_destroy(l_bio);
1320
1321         /* EPH markers */
1322         if (p_tcp->csty & J2K_CP_CSTY_EPH) {
1323                 if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) {
1324                         // TODO opj_event_msg(t2->cinfo->event_mgr, EVT_ERROR, "Expected EPH marker\n");
1325                 } else {
1326                         l_header_data += 2;
1327                 }
1328         }
1329
1330         l_header_length = (l_header_data - *l_header_data_start);
1331         *l_modified_length_ptr -= l_header_length;
1332         *l_header_data_start += l_header_length;
1333
1334         /* << INDEX */
1335         // End of packet header position. Currently only represents the distance to start of packet
1336         // Will be updated later by incrementing with packet start value
1337         if (p_pack_info) {
1338                 p_pack_info->end_ph_pos = (OPJ_INT32)(l_current_data - p_src_data);
1339         }
1340         /* INDEX >> */
1341
1342         *p_is_data_present = OPJ_TRUE;
1343         *p_data_read = l_current_data - p_src_data;
1344
1345         return OPJ_TRUE;
1346 }
1347
1348 static opj_bool t2_read_packet_data(
1349                                                          opj_t2_v2_t* p_t2,
1350                                                          opj_tcd_tile_v2_t *p_tile,
1351                                                          opj_pi_iterator_t *p_pi,
1352                                                          OPJ_BYTE *p_src_data,
1353                                                          OPJ_UINT32 * p_data_read,
1354                                                          OPJ_UINT32 p_max_length,
1355                                                          opj_packet_info_t *pack_info)
1356 {
1357         OPJ_UINT32 bandno, cblkno;
1358         OPJ_UINT32 l_nb_code_blocks;
1359         OPJ_BYTE *l_current_data = p_src_data;
1360         opj_tcd_band_v2_t *l_band = 00;
1361         opj_tcd_cblk_dec_v2_t* l_cblk = 00;
1362         opj_tcd_resolution_v2_t* l_res = &p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
1363
1364         l_band = l_res->bands;
1365         for (bandno = 0; bandno < l_res->numbands; ++bandno) {
1366                 opj_tcd_precinct_v2_t *l_prc = &l_band->precincts[p_pi->precno];
1367
1368                 if ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) {
1369                         ++l_band;
1370                         continue;
1371                 }
1372
1373                 l_nb_code_blocks = l_prc->cw * l_prc->ch;
1374                 l_cblk = l_prc->cblks.dec;
1375
1376                 for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
1377                         opj_tcd_seg_t *l_seg = 00;
1378
1379                         if (!l_cblk->numnewpasses) {
1380                                 /* nothing to do */
1381                                 ++l_cblk;
1382                                 continue;
1383                         }
1384
1385                         if (!l_cblk->numsegs) {
1386                                 l_seg = l_cblk->segs;
1387                                 ++l_cblk->numsegs;
1388                                 l_cblk->len = 0;
1389                         }
1390                         else {
1391                                 l_seg = &l_cblk->segs[l_cblk->numsegs - 1];
1392
1393                                 if (l_seg->numpasses == l_seg->maxpasses) {
1394                                         ++l_seg;
1395                                         ++l_cblk->numsegs;
1396                                 }
1397                         }
1398
1399                         do {
1400                                 if (l_current_data + l_seg->newlen > p_src_data + p_max_length) {
1401                                         return OPJ_FALSE;
1402                                 }
1403
1404 #ifdef USE_JPWL
1405                         /* we need here a j2k handle to verify if making a check to
1406                         the validity of cblocks parameters is selected from user (-W) */
1407
1408                                 /* let's check that we are not exceeding */
1409                                 if ((l_cblk->len + l_seg->newlen) > 8192) {
1410                                         opj_event_msg(p_t2->cinfo, EVT_WARNING,
1411                                                 "JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
1412                                                 l_seg->newlen, cblkno, p_pi->precno, bandno, p_pi->resno, p_pi->compno);
1413                                         if (!JPWL_ASSUME) {
1414                                                 opj_event_msg(p_t2->cinfo, EVT_ERROR, "JPWL: giving up\n");
1415                                                 return OPJ_FALSE;
1416                                         }
1417                                         l_seg->newlen = 8192 - l_cblk->len;
1418                                         opj_event_msg(p_t2->cinfo, EVT_WARNING, "      - truncating segment to %d\n", l_seg->newlen);
1419                                         break;
1420                                 };
1421
1422 #endif /* USE_JPWL */
1423
1424                                 memcpy(l_cblk->data + l_cblk->len, l_current_data, l_seg->newlen);
1425
1426                                 if (l_seg->numpasses == 0) {
1427                                         l_seg->data = &l_cblk->data;
1428                                         l_seg->dataindex = l_cblk->len;
1429                                 }
1430
1431                                 l_current_data += l_seg->newlen;
1432                                 l_seg->numpasses += l_seg->numnewpasses;
1433                                 l_cblk->numnewpasses -= l_seg->numnewpasses;
1434
1435                                 l_seg->real_num_passes = l_seg->numpasses;
1436                                 l_cblk->len += l_seg->newlen;
1437                                 l_seg->len += l_seg->newlen;
1438
1439                                 if (l_cblk->numnewpasses > 0) {
1440                                         ++l_seg;
1441                                         ++l_cblk->numsegs;
1442                                 }
1443                         } while (l_cblk->numnewpasses > 0);
1444
1445                         l_cblk->real_num_segs = l_cblk->numsegs;
1446                         ++l_cblk;
1447                 }
1448
1449                 ++l_band;
1450         }
1451
1452         *(p_data_read) = l_current_data - p_src_data;
1453
1454         return OPJ_TRUE;
1455 }
1456
1457 static opj_bool t2_skip_packet_data(
1458                                                          opj_t2_v2_t* p_t2,
1459                                                          opj_tcd_tile_v2_t *p_tile,
1460                                                          opj_pi_iterator_t *p_pi,
1461                                                          OPJ_UINT32 * p_data_read,
1462                                                          OPJ_UINT32 p_max_length,
1463                                                          opj_packet_info_t *pack_info)
1464 {
1465         OPJ_UINT32 bandno, cblkno;
1466         OPJ_UINT32 l_nb_code_blocks;
1467         opj_tcd_band_v2_t *l_band = 00;
1468         opj_tcd_cblk_dec_v2_t* l_cblk = 00;
1469         opj_tcd_resolution_v2_t* l_res = &p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
1470
1471         *p_data_read = 0;
1472         l_band = l_res->bands;
1473
1474         for (bandno = 0; bandno < l_res->numbands; ++bandno) {
1475                 opj_tcd_precinct_v2_t *l_prc = &l_band->precincts[p_pi->precno];
1476
1477                 if ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) {
1478                         ++l_band;
1479                         continue;
1480                 }
1481
1482                 l_nb_code_blocks = l_prc->cw * l_prc->ch;
1483                 l_cblk = l_prc->cblks.dec;
1484
1485                 for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
1486                         opj_tcd_seg_t *l_seg = 00;
1487
1488                         if (!l_cblk->numnewpasses) {
1489                                 /* nothing to do */
1490                                 ++l_cblk;
1491                                 continue;
1492                         }
1493
1494                         if (!l_cblk->numsegs) {
1495                                 l_seg = l_cblk->segs;
1496                                 ++l_cblk->numsegs;
1497                                 l_cblk->len = 0;
1498                         }
1499                         else {
1500                                 l_seg = &l_cblk->segs[l_cblk->numsegs - 1];
1501
1502                                 if (l_seg->numpasses == l_seg->maxpasses) {
1503                                         ++l_seg;
1504                                         ++l_cblk->numsegs;
1505                                 }
1506                         }
1507
1508                         do {
1509                                 if (* p_data_read + l_seg->newlen > p_max_length) {
1510                                         return OPJ_FALSE;
1511                                 }
1512
1513 #ifdef USE_JPWL
1514                         /* we need here a j2k handle to verify if making a check to
1515                         the validity of cblocks parameters is selected from user (-W) */
1516
1517                                 /* let's check that we are not exceeding */
1518                                 if ((l_cblk->len + l_seg->newlen) > 8192) {
1519                                         opj_event_msg(p_t2->cinfo, EVT_WARNING,
1520                                                 "JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
1521                                                 l_seg->newlen, cblkno, p_pi->precno, bandno, p_pi->resno, p_pi->compno);
1522                                         if (!JPWL_ASSUME) {
1523                                                 opj_event_msg(p_t2->cinfo, EVT_ERROR, "JPWL: giving up\n");
1524                                                 return -999;
1525                                         }
1526                                         l_seg->newlen = 8192 - l_cblk->len;
1527                                         opj_event_msg(p_t2->cinfo, EVT_WARNING, "      - truncating segment to %d\n", l_seg->newlen);
1528                                         break;
1529                                 };
1530
1531 #endif /* USE_JPWL */
1532                                 *(p_data_read) += l_seg->newlen;
1533
1534                                 l_seg->numpasses += l_seg->numnewpasses;
1535                                 l_cblk->numnewpasses -= l_seg->numnewpasses;
1536                                 if (l_cblk->numnewpasses > 0)
1537                                 {
1538                                         ++l_seg;
1539                                         ++l_cblk->numsegs;
1540                                 }
1541                         } while (l_cblk->numnewpasses > 0);
1542
1543                         ++l_cblk;
1544                 }
1545
1546                 ++l_band;
1547         }
1548
1549         return OPJ_TRUE;
1550 }
1551
1552
1553 static opj_bool t2_init_seg_v2(opj_tcd_cblk_dec_v2_t* cblk, OPJ_UINT32 index, OPJ_UINT32 cblksty, OPJ_UINT32 first)
1554 {
1555         opj_tcd_seg_t* seg = 00;
1556         OPJ_UINT32 l_nb_segs = index + 1;
1557
1558         if (l_nb_segs > cblk->m_current_max_segs) {
1559                 cblk->m_current_max_segs += J2K_DEFAULT_NB_SEGS;
1560
1561                 cblk->segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs, cblk->m_current_max_segs * sizeof(opj_tcd_seg_t));
1562                 if(! cblk->segs) {
1563                         return OPJ_FALSE;
1564                 }
1565         }
1566
1567         seg = &cblk->segs[index];
1568         memset(seg,0,sizeof(opj_tcd_seg_t));
1569
1570         if (cblksty & J2K_CCP_CBLKSTY_TERMALL) {
1571                 seg->maxpasses = 1;
1572         }
1573         else if (cblksty & J2K_CCP_CBLKSTY_LAZY) {
1574                 if (first) {
1575                         seg->maxpasses = 10;
1576                 } else {
1577                         seg->maxpasses = (((seg - 1)->maxpasses == 1) || ((seg - 1)->maxpasses == 10)) ? 2 : 1;
1578                 }
1579         } else {
1580                 seg->maxpasses = 109;
1581         }
1582
1583         return OPJ_TRUE;
1584 }