Output image color space set when decoding a JP2 file
[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 image_info Structure to create an index file
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_image_info_t *image_info, int tileno);
61 /**
62 @param seg
63 @param cblksty
64 @param first
65 */
66 static void t2_init_seg(opj_tcd_seg_t *seg, int cblksty, int first);
67 /**
68 Decode a packet of a tile from a source buffer
69 @param t2 T2 handle
70 @param src Source buffer
71 @param len Length of the source buffer
72 @param tile Tile for which to write the packets
73 @param tcp Tile coding parameters
74 @param pi Packet identity
75 @return 
76 */
77 static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_tile_t *tile, opj_tcp_t *tcp, opj_pi_iterator_t *pi);
78
79 /*@}*/
80
81 /*@}*/
82
83 /* ----------------------------------------------------------------------- */
84
85 /* #define RESTART 0x04 */
86
87 static void t2_putcommacode(opj_bio_t *bio, int n) {
88         while (--n >= 0) {
89                 bio_write(bio, 1, 1);
90         }
91         bio_write(bio, 0, 1);
92 }
93
94 static int t2_getcommacode(opj_bio_t *bio) {
95         int n;
96         for (n = 0; bio_read(bio, 1); n++) {
97                 ;
98         }
99         return n;
100 }
101
102 static void t2_putnumpasses(opj_bio_t *bio, int n) {
103         if (n == 1) {
104                 bio_write(bio, 0, 1);
105         } else if (n == 2) {
106                 bio_write(bio, 2, 2);
107         } else if (n <= 5) {
108                 bio_write(bio, 0xc | (n - 3), 4);
109         } else if (n <= 36) {
110                 bio_write(bio, 0x1e0 | (n - 6), 9);
111         } else if (n <= 164) {
112                 bio_write(bio, 0xff80 | (n - 37), 16);
113         }
114 }
115
116 static int t2_getnumpasses(opj_bio_t *bio) {
117         int n;
118         if (!bio_read(bio, 1))
119                 return 1;
120         if (!bio_read(bio, 1))
121                 return 2;
122         if ((n = bio_read(bio, 2)) != 3)
123                 return (3 + n);
124         if ((n = bio_read(bio, 5)) != 31)
125                 return (6 + n);
126         return (37 + bio_read(bio, 7));
127 }
128
129 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_image_info_t * image_info, int tileno) {
130         int bandno, cblkno;
131         unsigned char *sop = 0, *eph = 0;
132         unsigned char *c = dest;
133
134         int compno = pi->compno;        /* component value */
135         int resno  = pi->resno;         /* resolution level value */
136         int precno = pi->precno;        /* precinct value */
137         int layno  = pi->layno;         /* quality layer value */
138
139         opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
140         opj_tcd_resolution_t *res = &tilec->resolutions[resno];
141         
142         opj_bio_t *bio = NULL;  /* BIO component */
143         
144         /* <SOP 0xff91> */
145         if (tcp->csty & J2K_CP_CSTY_SOP) {
146                 sop = (unsigned char *) opj_malloc(6 * sizeof(unsigned char));
147                 sop[0] = 255;
148                 sop[1] = 145;
149                 sop[2] = 0;
150                 sop[3] = 4;
151                 sop[4] = (image_info->num % 65536) / 256;
152                 sop[5] = (image_info->num % 65536) % 256;
153                 memcpy(c, sop, 6);
154                 opj_free(sop);
155                 c += 6;
156         }
157         /* </SOP> */
158         
159         if (!layno) {
160                 for (bandno = 0; bandno < res->numbands; bandno++) {
161                         opj_tcd_band_t *band = &res->bands[bandno];
162                         opj_tcd_precinct_t *prc = &band->precincts[precno];
163                         tgt_reset(prc->incltree);
164                         tgt_reset(prc->imsbtree);
165                         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
166                                 opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];
167                                 cblk->numpasses = 0;
168                                 tgt_setvalue(prc->imsbtree, cblkno, band->numbps - cblk->numbps);
169                         }
170                 }
171         }
172         
173         bio = bio_create();
174         bio_init_enc(bio, c, length);
175         bio_write(bio, 1, 1);           /* Empty header bit */
176         
177         /* Writing Packet header */
178         for (bandno = 0; bandno < res->numbands; bandno++) {
179                 opj_tcd_band_t *band = &res->bands[bandno];
180                 opj_tcd_precinct_t *prc = &band->precincts[precno];
181                 for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
182                         opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];
183                         opj_tcd_layer_t *layer = &cblk->layers[layno];
184                         if (!cblk->numpasses && layer->numpasses) {
185                                 tgt_setvalue(prc->incltree, cblkno, layno);
186                         }
187                 }
188                 for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
189                         opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];
190                         opj_tcd_layer_t *layer = &cblk->layers[layno];
191                         int increment = 0;
192                         int nump = 0;
193                         int len = 0, passno;
194                         /* cblk inclusion bits */
195                         if (!cblk->numpasses) {
196                                 tgt_encode(bio, prc->incltree, cblkno, layno + 1);
197                         } else {
198                                 bio_write(bio, layer->numpasses != 0, 1);
199                         }
200                         /* if cblk not included, go to the next cblk  */
201                         if (!layer->numpasses) {
202                                 continue;
203                         }
204                         /* if first instance of cblk --> zero bit-planes information */
205                         if (!cblk->numpasses) {
206                                 cblk->numlenbits = 3;
207                                 tgt_encode(bio, prc->imsbtree, cblkno, 999);
208                         }
209                         /* number of coding passes included */
210                         t2_putnumpasses(bio, layer->numpasses);
211                         
212                         /* computation of the increase of the length indicator and insertion in the header     */
213                         for (passno = cblk->numpasses; passno < cblk->numpasses + layer->numpasses; passno++) {
214                                 opj_tcd_pass_t *pass = &cblk->passes[passno];
215                                 nump++;
216                                 len += pass->len;
217                                 if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
218                                         increment = int_max(increment, int_floorlog2(len) + 1 - (cblk->numlenbits + int_floorlog2(nump)));
219                                         len = 0;
220                                         nump = 0;
221                                 }
222                         }
223                         t2_putcommacode(bio, increment);
224
225                         /* computation of the new Length indicator */
226                         cblk->numlenbits += increment;
227
228                         /* insertion of the codeword segment length */
229                         for (passno = cblk->numpasses; passno < cblk->numpasses + layer->numpasses; passno++) {
230                                 opj_tcd_pass_t *pass = &cblk->passes[passno];
231                                 nump++;
232                                 len += pass->len;
233                                 if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
234                                         bio_write(bio, len, cblk->numlenbits + int_floorlog2(nump));
235                                         len = 0;
236                                         nump = 0;
237                                 }
238                         }
239                 }
240         }
241         
242         if (bio_flush(bio)) {
243                 return -999;            /* modified to eliminate longjmp !! */
244         }
245         
246         c += bio_numbytes(bio);
247
248         bio_destroy(bio);
249         
250         /* <EPH 0xff92> */
251         if (tcp->csty & J2K_CP_CSTY_EPH) {
252                 eph = (unsigned char *) opj_malloc(2 * sizeof(unsigned char));
253                 eph[0] = 255;
254                 eph[1] = 146;
255                 memcpy(c, eph, 2);
256                 opj_free(eph);
257                 c += 2;
258         }
259         /* </EPH> */
260         
261         /* Writing the packet body */
262         
263         for (bandno = 0; bandno < res->numbands; bandno++) {
264                 opj_tcd_band_t *band = &res->bands[bandno];
265                 opj_tcd_precinct_t *prc = &band->precincts[precno];
266                 for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
267                         opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];
268                         opj_tcd_layer_t *layer = &cblk->layers[layno];
269                         if (!layer->numpasses) {
270                                 continue;
271                         }
272                         if (c + layer->len > dest + length) {
273                                 return -999;
274                         }
275                         
276                         memcpy(c, layer->data, layer->len);
277                         cblk->numpasses += layer->numpasses;
278                         c += layer->len;
279                         /* ADD for index Cfr. Marcela --> delta disto by packet */
280                         if(image_info && image_info->index_write && image_info->index_on) {
281                                 opj_tile_info_t *info_TL = &image_info->tile[tileno];
282                                 opj_packet_info_t *info_PK = &info_TL->packet[image_info->num];
283                                 info_PK->disto += layer->disto;
284                                 if (image_info->D_max < info_PK->disto) {
285                                         image_info->D_max = info_PK->disto;
286                                 }
287                         }
288                         /* </ADD> */
289                 }
290         }
291         
292         return (c - dest);
293 }
294
295 static void t2_init_seg(opj_tcd_seg_t * seg, int cblksty, int first) {
296         seg->numpasses = 0;
297         seg->len = 0;
298         if (cblksty & J2K_CCP_CBLKSTY_TERMALL) {
299                 seg->maxpasses = 1;
300         }
301         else if (cblksty & J2K_CCP_CBLKSTY_LAZY) {
302                 if (first) {
303                         seg->maxpasses = 10;
304                 } else {
305                         seg->maxpasses = (((seg - 1)->maxpasses == 1) || ((seg - 1)->maxpasses == 10)) ? 2 : 1;
306                 }
307         } else {
308                 seg->maxpasses = 109;
309         }
310 }
311
312 static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_tile_t *tile, opj_tcp_t *tcp, opj_pi_iterator_t *pi) {
313         int bandno, cblkno;
314         unsigned char *c = src;
315
316         opj_cp_t *cp = t2->cp;
317
318         int compno = pi->compno;        /* component value */
319         int resno  = pi->resno;         /* resolution level value */
320         int precno = pi->precno;        /* precinct value */
321         int layno  = pi->layno;         /* quality layer value */
322
323         opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
324         opj_tcd_resolution_t *res = &tilec->resolutions[resno];
325         
326         unsigned char *hd = NULL;
327         int present;
328         
329         opj_bio_t *bio = NULL;  /* BIO component */
330         
331         if (layno == 0) {
332                 for (bandno = 0; bandno < res->numbands; bandno++) {
333                         opj_tcd_band_t *band = &res->bands[bandno];
334                         opj_tcd_precinct_t *prc = &band->precincts[precno];
335                         
336                         if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)) continue;
337                         
338                         tgt_reset(prc->incltree);
339                         tgt_reset(prc->imsbtree);
340                         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
341                                 opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];
342                                 cblk->numsegs = 0;
343                         }
344                 }
345         }
346         
347         /* SOP markers */
348         
349         if (tcp->csty & J2K_CP_CSTY_SOP) {
350                 if ((*c) != 0xff || (*(c + 1) != 0x91)) {
351                         opj_event_msg(t2->cinfo, EVT_WARNING, "Expected SOP marker\n");
352                 } else {
353                         c += 6;
354                 }
355                 
356                 /** TODO : check the Nsop value */
357         }
358         
359         /* 
360         When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
361         This part deal with this caracteristic
362         step 1: Read packet header in the saved structure
363         step 2: Return to codestream for decoding 
364         */
365
366         bio = bio_create();
367         
368         if (cp->ppm == 1) {             /* PPM */
369                 hd = cp->ppm_data;
370                 bio_init_dec(bio, hd, cp->ppm_len);
371         } else if (tcp->ppt == 1) {     /* PPT */
372                 hd = tcp->ppt_data;
373                 bio_init_dec(bio, hd, tcp->ppt_len);
374         } else {                        /* Normal Case */
375                 hd = c;
376                 bio_init_dec(bio, hd, src+len-hd);
377         }
378         
379         present = bio_read(bio, 1);
380         
381         if (!present) {
382                 bio_inalign(bio);
383                 hd += bio_numbytes(bio);
384                 bio_destroy(bio);
385                 
386                 /* EPH markers */
387                 
388                 if (tcp->csty & J2K_CP_CSTY_EPH) {
389                         if ((*hd) != 0xff || (*(hd + 1) != 0x92)) {
390                                 printf("Error : expected EPH marker\n");
391                         } else {
392                                 hd += 2;
393                         }
394                 }
395                 
396                 if (cp->ppm == 1) {             /* PPM case */
397                         cp->ppm_len += cp->ppm_data-hd;
398                         cp->ppm_data = hd;
399                         return (c - src);
400                 }
401                 if (tcp->ppt == 1) {    /* PPT case */
402                         tcp->ppt_len+=tcp->ppt_data-hd;
403                         tcp->ppt_data = hd;
404                         return (c - src);
405                 }
406                 
407                 return (hd - src);
408         }
409         
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                 for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
417                         int included, increment, n;
418                         opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];
419                         opj_tcd_seg_t *seg = NULL;
420                         /* if cblk not yet included before --> inclusion tagtree */
421                         if (!cblk->numsegs) {
422                                 included = tgt_decode(bio, prc->incltree, cblkno, layno + 1);
423                                 /* else one bit */
424                         } else {
425                                 included = bio_read(bio, 1);
426                         }
427                         /* if cblk not included */
428                         if (!included) {
429                                 cblk->numnewpasses = 0;
430                                 continue;
431                         }
432                         /* if cblk not yet included --> zero-bitplane tagtree */
433                         if (!cblk->numsegs) {
434                                 int i, numimsbs;
435                                 for (i = 0; !tgt_decode(bio, prc->imsbtree, cblkno, i); i++) {
436                                         ;
437                                 }
438                                 numimsbs = i - 1;
439                                 cblk->numbps = band->numbps - numimsbs;
440                                 cblk->numlenbits = 3;
441                         }
442                         /* number of coding passes */
443                         cblk->numnewpasses = t2_getnumpasses(bio);
444                         increment = t2_getcommacode(bio);
445                         /* length indicator increment */
446                         cblk->numlenbits += increment;
447                         if (!cblk->numsegs) {
448                                 seg = &cblk->segs[0];
449                                 t2_init_seg(seg, tcp->tccps[compno].cblksty, 1);
450                         } else {
451                                 seg = &cblk->segs[cblk->numsegs - 1];
452                                 if (seg->numpasses == seg->maxpasses) {
453                                         t2_init_seg(++seg, tcp->tccps[compno].cblksty, 0);
454                                 }
455                         }
456                         n = cblk->numnewpasses;
457                         
458                         do {
459                                 seg->numnewpasses = int_min(seg->maxpasses - seg->numpasses, n);
460                                 seg->newlen = bio_read(bio, cblk->numlenbits + int_floorlog2(seg->numnewpasses));
461                                 n -= seg->numnewpasses;
462                                 if (n > 0) {
463                                         t2_init_seg(++seg, tcp->tccps[compno].cblksty, 0);
464                                 }
465                         } while (n > 0);
466                 }
467         }
468         
469         if (bio_inalign(bio)) {
470                 bio_destroy(bio);
471                 return -999;
472         }
473         
474         hd += bio_numbytes(bio);
475         bio_destroy(bio);
476         
477         /* EPH markers */
478         if (tcp->csty & J2K_CP_CSTY_EPH) {
479                 if ((*hd) != 0xff || (*(hd + 1) != 0x92)) {
480                         opj_event_msg(t2->cinfo, EVT_ERROR, "Expected EPH marker\n");
481                 } else {
482                         hd += 2;
483                 }
484         }
485         
486         if (cp->ppm==1) {
487                 cp->ppm_len+=cp->ppm_data-hd;
488                 cp->ppm_data = hd;
489         } else if (tcp->ppt == 1) {
490                 tcp->ppt_len+=tcp->ppt_data-hd;
491                 tcp->ppt_data = hd;
492         } else {
493                 c=hd;
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                         opj_tcd_cblk_t *cblk = &prc->cblks[cblkno];
504                         opj_tcd_seg_t *seg = NULL;
505                         if (!cblk->numnewpasses)
506                                 continue;
507                         if (!cblk->numsegs) {
508                                 seg = &cblk->segs[0];
509                                 cblk->numsegs++;
510                                 cblk->len = 0;
511                         } else {
512                                 seg = &cblk->segs[cblk->numsegs - 1];
513                                 if (seg->numpasses == seg->maxpasses) {
514                                         seg++;
515                                         cblk->numsegs++;
516                                 }
517                         }
518                         
519                         do {
520                                 if (c + seg->newlen > src + len) {
521                                         return -999;
522                                 }
523
524 #ifdef USE_JPWL
525                         /* we need here a j2k handle to verify if making a check to
526                         the validity of cblocks parameters is selected from user (-W) */
527
528                                 /* let's check that we are not exceeding */
529                                 if ((cblk->len + seg->newlen) > 8192) {
530                                         opj_event_msg(t2->cinfo, EVT_WARNING,
531                                                 "JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
532                                                 seg->newlen, cblkno, precno, bandno, resno, compno);
533                                         if (!JPWL_ASSUME) {
534                                                 opj_event_msg(t2->cinfo, EVT_ERROR, "JPWL: giving up\n");
535                                                 return -999;
536                                         }
537                                         seg->newlen = 8192 - cblk->len;
538                                         opj_event_msg(t2->cinfo, EVT_WARNING, "      - truncating segment to %d\n", seg->newlen);
539                                         break;
540                                 };
541
542 #endif /* USE_JPWL */
543                                 
544                                 memcpy(cblk->data + cblk->len, c, seg->newlen);
545                                 if (seg->numpasses == 0) {
546                                         seg->data = cblk->data + cblk->len;
547                                 }
548                                 c += seg->newlen;
549                                 cblk->len += seg->newlen;
550                                 seg->len += seg->newlen;
551                                 seg->numpasses += seg->numnewpasses;
552                                 cblk->numnewpasses -= seg->numnewpasses;
553                                 if (cblk->numnewpasses > 0) {
554                                         seg++;
555                                         cblk->numsegs++;
556                                 }
557                         } while (cblk->numnewpasses > 0);
558                 }
559         }
560         
561         return (c - src);
562 }
563
564 /* ----------------------------------------------------------------------- */
565
566 int t2_encode_packets(opj_t2_t* t2,int tileno, opj_tcd_tile_t *tile, int maxlayers, unsigned char *dest, int len, opj_image_info_t *image_info,int tpnum, int tppos,int pino, J2K_T2_MODE t2_mode){
567         unsigned char *c = dest;
568         int e = 0;
569         int compno;
570         int comp_len = 0;
571         opj_pi_iterator_t *pi = NULL;
572         int poc;
573         opj_image_t *image = t2->image;
574         opj_cp_t *cp = t2->cp;
575         int pocno = cp->cinema == CINEMA4K_24? 2: 1;
576         int maxcomp = cp->max_comp_size > 0 ? image->numcomps : 1;
577         
578         pi = pi_initialise_encode(image, cp, tileno, t2_mode);
579         if(!pi) {
580                 /* TODO: throw an error */
581                 return -999;
582         }
583         
584         if(t2_mode == THRESH_CALC ){ /* Calculating threshold */
585                 for(compno = 0; compno < maxcomp; compno++ ){
586                         for(poc = 0; poc < pocno ; poc++){
587                                 int comp_len = 0;
588                                 int tpnum = compno;
589                                 pi_create_encode(pi, cp,tileno,poc,tpnum,tppos); 
590                                 while (pi_next(&pi[poc])) {
591                                         if (pi[poc].layno < maxlayers) {
592                                                 e = t2_encode_packet(tile, &cp->tcps[tileno], &pi[poc], c, dest + len - c, image_info, tileno);
593                                                 comp_len = comp_len + e;
594                                                 if (e == -999) {
595                                                         break;
596                                                 } else {
597                                                         c += e;
598                                                 }
599                                         }
600                                 }
601                                 if (e == -999) break;
602                                 if (cp->max_comp_size){
603                                         if (comp_len > cp->max_comp_size){
604                                                 e = -999;
605                                                 break;
606                                         }
607                                 }
608                         }
609                         if (e == -999)  break;
610                 }
611         }else{  /* t2_mode == FINAL_PASS  */
612                 pi_create_encode(pi, cp,tileno,pino,tpnum,tppos); 
613                 while (pi_next(&pi[pino])) {
614                         if (pi[pino].layno < maxlayers) {
615                                 e = t2_encode_packet(tile, &cp->tcps[tileno], &pi[pino], c, dest + len - c, image_info, tileno);
616                                 if (e == -999) {
617                                         break;
618                                 } else {
619                                         c += e;
620                                 }
621                                 /* INDEX >> */
622                                 if(image_info && image_info->index_on) {
623                                         if(image_info->index_write) {
624                                                 opj_tile_info_t *info_TL = &image_info->tile[tileno];
625                                                 opj_packet_info_t *info_PK = &info_TL->packet[image_info->num];
626                                                 if (!image_info->num) {
627                                                         info_PK->start_pos = info_TL->end_header + 1;
628                                                 } else {
629                                                         info_PK->start_pos = (cp->tp_on && info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[image_info->num - 1].end_pos + 1;
630                                                 }
631                                                 info_PK->end_pos = info_PK->start_pos + e - 1;
632                                         }
633                                         
634                                         image_info->num++;
635                                 }
636                                 /* << INDEX */
637                         }
638                 }
639         }
640         
641         pi_destroy(pi, cp, tileno);
642         
643         if (e == -999) {
644                 return e;
645         }
646         
647   return (c - dest);
648 }
649
650 int t2_decode_packets(opj_t2_t *t2, unsigned char *src, int len, int tileno, opj_tcd_tile_t *tile) {
651         unsigned char *c = src;
652         opj_pi_iterator_t *pi;
653         int pino, e = 0;
654         int n = 0;
655
656         opj_image_t *image = t2->image;
657         opj_cp_t *cp = t2->cp;
658         
659         /* create a packet iterator */
660         pi = pi_create_decode(image, cp, tileno);
661         if(!pi) {
662                 /* TODO: throw an error */
663                 return -999;
664         }
665         
666         for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++) {
667                 while (pi_next(&pi[pino])) {
668                         if ((cp->layer==0) || (cp->layer>=((pi[pino].layno)+1))) {
669                                 e = t2_decode_packet(t2, c, src + len - c, tile, &cp->tcps[tileno], &pi[pino]);
670                         } else {
671                                 e = 0;
672                         }
673                         
674                         /* progression in resolution */
675                         image->comps[pi[pino].compno].resno_decoded =   
676                                 (e > 0) ? 
677                                 int_max(pi[pino].resno, image->comps[pi[pino].compno].resno_decoded) 
678                                 : image->comps[pi[pino].compno].resno_decoded;
679                         n++;
680                         
681                         if (e == -999) {                /* ADD */
682                                 break;
683                         } else {
684                                 c += e;
685                         }
686                 }
687         }
688
689         /* don't forget to release pi */
690         pi_destroy(pi, cp, tileno);
691         
692         if (e == -999) {
693                 return e;
694         }
695         
696     return (c - src);
697 }
698
699 /* ----------------------------------------------------------------------- */
700
701 opj_t2_t* t2_create(opj_common_ptr cinfo, opj_image_t *image, opj_cp_t *cp) {
702         /* create the tcd structure */
703         opj_t2_t *t2 = (opj_t2_t*)opj_malloc(sizeof(opj_t2_t));
704         if(!t2) return NULL;
705         t2->cinfo = cinfo;
706         t2->image = image;
707         t2->cp = cp;
708
709         return t2;
710 }
711
712 void t2_destroy(opj_t2_t *t2) {
713         if(t2) {
714                 opj_free(t2);
715         }
716 }
717