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