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