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