Merge pull request #1140 from bukatlib/fix_relpath
[openjpeg.git] / src / lib / openmj2 / t2.c
1 /*
2  * The copyright in this software is being made available under the 2-clauses
3  * BSD License, included below. This software may be subject to other third
4  * party and contributor rights, including patent rights, and no such rights
5  * are granted under this license.
6  *
7  * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
8  * Copyright (c) 2002-2014, Professor Benoit Macq
9  * Copyright (c) 2001-2003, David Janssens
10  * Copyright (c) 2002-2003, Yannick Verschueren
11  * Copyright (c) 2003-2007, Francois-Olivier Devaux
12  * Copyright (c) 2003-2014, Antonin Descampe
13  * Copyright (c) 2005, Herve Drolon, FreeImage Team
14  * All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
26  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
29  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  */
37
38 #include "opj_includes.h"
39
40 /** @defgroup T2 T2 - Implementation of a tier-2 coding */
41 /*@{*/
42
43 /** @name Local static functions */
44 /*@{*/
45
46 static void t2_putcommacode(opj_bio_t *bio, int n);
47 static int t2_getcommacode(opj_bio_t *bio);
48 /**
49 Variable length code for signalling delta Zil (truncation point)
50 @param bio Bit Input/Output component
51 @param n delta Zil
52 */
53 static void t2_putnumpasses(opj_bio_t *bio, int n);
54 static int t2_getnumpasses(opj_bio_t *bio);
55 /**
56 Encode a packet of a tile to a destination buffer
57 @param tile Tile for which to write the packets
58 @param tcp Tile coding parameters
59 @param pi Packet identity
60 @param dest Destination buffer
61 @param len Length of the destination buffer
62 @param cstr_info Codestream information structure
63 @param tileno Number of the tile encoded
64 @return
65 */
66 static int t2_encode_packet(opj_tcd_tile_t *tile, opj_tcp_t *tcp,
67                             opj_pi_iterator_t *pi, unsigned char *dest, int len,
68                             opj_codestream_info_t *cstr_info, int tileno);
69 /**
70 @param cblk
71 @param index
72 @param cblksty
73 @param first
74 */
75 static opj_bool t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty,
76                             int first);
77 /**
78 Decode a packet of a tile from a source buffer
79 @param t2 T2 handle
80 @param src Source buffer
81 @param len Length of the source buffer
82 @param tile Tile for which to write the packets
83 @param tcp Tile coding parameters
84 @param pi Packet identity
85 @param pack_info Packet information
86 @return
87 */
88 static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len,
89                             opj_tcd_tile_t *tile,
90                             opj_tcp_t *tcp, opj_pi_iterator_t *pi, opj_packet_info_t *pack_info);
91
92 /*@}*/
93
94 /*@}*/
95
96 /* ----------------------------------------------------------------------- */
97
98 /* #define RESTART 0x04 */
99
100 static void t2_putcommacode(opj_bio_t *bio, int n)
101 {
102     while (--n >= 0) {
103         bio_write(bio, 1, 1);
104     }
105     bio_write(bio, 0, 1);
106 }
107
108 static int t2_getcommacode(opj_bio_t *bio)
109 {
110     int n;
111     for (n = 0; bio_read(bio, 1); n++) {
112         ;
113     }
114     return n;
115 }
116
117 static void t2_putnumpasses(opj_bio_t *bio, int n)
118 {
119     if (n == 1) {
120         bio_write(bio, 0, 1);
121     } else if (n == 2) {
122         bio_write(bio, 2, 2);
123     } else if (n <= 5) {
124         bio_write(bio, 0xc | (n - 3), 4);
125     } else if (n <= 36) {
126         bio_write(bio, 0x1e0 | (n - 6), 9);
127     } else if (n <= 164) {
128         bio_write(bio, 0xff80 | (n - 37), 16);
129     }
130 }
131
132 static int t2_getnumpasses(opj_bio_t *bio)
133 {
134     int n;
135     if (!bio_read(bio, 1)) {
136         return 1;
137     }
138     if (!bio_read(bio, 1)) {
139         return 2;
140     }
141     if ((n = bio_read(bio, 2)) != 3) {
142         return (3 + n);
143     }
144     if ((n = bio_read(bio, 5)) != 31) {
145         return (6 + n);
146     }
147     return (37 + bio_read(bio, 7));
148 }
149
150 static int t2_encode_packet(opj_tcd_tile_t * tile, opj_tcp_t * tcp,
151                             opj_pi_iterator_t *pi, unsigned char *dest, int length,
152                             opj_codestream_info_t *cstr_info, int tileno)
153 {
154     int bandno, cblkno;
155     unsigned char *c = dest;
156
157     int compno = pi->compno;    /* component value */
158     int resno  = pi->resno;     /* resolution level value */
159     int precno = pi->precno;    /* precinct value */
160     int layno  = pi->layno;     /* quality layer value */
161
162     opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
163     opj_tcd_resolution_t *res = &tilec->resolutions[resno];
164
165     opj_bio_t *bio = NULL;  /* BIO component */
166
167     /* <SOP 0xff91> */
168     if (tcp->csty & J2K_CP_CSTY_SOP) {
169         c[0] = 255;
170         c[1] = 145;
171         c[2] = 0;
172         c[3] = 4;
173         c[4] = (unsigned char)((tile->packno % 65536) / 256);
174         c[5] = (unsigned char)((tile->packno % 65536) % 256);
175         c += 6;
176     }
177     /* </SOP> */
178
179     if (!layno) {
180         for (bandno = 0; bandno < res->numbands; bandno++) {
181             opj_tcd_band_t *band = &res->bands[bandno];
182             opj_tcd_precinct_t *prc = &band->precincts[precno];
183             tgt_reset(prc->incltree);
184             tgt_reset(prc->imsbtree);
185             for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
186                 opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno];
187                 cblk->numpasses = 0;
188                 tgt_setvalue(prc->imsbtree, cblkno, band->numbps - cblk->numbps);
189             }
190         }
191     }
192
193     bio = bio_create();
194     bio_init_enc(bio, c, length);
195     bio_write(bio, 1, 1);       /* Empty header bit */
196
197     /* Writing Packet header */
198     for (bandno = 0; bandno < res->numbands; bandno++) {
199         opj_tcd_band_t *band = &res->bands[bandno];
200         opj_tcd_precinct_t *prc = &band->precincts[precno];
201         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
202             opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno];
203             opj_tcd_layer_t *layer = &cblk->layers[layno];
204             if (!cblk->numpasses && layer->numpasses) {
205                 tgt_setvalue(prc->incltree, cblkno, layno);
206             }
207         }
208         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
209             opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno];
210             opj_tcd_layer_t *layer = &cblk->layers[layno];
211             int increment = 0;
212             int nump = 0;
213             int len = 0, passno;
214             /* cblk inclusion bits */
215             if (!cblk->numpasses) {
216                 tgt_encode(bio, prc->incltree, cblkno, layno + 1);
217             } else {
218                 bio_write(bio, layer->numpasses != 0, 1);
219             }
220             /* if cblk not included, go to the next cblk  */
221             if (!layer->numpasses) {
222                 continue;
223             }
224             /* if first instance of cblk --> zero bit-planes information */
225             if (!cblk->numpasses) {
226                 cblk->numlenbits = 3;
227                 tgt_encode(bio, prc->imsbtree, cblkno, 999);
228             }
229             /* number of coding passes included */
230             t2_putnumpasses(bio, layer->numpasses);
231
232             /* computation of the increase of the length indicator and insertion in the header     */
233             for (passno = cblk->numpasses; passno < cblk->numpasses + layer->numpasses;
234                     passno++) {
235                 opj_tcd_pass_t *pass = &cblk->passes[passno];
236                 nump++;
237                 len += pass->len;
238                 if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
239                     increment = int_max(increment,
240                                         int_floorlog2(len) + 1 - (cblk->numlenbits + int_floorlog2(nump)));
241                     len = 0;
242                     nump = 0;
243                 }
244             }
245             t2_putcommacode(bio, increment);
246
247             /* computation of the new Length indicator */
248             cblk->numlenbits += increment;
249
250             /* insertion of the codeword segment length */
251             for (passno = cblk->numpasses; passno < cblk->numpasses + layer->numpasses;
252                     passno++) {
253                 opj_tcd_pass_t *pass = &cblk->passes[passno];
254                 nump++;
255                 len += pass->len;
256                 if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
257                     bio_write(bio, len, cblk->numlenbits + int_floorlog2(nump));
258                     len = 0;
259                     nump = 0;
260                 }
261             }
262         }
263     }
264
265     if (bio_flush(bio)) {
266         bio_destroy(bio);
267         return -999;        /* modified to eliminate longjmp !! */
268     }
269
270     c += bio_numbytes(bio);
271     bio_destroy(bio);
272
273     /* <EPH 0xff92> */
274     if (tcp->csty & J2K_CP_CSTY_EPH) {
275         c[0] = 255;
276         c[1] = 146;
277         c += 2;
278     }
279     /* </EPH> */
280
281     /* << INDEX */
282     /* End of packet header position. Currently only represents the distance to start of packet
283     // Will be updated later by incrementing with packet start value */
284     if (cstr_info && cstr_info->index_write) {
285         opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno];
286         info_PK->end_ph_pos = (int)(c - dest);
287     }
288     /* INDEX >> */
289
290     /* Writing the packet body */
291
292     for (bandno = 0; bandno < res->numbands; bandno++) {
293         opj_tcd_band_t *band = &res->bands[bandno];
294         opj_tcd_precinct_t *prc = &band->precincts[precno];
295         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
296             opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno];
297             opj_tcd_layer_t *layer = &cblk->layers[layno];
298             if (!layer->numpasses) {
299                 continue;
300             }
301             if (c + layer->len > dest + length) {
302                 return -999;
303             }
304
305             memcpy(c, layer->data, layer->len);
306             cblk->numpasses += layer->numpasses;
307             c += layer->len;
308             /* << INDEX */
309             if (cstr_info && cstr_info->index_write) {
310                 opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno];
311                 info_PK->disto += layer->disto;
312                 if (cstr_info->D_max < info_PK->disto) {
313                     cstr_info->D_max = info_PK->disto;
314                 }
315             }
316             /* INDEX >> */
317         }
318     }
319
320     return (c - dest);
321 }
322
323 static opj_bool t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty,
324                             int first)
325 {
326     opj_tcd_seg_t* seg;
327     opj_tcd_seg_t* segs;
328     segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs,
329                                         (index + 1) * sizeof(opj_tcd_seg_t));
330
331     if (segs == NULL) {
332         return OPJ_FALSE;
333     }
334     cblk->segs = segs;
335
336     seg = &cblk->segs[index];
337     seg->data = NULL;
338     seg->dataindex = 0;
339     seg->numpasses = 0;
340     seg->len = 0;
341     if (cblksty & J2K_CCP_CBLKSTY_TERMALL) {
342         seg->maxpasses = 1;
343     } else if (cblksty & J2K_CCP_CBLKSTY_LAZY) {
344         if (first) {
345             seg->maxpasses = 10;
346         } else {
347             seg->maxpasses = (((seg - 1)->maxpasses == 1) ||
348                               ((seg - 1)->maxpasses == 10)) ? 2 : 1;
349         }
350     } else {
351         seg->maxpasses = 109;
352     }
353
354     return OPJ_TRUE;
355 }
356
357 static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len,
358                             opj_tcd_tile_t *tile,
359                             opj_tcp_t *tcp, opj_pi_iterator_t *pi, opj_packet_info_t *pack_info)
360 {
361     int bandno, cblkno;
362     unsigned char *c = src;
363
364     opj_cp_t *cp = t2->cp;
365
366     int compno = pi->compno;    /* component value */
367     int resno  = pi->resno;     /* resolution level value */
368     int precno = pi->precno;    /* precinct value */
369     int layno  = pi->layno;     /* quality layer value */
370
371     opj_tcd_resolution_t* res = &tile->comps[compno].resolutions[resno];
372
373     unsigned char *hd = NULL;
374     int present;
375
376     opj_bio_t *bio = NULL;  /* BIO component */
377
378     if (layno == 0) {
379         for (bandno = 0; bandno < res->numbands; bandno++) {
380             opj_tcd_band_t *band = &res->bands[bandno];
381             opj_tcd_precinct_t *prc = &band->precincts[precno];
382
383             if ((band->x1 - band->x0 == 0) || (band->y1 - band->y0 == 0)) {
384                 continue;
385             }
386
387             tgt_reset(prc->incltree);
388             tgt_reset(prc->imsbtree);
389             for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
390                 opj_tcd_cblk_dec_t* cblk = &prc->cblks.dec[cblkno];
391                 cblk->numsegs = 0;
392             }
393         }
394     }
395
396     /* SOP markers */
397
398     if (tcp->csty & J2K_CP_CSTY_SOP) {
399         if ((*c) != 0xff || (*(c + 1) != 0x91)) {
400             opj_event_msg(t2->cinfo, EVT_WARNING, "Expected SOP marker\n");
401         } else {
402             c += 6;
403         }
404
405         /** TODO : check the Nsop value */
406     }
407
408     /*
409     When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
410     This part deal with this caracteristic
411     step 1: Read packet header in the saved structure
412     step 2: Return to codestream for decoding
413     */
414
415     bio = bio_create();
416
417     if (cp->ppm == 1) {     /* PPM */
418         hd = cp->ppm_data;
419         bio_init_dec(bio, hd, cp->ppm_len);
420     } else if (tcp->ppt == 1) { /* PPT */
421         hd = tcp->ppt_data;
422         bio_init_dec(bio, hd, tcp->ppt_len);
423     } else {            /* Normal Case */
424         hd = c;
425         bio_init_dec(bio, hd, src + len - hd);
426     }
427
428     present = bio_read(bio, 1);
429
430     if (!present) {
431         bio_inalign(bio);
432         hd += bio_numbytes(bio);
433         bio_destroy(bio);
434
435         /* EPH markers */
436
437         if (tcp->csty & J2K_CP_CSTY_EPH) {
438             if ((*hd) != 0xff || (*(hd + 1) != 0x92)) {
439                 printf("Error : expected EPH marker\n");
440             } else {
441                 hd += 2;
442             }
443         }
444
445         /* << INDEX */
446         /* End of packet header position. Currently only represents the distance to start of packet
447         // Will be updated later by incrementing with packet start value*/
448         if (pack_info) {
449             pack_info->end_ph_pos = (int)(c - src);
450         }
451         /* INDEX >> */
452
453         if (cp->ppm == 1) {     /* PPM case */
454             cp->ppm_len += cp->ppm_data - hd;
455             cp->ppm_data = hd;
456             return (c - src);
457         }
458         if (tcp->ppt == 1) {    /* PPT case */
459             tcp->ppt_len += tcp->ppt_data - hd;
460             tcp->ppt_data = hd;
461             return (c - src);
462         }
463
464         return (hd - src);
465     }
466
467     for (bandno = 0; bandno < res->numbands; bandno++) {
468         opj_tcd_band_t *band = &res->bands[bandno];
469         opj_tcd_precinct_t *prc = &band->precincts[precno];
470
471         if ((band->x1 - band->x0 == 0) || (band->y1 - band->y0 == 0)) {
472             continue;
473         }
474
475         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
476             int included, increment, n, segno;
477             opj_tcd_cblk_dec_t* cblk = &prc->cblks.dec[cblkno];
478             /* if cblk not yet included before --> inclusion tagtree */
479             if (!cblk->numsegs) {
480                 included = tgt_decode(bio, prc->incltree, cblkno, layno + 1);
481                 /* else one bit */
482             } else {
483                 included = bio_read(bio, 1);
484             }
485             /* if cblk not included */
486             if (!included) {
487                 cblk->numnewpasses = 0;
488                 continue;
489             }
490             /* if cblk not yet included --> zero-bitplane tagtree */
491             if (!cblk->numsegs) {
492                 int i, numimsbs;
493                 for (i = 0; !tgt_decode(bio, prc->imsbtree, cblkno, i); i++) {
494                     ;
495                 }
496                 numimsbs = i - 1;
497                 cblk->numbps = band->numbps - numimsbs;
498                 cblk->numlenbits = 3;
499             }
500             /* number of coding passes */
501             cblk->numnewpasses = t2_getnumpasses(bio);
502             increment = t2_getcommacode(bio);
503             /* length indicator increment */
504             cblk->numlenbits += increment;
505             segno = 0;
506             if (!cblk->numsegs) {
507                 if (!t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 1)) {
508                     opj_event_msg(t2->cinfo, EVT_ERROR, "Out of memory\n");
509                     bio_destroy(bio);
510                     return -999;
511                 }
512             } else {
513                 segno = cblk->numsegs - 1;
514                 if (cblk->segs[segno].numpasses == cblk->segs[segno].maxpasses) {
515                     ++segno;
516                     if (!t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0)) {
517                         opj_event_msg(t2->cinfo, EVT_ERROR, "Out of memory\n");
518                         bio_destroy(bio);
519                         return -999;
520                     }
521                 }
522             }
523             n = cblk->numnewpasses;
524
525             do {
526                 cblk->segs[segno].numnewpasses = int_min(cblk->segs[segno].maxpasses -
527                                                  cblk->segs[segno].numpasses, n);
528                 cblk->segs[segno].newlen = bio_read(bio,
529                                                     cblk->numlenbits + int_floorlog2(cblk->segs[segno].numnewpasses));
530                 n -= cblk->segs[segno].numnewpasses;
531                 if (n > 0) {
532                     ++segno;
533                     if (!t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0)) {
534                         opj_event_msg(t2->cinfo, EVT_ERROR, "Out of memory\n");
535                         bio_destroy(bio);
536                         return -999;
537                     }
538                 }
539             } while (n > 0);
540         }
541     }
542
543     if (bio_inalign(bio)) {
544         bio_destroy(bio);
545         return -999;
546     }
547
548     hd += bio_numbytes(bio);
549     bio_destroy(bio);
550
551     /* EPH markers */
552     if (tcp->csty & J2K_CP_CSTY_EPH) {
553         if ((*hd) != 0xff || (*(hd + 1) != 0x92)) {
554             opj_event_msg(t2->cinfo, EVT_ERROR, "Expected EPH marker\n");
555             return -999;
556         } else {
557             hd += 2;
558         }
559     }
560
561     /* << INDEX */
562     /* End of packet header position. Currently only represents the distance to start of packet
563     // Will be updated later by incrementing with packet start value*/
564     if (pack_info) {
565         pack_info->end_ph_pos = (int)(hd - src);
566     }
567     /* INDEX >> */
568
569     if (cp->ppm == 1) {
570         cp->ppm_len += cp->ppm_data - hd;
571         cp->ppm_data = hd;
572     } else if (tcp->ppt == 1) {
573         tcp->ppt_len += tcp->ppt_data - hd;
574         tcp->ppt_data = hd;
575     } else {
576         c = hd;
577     }
578
579     for (bandno = 0; bandno < res->numbands; bandno++) {
580         opj_tcd_band_t *band = &res->bands[bandno];
581         opj_tcd_precinct_t *prc = &band->precincts[precno];
582
583         if ((band->x1 - band->x0 == 0) || (band->y1 - band->y0 == 0)) {
584             continue;
585         }
586
587         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
588             opj_tcd_cblk_dec_t* cblk = &prc->cblks.dec[cblkno];
589             opj_tcd_seg_t *seg = NULL;
590             if (!cblk->numnewpasses) {
591                 continue;
592             }
593             if (!cblk->numsegs) {
594                 seg = &cblk->segs[0];
595                 cblk->numsegs++;
596                 cblk->len = 0;
597             } else {
598                 seg = &cblk->segs[cblk->numsegs - 1];
599                 if (seg->numpasses == seg->maxpasses) {
600                     seg++;
601                     cblk->numsegs++;
602                 }
603             }
604
605             do {
606                 if (c + seg->newlen > src + len) {
607                     return -999;
608                 }
609
610 #ifdef USE_JPWL
611                 /* we need here a j2k handle to verify if making a check to
612                 the validity of cblocks parameters is selected from user (-W) */
613
614                 /* let's check that we are not exceeding */
615                 if ((cblk->len + seg->newlen) > 8192) {
616                     opj_event_msg(t2->cinfo, EVT_WARNING,
617                                   "JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
618                                   seg->newlen, cblkno, precno, bandno, resno, compno);
619                     if (!JPWL_ASSUME) {
620                         opj_event_msg(t2->cinfo, EVT_ERROR, "JPWL: giving up\n");
621                         return -999;
622                     }
623                     seg->newlen = 8192 - cblk->len;
624                     opj_event_msg(t2->cinfo, EVT_WARNING, "      - truncating segment to %d\n",
625                                   seg->newlen);
626                     break;
627                 };
628
629 #endif /* USE_JPWL */
630
631                 cblk->data = (unsigned char*) opj_realloc(cblk->data,
632                              (cblk->len + seg->newlen) * sizeof(unsigned char));
633                 memcpy(cblk->data + cblk->len, c, seg->newlen);
634                 if (seg->numpasses == 0) {
635                     seg->data = &cblk->data;
636                     seg->dataindex = cblk->len;
637                 }
638                 c += seg->newlen;
639                 cblk->len += seg->newlen;
640                 seg->len += seg->newlen;
641                 seg->numpasses += seg->numnewpasses;
642                 cblk->numnewpasses -= seg->numnewpasses;
643                 if (cblk->numnewpasses > 0) {
644                     seg++;
645                     cblk->numsegs++;
646                 }
647             } while (cblk->numnewpasses > 0);
648         }
649     }
650
651     return (c - src);
652 }
653
654 /* ----------------------------------------------------------------------- */
655
656 int t2_encode_packets(opj_t2_t* t2, int tileno, opj_tcd_tile_t *tile,
657                       int maxlayers, unsigned char *dest, int len, opj_codestream_info_t *cstr_info,
658                       int tpnum, int tppos, int pino, J2K_T2_MODE t2_mode, int cur_totnum_tp)
659 {
660     unsigned char *c = dest;
661     int e = 0;
662     int compno;
663     opj_pi_iterator_t *pi = NULL;
664     int poc;
665     opj_image_t *image = t2->image;
666     opj_cp_t *cp = t2->cp;
667     opj_tcp_t *tcp = &cp->tcps[tileno];
668     int pocno = cp->cinema == CINEMA4K_24 ? 2 : 1;
669     int maxcomp = cp->max_comp_size > 0 ? image->numcomps : 1;
670
671     pi = pi_initialise_encode(image, cp, tileno, t2_mode);
672     if (!pi) {
673         /* TODO: throw an error */
674         return -999;
675     }
676
677     if (t2_mode == THRESH_CALC) { /* Calculating threshold */
678         for (compno = 0; compno < maxcomp; compno++) {
679             for (poc = 0; poc < pocno ; poc++) {
680                 int comp_len = 0;
681                 int tpnum = compno;
682                 if (pi_create_encode(pi, cp, tileno, poc, tpnum, tppos, t2_mode,
683                                      cur_totnum_tp)) {
684                     opj_event_msg(t2->cinfo, EVT_ERROR, "Error initializing Packet Iterator\n");
685                     pi_destroy(pi, cp, tileno);
686                     return -999;
687                 }
688                 while (pi_next(&pi[poc])) {
689                     if (pi[poc].layno < maxlayers) {
690                         e = t2_encode_packet(tile, &cp->tcps[tileno], &pi[poc], c, dest + len - c,
691                                              cstr_info, tileno);
692                         comp_len = comp_len + e;
693                         if (e == -999) {
694                             break;
695                         } else {
696                             c += e;
697                         }
698                     }
699                 }
700                 if (e == -999) {
701                     break;
702                 }
703                 if (cp->max_comp_size) {
704                     if (comp_len > cp->max_comp_size) {
705                         e = -999;
706                         break;
707                     }
708                 }
709             }
710             if (e == -999) {
711                 break;
712             }
713         }
714     } else { /* t2_mode == FINAL_PASS  */
715         pi_create_encode(pi, cp, tileno, pino, tpnum, tppos, t2_mode, cur_totnum_tp);
716         while (pi_next(&pi[pino])) {
717             if (pi[pino].layno < maxlayers) {
718                 e = t2_encode_packet(tile, &cp->tcps[tileno], &pi[pino], c, dest + len - c,
719                                      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) &&
734                                                   info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[cstr_info->packno -
735                                                                             1].end_pos + 1;
736                         }
737                         info_PK->end_pos = info_PK->start_pos + e - 1;
738                         info_PK->end_ph_pos += info_PK->start_pos -
739                                                1;  /* End of packet header which now only represents the distance
740                                                                                                                         // to start of packet is incremented by value of start of packet*/
741                     }
742
743                     cstr_info->packno++;
744                 }
745                 /* << INDEX */
746                 tile->packno++;
747             }
748         }
749     }
750
751     pi_destroy(pi, cp, tileno);
752
753     if (e == -999) {
754         return e;
755     }
756
757     return (c - dest);
758 }
759
760 int t2_decode_packets(opj_t2_t *t2, unsigned char *src, int len, int tileno,
761                       opj_tcd_tile_t *tile, opj_codestream_info_t *cstr_info)
762 {
763     unsigned char *c = src;
764     opj_pi_iterator_t *pi;
765     int pino, e = 0;
766     int n = 0, curtp = 0;
767     int tp_start_packno;
768
769     opj_image_t *image = t2->image;
770     opj_cp_t *cp = t2->cp;
771
772     /* create a packet iterator */
773     pi = pi_create_decode(image, cp, tileno);
774     if (!pi) {
775         /* TODO: throw an error */
776         return -999;
777     }
778
779     tp_start_packno = 0;
780
781     for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++) {
782         while (pi_next(&pi[pino])) {
783             if ((cp->layer == 0) || (cp->layer >= ((pi[pino].layno) + 1))) {
784                 opj_packet_info_t *pack_info;
785                 if (cstr_info) {
786                     pack_info = &cstr_info->tile[tileno].packet[cstr_info->packno];
787                 } else {
788                     pack_info = NULL;
789                 }
790                 e = t2_decode_packet(t2, c, src + len - c, tile, &cp->tcps[tileno], &pi[pino],
791                                      pack_info);
792             } else {
793                 e = 0;
794             }
795             if (e == -999) {
796                 pi_destroy(pi, cp, tileno);
797                 return -999;
798             }
799             /* progression in resolution */
800             image->comps[pi[pino].compno].resno_decoded =
801                 (e > 0) ?
802                 int_max(pi[pino].resno, image->comps[pi[pino].compno].resno_decoded)
803                 : image->comps[pi[pino].compno].resno_decoded;
804             n++;
805
806             /* INDEX >> */
807             if (cstr_info) {
808                 opj_tile_info_t *info_TL = &cstr_info->tile[tileno];
809                 opj_packet_info_t *info_PK = &info_TL->packet[cstr_info->packno];
810                 if (!cstr_info->packno) {
811                     info_PK->start_pos = info_TL->end_header + 1;
812                 } else if (info_TL->packet[cstr_info->packno - 1].end_pos >=
813                            (int)cstr_info->tile[tileno].tp[curtp].tp_end_pos) { /* New tile part*/
814                     info_TL->tp[curtp].tp_numpacks = cstr_info->packno -
815                                                      tp_start_packno; /* Number of packets in previous tile-part*/
816                     info_TL->tp[curtp].tp_start_pack = tp_start_packno;
817                     tp_start_packno = cstr_info->packno;
818                     curtp++;
819                     info_PK->start_pos = cstr_info->tile[tileno].tp[curtp].tp_end_header + 1;
820                 } else {
821                     info_PK->start_pos = (cp->tp_on &&
822                                           info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[cstr_info->packno -
823                                                                     1].end_pos + 1;
824                 }
825                 info_PK->end_pos = info_PK->start_pos + e - 1;
826                 info_PK->end_ph_pos += info_PK->start_pos -
827                                        1;  /* End of packet header which now only represents the distance
828                                                                                                                 // to start of packet is incremented by value of start of packet*/
829                 cstr_info->packno++;
830             }
831             /* << INDEX */
832
833             if (e == -999) {        /* ADD */
834                 break;
835             } else {
836                 c += e;
837             }
838         }
839     }
840     /* INDEX >> */
841     if (cstr_info) {
842         cstr_info->tile[tileno].tp[curtp].tp_numpacks = cstr_info->packno -
843                 tp_start_packno; /* Number of packets in last tile-part*/
844         cstr_info->tile[tileno].tp[curtp].tp_start_pack = tp_start_packno;
845     }
846     /* << INDEX */
847
848     /* don't forget to release pi */
849     pi_destroy(pi, cp, tileno);
850
851     if (e == -999) {
852         return e;
853     }
854
855     return (c - src);
856 }
857
858 /* ----------------------------------------------------------------------- */
859
860 opj_t2_t* t2_create(opj_common_ptr cinfo, opj_image_t *image, opj_cp_t *cp)
861 {
862     /* create the tcd structure */
863     opj_t2_t *t2 = (opj_t2_t*)opj_malloc(sizeof(opj_t2_t));
864     if (!t2) {
865         return NULL;
866     }
867     t2->cinfo = cinfo;
868     t2->image = image;
869     t2->cp = cp;
870
871     return t2;
872 }
873
874 void t2_destroy(opj_t2_t *t2)
875 {
876     if (t2) {
877         opj_free(t2);
878     }
879 }
880
881
882
883
884