485eb9e2f1db5b69d89a39e9bf85ecfb5daf590d
[openjpeg.git] / src / lib / openjp2 / tcd.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  * Copyright (c) 2006-2007, Parvatha Elangovan
15  * Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR
16  * Copyright (c) 2012, CS Systemes d'Information, France
17  * Copyright (c) 2017, IntoPIX SA <support@intopix.com>
18  * All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
30  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
33  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39  * POSSIBILITY OF SUCH DAMAGE.
40  */
41
42 #include "opj_includes.h"
43 #include "opj_common.h"
44
45 /* ----------------------------------------------------------------------- */
46
47 /* TODO MSD: */
48 #ifdef TODO_MSD
49 void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_image_t * img)
50 {
51     int tileno, compno, resno, bandno, precno;/*, cblkno;*/
52
53     fprintf(fd, "image {\n");
54     fprintf(fd, "  tw=%d, th=%d x0=%d x1=%d y0=%d y1=%d\n",
55             img->tw, img->th, tcd->image->x0, tcd->image->x1, tcd->image->y0,
56             tcd->image->y1);
57
58     for (tileno = 0; tileno < img->th * img->tw; tileno++) {
59         opj_tcd_tile_t *tile = &tcd->tcd_image->tiles[tileno];
60         fprintf(fd, "  tile {\n");
61         fprintf(fd, "    x0=%d, y0=%d, x1=%d, y1=%d, numcomps=%d\n",
62                 tile->x0, tile->y0, tile->x1, tile->y1, tile->numcomps);
63         for (compno = 0; compno < tile->numcomps; compno++) {
64             opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
65             fprintf(fd, "    tilec {\n");
66             fprintf(fd,
67                     "      x0=%d, y0=%d, x1=%d, y1=%d, numresolutions=%d\n",
68                     tilec->x0, tilec->y0, tilec->x1, tilec->y1, tilec->numresolutions);
69             for (resno = 0; resno < tilec->numresolutions; resno++) {
70                 opj_tcd_resolution_t *res = &tilec->resolutions[resno];
71                 fprintf(fd, "\n   res {\n");
72                 fprintf(fd,
73                         "          x0=%d, y0=%d, x1=%d, y1=%d, pw=%d, ph=%d, numbands=%d\n",
74                         res->x0, res->y0, res->x1, res->y1, res->pw, res->ph, res->numbands);
75                 for (bandno = 0; bandno < res->numbands; bandno++) {
76                     opj_tcd_band_t *band = &res->bands[bandno];
77                     fprintf(fd, "        band {\n");
78                     fprintf(fd,
79                             "          x0=%d, y0=%d, x1=%d, y1=%d, stepsize=%f, numbps=%d\n",
80                             band->x0, band->y0, band->x1, band->y1, band->stepsize, band->numbps);
81                     for (precno = 0; precno < res->pw * res->ph; precno++) {
82                         opj_tcd_precinct_t *prec = &band->precincts[precno];
83                         fprintf(fd, "          prec {\n");
84                         fprintf(fd,
85                                 "            x0=%d, y0=%d, x1=%d, y1=%d, cw=%d, ch=%d\n",
86                                 prec->x0, prec->y0, prec->x1, prec->y1, prec->cw, prec->ch);
87                         /*
88                         for (cblkno = 0; cblkno < prec->cw * prec->ch; cblkno++) {
89                                 opj_tcd_cblk_t *cblk = &prec->cblks[cblkno];
90                                 fprintf(fd, "            cblk {\n");
91                                 fprintf(fd,
92                                         "              x0=%d, y0=%d, x1=%d, y1=%d\n",
93                                         cblk->x0, cblk->y0, cblk->x1, cblk->y1);
94                                 fprintf(fd, "            }\n");
95                         }
96                         */
97                         fprintf(fd, "          }\n");
98                     }
99                     fprintf(fd, "        }\n");
100                 }
101                 fprintf(fd, "      }\n");
102             }
103             fprintf(fd, "    }\n");
104         }
105         fprintf(fd, "  }\n");
106     }
107     fprintf(fd, "}\n");
108 }
109 #endif
110
111 /**
112  * Initializes tile coding/decoding
113  */
114 static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
115         OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block,
116         opj_event_mgr_t* manager);
117
118 /**
119 * Allocates memory for a decoding code block.
120 */
121 static OPJ_BOOL opj_tcd_code_block_dec_allocate(opj_tcd_cblk_dec_t *
122         p_code_block);
123
124 /**
125  * Deallocates the decoding data of the given precinct.
126  */
127 static void opj_tcd_code_block_dec_deallocate(opj_tcd_precinct_t * p_precinct);
128
129 /**
130  * Allocates memory for an encoding code block (but not data).
131  */
132 static OPJ_BOOL opj_tcd_code_block_enc_allocate(opj_tcd_cblk_enc_t *
133         p_code_block);
134
135 /**
136  * Allocates data for an encoding code block
137  */
138 static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *
139         p_code_block);
140
141 /**
142  * Deallocates the encoding data of the given precinct.
143  */
144 static void opj_tcd_code_block_enc_deallocate(opj_tcd_precinct_t * p_precinct);
145
146
147 /**
148 Free the memory allocated for encoding
149 @param tcd TCD handle
150 */
151 static void opj_tcd_free_tile(opj_tcd_t *tcd);
152
153
154 static OPJ_BOOL opj_tcd_t2_decode(opj_tcd_t *p_tcd,
155                                   OPJ_BYTE * p_src_data,
156                                   OPJ_UINT32 * p_data_read,
157                                   OPJ_UINT32 p_max_src_size,
158                                   opj_codestream_index_t *p_cstr_index,
159                                   opj_event_mgr_t *p_manager);
160
161 static OPJ_BOOL opj_tcd_t1_decode(opj_tcd_t *p_tcd,
162                                   opj_event_mgr_t *p_manager);
163
164 static OPJ_BOOL opj_tcd_dwt_decode(opj_tcd_t *p_tcd);
165
166 static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd,
167                                    opj_event_mgr_t *p_manager);
168
169 static OPJ_BOOL opj_tcd_dc_level_shift_decode(opj_tcd_t *p_tcd);
170
171
172 static OPJ_BOOL opj_tcd_dc_level_shift_encode(opj_tcd_t *p_tcd);
173
174 static OPJ_BOOL opj_tcd_mct_encode(opj_tcd_t *p_tcd);
175
176 static OPJ_BOOL opj_tcd_dwt_encode(opj_tcd_t *p_tcd);
177
178 static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd);
179
180 static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd,
181                                   OPJ_BYTE * p_dest_data,
182                                   OPJ_UINT32 * p_data_written,
183                                   OPJ_UINT32 p_max_dest_size,
184                                   opj_codestream_info_t *p_cstr_info,
185                                   opj_event_mgr_t *p_manager);
186
187 static OPJ_BOOL opj_tcd_rate_allocate_encode(opj_tcd_t *p_tcd,
188         OPJ_BYTE * p_dest_data,
189         OPJ_UINT32 p_max_dest_size,
190         opj_codestream_info_t *p_cstr_info,
191         opj_event_mgr_t *p_manager);
192
193
194 static OPJ_BOOL opj_tcd_is_whole_tilecomp_decoding(opj_tcd_t *tcd,
195         OPJ_UINT32 compno);
196
197 /* ----------------------------------------------------------------------- */
198
199 /**
200 Create a new TCD handle
201 */
202 opj_tcd_t* opj_tcd_create(OPJ_BOOL p_is_decoder)
203 {
204     opj_tcd_t *l_tcd = 00;
205
206     /* create the tcd structure */
207     l_tcd = (opj_tcd_t*) opj_calloc(1, sizeof(opj_tcd_t));
208     if (!l_tcd) {
209         return 00;
210     }
211
212     l_tcd->m_is_decoder = p_is_decoder ? 1 : 0;
213
214     l_tcd->tcd_image = (opj_tcd_image_t*)opj_calloc(1, sizeof(opj_tcd_image_t));
215     if (!l_tcd->tcd_image) {
216         opj_free(l_tcd);
217         return 00;
218     }
219
220     return l_tcd;
221 }
222
223
224 /* ----------------------------------------------------------------------- */
225
226 void opj_tcd_rateallocate_fixed(opj_tcd_t *tcd)
227 {
228     OPJ_UINT32 layno;
229
230     for (layno = 0; layno < tcd->tcp->numlayers; layno++) {
231         opj_tcd_makelayer_fixed(tcd, layno, 1);
232     }
233 }
234
235
236 void opj_tcd_makelayer(opj_tcd_t *tcd,
237                        OPJ_UINT32 layno,
238                        OPJ_FLOAT64 thresh,
239                        OPJ_UINT32 final)
240 {
241     OPJ_UINT32 compno, resno, bandno, precno, cblkno;
242     OPJ_UINT32 passno;
243
244     opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles;
245
246     tcd_tile->distolayer[layno] = 0;        /* fixed_quality */
247
248     for (compno = 0; compno < tcd_tile->numcomps; compno++) {
249         opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];
250
251         for (resno = 0; resno < tilec->numresolutions; resno++) {
252             opj_tcd_resolution_t *res = &tilec->resolutions[resno];
253
254             for (bandno = 0; bandno < res->numbands; bandno++) {
255                 opj_tcd_band_t *band = &res->bands[bandno];
256
257                 /* Skip empty bands */
258                 if (opj_tcd_is_band_empty(band)) {
259                     continue;
260                 }
261
262                 for (precno = 0; precno < res->pw * res->ph; precno++) {
263                     opj_tcd_precinct_t *prc = &band->precincts[precno];
264
265                     for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
266                         opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno];
267                         opj_tcd_layer_t *layer = &cblk->layers[layno];
268                         OPJ_UINT32 n;
269
270                         if (layno == 0) {
271                             cblk->numpassesinlayers = 0;
272                         }
273
274                         n = cblk->numpassesinlayers;
275
276                         for (passno = cblk->numpassesinlayers; passno < cblk->totalpasses; passno++) {
277                             OPJ_UINT32 dr;
278                             OPJ_FLOAT64 dd;
279                             opj_tcd_pass_t *pass = &cblk->passes[passno];
280
281                             if (n == 0) {
282                                 dr = pass->rate;
283                                 dd = pass->distortiondec;
284                             } else {
285                                 dr = pass->rate - cblk->passes[n - 1].rate;
286                                 dd = pass->distortiondec - cblk->passes[n - 1].distortiondec;
287                             }
288
289                             if (!dr) {
290                                 if (dd != 0) {
291                                     n = passno + 1;
292                                 }
293                                 continue;
294                             }
295                             if (thresh - (dd / dr) <
296                                     DBL_EPSILON) { /* do not rely on float equality, check with DBL_EPSILON margin */
297                                 n = passno + 1;
298                             }
299                         }
300
301                         layer->numpasses = n - cblk->numpassesinlayers;
302
303                         if (!layer->numpasses) {
304                             layer->disto = 0;
305                             continue;
306                         }
307
308                         if (cblk->numpassesinlayers == 0) {
309                             layer->len = cblk->passes[n - 1].rate;
310                             layer->data = cblk->data;
311                             layer->disto = cblk->passes[n - 1].distortiondec;
312                         } else {
313                             layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers -
314                                          1].rate;
315                             layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate;
316                             layer->disto = cblk->passes[n - 1].distortiondec -
317                                            cblk->passes[cblk->numpassesinlayers - 1].distortiondec;
318                         }
319
320                         tcd_tile->distolayer[layno] += layer->disto;    /* fixed_quality */
321
322                         if (final) {
323                             cblk->numpassesinlayers = n;
324                         }
325                     }
326                 }
327             }
328         }
329     }
330 }
331
332 void opj_tcd_makelayer_fixed(opj_tcd_t *tcd, OPJ_UINT32 layno,
333                              OPJ_UINT32 final)
334 {
335     OPJ_UINT32 compno, resno, bandno, precno, cblkno;
336     OPJ_INT32 value;                        /*, matrice[tcd_tcp->numlayers][tcd_tile->comps[0].numresolutions][3]; */
337     OPJ_INT32 matrice[10][10][3];
338     OPJ_UINT32 i, j, k;
339
340     opj_cp_t *cp = tcd->cp;
341     opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles;
342     opj_tcp_t *tcd_tcp = tcd->tcp;
343
344     for (compno = 0; compno < tcd_tile->numcomps; compno++) {
345         opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];
346
347         for (i = 0; i < tcd_tcp->numlayers; i++) {
348             for (j = 0; j < tilec->numresolutions; j++) {
349                 for (k = 0; k < 3; k++) {
350                     matrice[i][j][k] =
351                         (OPJ_INT32)((OPJ_FLOAT32)cp->m_specific_param.m_enc.m_matrice[i *
352                                       tilec->numresolutions * 3 + j * 3 + k]
353                                     * (OPJ_FLOAT32)(tcd->image->comps[compno].prec / 16.0));
354                 }
355             }
356         }
357
358         for (resno = 0; resno < tilec->numresolutions; resno++) {
359             opj_tcd_resolution_t *res = &tilec->resolutions[resno];
360
361             for (bandno = 0; bandno < res->numbands; bandno++) {
362                 opj_tcd_band_t *band = &res->bands[bandno];
363
364                 /* Skip empty bands */
365                 if (opj_tcd_is_band_empty(band)) {
366                     continue;
367                 }
368
369                 for (precno = 0; precno < res->pw * res->ph; precno++) {
370                     opj_tcd_precinct_t *prc = &band->precincts[precno];
371
372                     for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
373                         opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno];
374                         opj_tcd_layer_t *layer = &cblk->layers[layno];
375                         OPJ_UINT32 n;
376                         OPJ_INT32 imsb = (OPJ_INT32)(tcd->image->comps[compno].prec -
377                                                      cblk->numbps); /* number of bit-plan equal to zero */
378
379                         /* Correction of the matrix of coefficient to include the IMSB information */
380                         if (layno == 0) {
381                             value = matrice[layno][resno][bandno];
382                             if (imsb >= value) {
383                                 value = 0;
384                             } else {
385                                 value -= imsb;
386                             }
387                         } else {
388                             value = matrice[layno][resno][bandno] - matrice[layno - 1][resno][bandno];
389                             if (imsb >= matrice[layno - 1][resno][bandno]) {
390                                 value -= (imsb - matrice[layno - 1][resno][bandno]);
391                                 if (value < 0) {
392                                     value = 0;
393                                 }
394                             }
395                         }
396
397                         if (layno == 0) {
398                             cblk->numpassesinlayers = 0;
399                         }
400
401                         n = cblk->numpassesinlayers;
402                         if (cblk->numpassesinlayers == 0) {
403                             if (value != 0) {
404                                 n = 3 * (OPJ_UINT32)value - 2 + cblk->numpassesinlayers;
405                             } else {
406                                 n = cblk->numpassesinlayers;
407                             }
408                         } else {
409                             n = 3 * (OPJ_UINT32)value + cblk->numpassesinlayers;
410                         }
411
412                         layer->numpasses = n - cblk->numpassesinlayers;
413
414                         if (!layer->numpasses) {
415                             continue;
416                         }
417
418                         if (cblk->numpassesinlayers == 0) {
419                             layer->len = cblk->passes[n - 1].rate;
420                             layer->data = cblk->data;
421                         } else {
422                             layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers -
423                                          1].rate;
424                             layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate;
425                         }
426
427                         if (final) {
428                             cblk->numpassesinlayers = n;
429                         }
430                     }
431                 }
432             }
433         }
434     }
435 }
436
437 OPJ_BOOL opj_tcd_rateallocate(opj_tcd_t *tcd,
438                               OPJ_BYTE *dest,
439                               OPJ_UINT32 * p_data_written,
440                               OPJ_UINT32 len,
441                               opj_codestream_info_t *cstr_info,
442                               opj_event_mgr_t *p_manager)
443 {
444     OPJ_UINT32 compno, resno, bandno, precno, cblkno, layno;
445     OPJ_UINT32 passno;
446     OPJ_FLOAT64 min, max;
447     OPJ_FLOAT64 cumdisto[100];      /* fixed_quality */
448     const OPJ_FLOAT64 K = 1;                /* 1.1; fixed_quality */
449     OPJ_FLOAT64 maxSE = 0;
450
451     opj_cp_t *cp = tcd->cp;
452     opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles;
453     opj_tcp_t *tcd_tcp = tcd->tcp;
454
455     min = DBL_MAX;
456     max = 0;
457
458     tcd_tile->numpix = 0;           /* fixed_quality */
459
460     for (compno = 0; compno < tcd_tile->numcomps; compno++) {
461         opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];
462         tilec->numpix = 0;
463
464         for (resno = 0; resno < tilec->numresolutions; resno++) {
465             opj_tcd_resolution_t *res = &tilec->resolutions[resno];
466
467             for (bandno = 0; bandno < res->numbands; bandno++) {
468                 opj_tcd_band_t *band = &res->bands[bandno];
469
470                 /* Skip empty bands */
471                 if (opj_tcd_is_band_empty(band)) {
472                     continue;
473                 }
474
475                 for (precno = 0; precno < res->pw * res->ph; precno++) {
476                     opj_tcd_precinct_t *prc = &band->precincts[precno];
477
478                     for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
479                         opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno];
480
481                         for (passno = 0; passno < cblk->totalpasses; passno++) {
482                             opj_tcd_pass_t *pass = &cblk->passes[passno];
483                             OPJ_INT32 dr;
484                             OPJ_FLOAT64 dd, rdslope;
485
486                             if (passno == 0) {
487                                 dr = (OPJ_INT32)pass->rate;
488                                 dd = pass->distortiondec;
489                             } else {
490                                 dr = (OPJ_INT32)(pass->rate - cblk->passes[passno - 1].rate);
491                                 dd = pass->distortiondec - cblk->passes[passno - 1].distortiondec;
492                             }
493
494                             if (dr == 0) {
495                                 continue;
496                             }
497
498                             rdslope = dd / dr;
499                             if (rdslope < min) {
500                                 min = rdslope;
501                             }
502
503                             if (rdslope > max) {
504                                 max = rdslope;
505                             }
506                         } /* passno */
507
508                         /* fixed_quality */
509                         tcd_tile->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0));
510                         tilec->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0));
511                     } /* cbklno */
512                 } /* precno */
513             } /* bandno */
514         } /* resno */
515
516         maxSE += (((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) - 1.0)
517                   * ((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) - 1.0))
518                  * ((OPJ_FLOAT64)(tilec->numpix));
519     } /* compno */
520
521     /* index file */
522     if (cstr_info) {
523         opj_tile_info_t *tile_info = &cstr_info->tile[tcd->tcd_tileno];
524         tile_info->numpix = tcd_tile->numpix;
525         tile_info->distotile = tcd_tile->distotile;
526         tile_info->thresh = (OPJ_FLOAT64 *) opj_malloc(tcd_tcp->numlayers * sizeof(
527                                 OPJ_FLOAT64));
528         if (!tile_info->thresh) {
529             /* FIXME event manager error callback */
530             return OPJ_FALSE;
531         }
532     }
533
534     for (layno = 0; layno < tcd_tcp->numlayers; layno++) {
535         OPJ_FLOAT64 lo = min;
536         OPJ_FLOAT64 hi = max;
537         OPJ_UINT32 maxlen = tcd_tcp->rates[layno] > 0.0f ? opj_uint_min(((
538                                 OPJ_UINT32) ceil(tcd_tcp->rates[layno])), len) : len;
539         OPJ_FLOAT64 goodthresh = 0;
540         OPJ_FLOAT64 stable_thresh = 0;
541         OPJ_UINT32 i;
542         OPJ_FLOAT64 distotarget;                /* fixed_quality */
543
544         /* fixed_quality */
545         distotarget = tcd_tile->distotile - ((K * maxSE) / pow((OPJ_FLOAT32)10,
546                                              tcd_tcp->distoratio[layno] / 10));
547
548         /* Don't try to find an optimal threshold but rather take everything not included yet, if
549           -r xx,yy,zz,0   (disto_alloc == 1 and rates == 0)
550           -q xx,yy,zz,0   (fixed_quality == 1 and distoratio == 0)
551           ==> possible to have some lossy layers and the last layer for sure lossless */
552         if (((cp->m_specific_param.m_enc.m_disto_alloc == 1) &&
553                 (tcd_tcp->rates[layno] > 0.0f)) ||
554                 ((cp->m_specific_param.m_enc.m_fixed_quality == 1) &&
555                  (tcd_tcp->distoratio[layno] > 0.0))) {
556             opj_t2_t*t2 = opj_t2_create(tcd->image, cp);
557             OPJ_FLOAT64 thresh = 0;
558
559             if (t2 == 00) {
560                 return OPJ_FALSE;
561             }
562
563             for (i = 0; i < 128; ++i) {
564                 OPJ_FLOAT64 distoachieved = 0;  /* fixed_quality */
565
566                 thresh = (lo + hi) / 2;
567
568                 opj_tcd_makelayer(tcd, layno, thresh, 0);
569
570                 if (cp->m_specific_param.m_enc.m_fixed_quality) {       /* fixed_quality */
571                     if (OPJ_IS_CINEMA(cp->rsiz)) {
572                         if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,
573                                                     p_data_written, maxlen, cstr_info, tcd->cur_tp_num, tcd->tp_pos, tcd->cur_pino,
574                                                     THRESH_CALC, p_manager)) {
575
576                             lo = thresh;
577                             continue;
578                         } else {
579                             distoachieved = layno == 0 ?
580                                             tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno];
581
582                             if (distoachieved < distotarget) {
583                                 hi = thresh;
584                                 stable_thresh = thresh;
585                                 continue;
586                             } else {
587                                 lo = thresh;
588                             }
589                         }
590                     } else {
591                         distoachieved = (layno == 0) ?
592                                         tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]);
593
594                         if (distoachieved < distotarget) {
595                             hi = thresh;
596                             stable_thresh = thresh;
597                             continue;
598                         }
599                         lo = thresh;
600                     }
601                 } else {
602                     if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,
603                                                 p_data_written, maxlen, cstr_info, tcd->cur_tp_num, tcd->tp_pos, tcd->cur_pino,
604                                                 THRESH_CALC, p_manager)) {
605                         /* TODO: what to do with l ??? seek / tell ??? */
606                         /* opj_event_msg(tcd->cinfo, EVT_INFO, "rate alloc: len=%d, max=%d\n", l, maxlen); */
607                         lo = thresh;
608                         continue;
609                     }
610
611                     hi = thresh;
612                     stable_thresh = thresh;
613                 }
614             }
615
616             goodthresh = stable_thresh == 0 ? thresh : stable_thresh;
617
618             opj_t2_destroy(t2);
619         } else {
620             goodthresh = min;
621         }
622
623         if (cstr_info) { /* Threshold for Marcela Index */
624             cstr_info->tile[tcd->tcd_tileno].thresh[layno] = goodthresh;
625         }
626
627         opj_tcd_makelayer(tcd, layno, goodthresh, 1);
628
629         /* fixed_quality */
630         cumdisto[layno] = (layno == 0) ? tcd_tile->distolayer[0] :
631                           (cumdisto[layno - 1] + tcd_tile->distolayer[layno]);
632     }
633
634     return OPJ_TRUE;
635 }
636
637 OPJ_BOOL opj_tcd_init(opj_tcd_t *p_tcd,
638                       opj_image_t * p_image,
639                       opj_cp_t * p_cp,
640                       opj_thread_pool_t* p_tp)
641 {
642     p_tcd->image = p_image;
643     p_tcd->cp = p_cp;
644
645     p_tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_calloc(1,
646                               sizeof(opj_tcd_tile_t));
647     if (! p_tcd->tcd_image->tiles) {
648         return OPJ_FALSE;
649     }
650
651     p_tcd->tcd_image->tiles->comps = (opj_tcd_tilecomp_t *) opj_calloc(
652                                          p_image->numcomps, sizeof(opj_tcd_tilecomp_t));
653     if (! p_tcd->tcd_image->tiles->comps) {
654         return OPJ_FALSE;
655     }
656
657     p_tcd->tcd_image->tiles->numcomps = p_image->numcomps;
658     p_tcd->tp_pos = p_cp->m_specific_param.m_enc.m_tp_pos;
659     p_tcd->thread_pool = p_tp;
660
661     return OPJ_TRUE;
662 }
663
664 /**
665 Destroy a previously created TCD handle
666 */
667 void opj_tcd_destroy(opj_tcd_t *tcd)
668 {
669     if (tcd) {
670         opj_tcd_free_tile(tcd);
671
672         if (tcd->tcd_image) {
673             opj_free(tcd->tcd_image);
674             tcd->tcd_image = 00;
675         }
676         opj_free(tcd);
677     }
678 }
679
680 OPJ_BOOL opj_alloc_tile_component_data(opj_tcd_tilecomp_t *l_tilec)
681 {
682     if ((l_tilec->data == 00) ||
683             ((l_tilec->data_size_needed > l_tilec->data_size) &&
684              (l_tilec->ownsData == OPJ_FALSE))) {
685         l_tilec->data = (OPJ_INT32 *) opj_image_data_alloc(l_tilec->data_size_needed);
686         if (!l_tilec->data && l_tilec->data_size_needed != 0) {
687             return OPJ_FALSE;
688         }
689         /*fprintf(stderr, "tAllocate data of tilec (int): %d x OPJ_UINT32n",l_data_size);*/
690         l_tilec->data_size = l_tilec->data_size_needed;
691         l_tilec->ownsData = OPJ_TRUE;
692     } else if (l_tilec->data_size_needed > l_tilec->data_size) {
693         /* We don't need to keep old data */
694         opj_image_data_free(l_tilec->data);
695         l_tilec->data = (OPJ_INT32 *) opj_image_data_alloc(l_tilec->data_size_needed);
696         if (! l_tilec->data) {
697             l_tilec->data_size = 0;
698             l_tilec->data_size_needed = 0;
699             l_tilec->ownsData = OPJ_FALSE;
700             return OPJ_FALSE;
701         }
702         /*fprintf(stderr, "tReallocate data of tilec (int): from %d to %d x OPJ_UINT32n", l_tilec->data_size, l_data_size);*/
703         l_tilec->data_size = l_tilec->data_size_needed;
704         l_tilec->ownsData = OPJ_TRUE;
705     }
706     return OPJ_TRUE;
707 }
708
709 /* ----------------------------------------------------------------------- */
710
711 static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
712         OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block,
713         opj_event_mgr_t* manager)
714 {
715     OPJ_UINT32(*l_gain_ptr)(OPJ_UINT32) = 00;
716     OPJ_UINT32 compno, resno, bandno, precno, cblkno;
717     opj_tcp_t * l_tcp = 00;
718     opj_cp_t * l_cp = 00;
719     opj_tcd_tile_t * l_tile = 00;
720     opj_tccp_t *l_tccp = 00;
721     opj_tcd_tilecomp_t *l_tilec = 00;
722     opj_image_comp_t * l_image_comp = 00;
723     opj_tcd_resolution_t *l_res = 00;
724     opj_tcd_band_t *l_band = 00;
725     opj_stepsize_t * l_step_size = 00;
726     opj_tcd_precinct_t *l_current_precinct = 00;
727     opj_image_t *l_image = 00;
728     OPJ_UINT32 p, q;
729     OPJ_UINT32 l_level_no;
730     OPJ_UINT32 l_pdx, l_pdy;
731     OPJ_UINT32 l_gain;
732     OPJ_INT32 l_x0b, l_y0b;
733     OPJ_UINT32 l_tx0, l_ty0;
734     /* extent of precincts , top left, bottom right**/
735     OPJ_INT32 l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end, l_br_prc_y_end;
736     /* number of precinct for a resolution */
737     OPJ_UINT32 l_nb_precincts;
738     /* room needed to store l_nb_precinct precinct for a resolution */
739     OPJ_UINT32 l_nb_precinct_size;
740     /* number of code blocks for a precinct*/
741     OPJ_UINT32 l_nb_code_blocks;
742     /* room needed to store l_nb_code_blocks code blocks for a precinct*/
743     OPJ_UINT32 l_nb_code_blocks_size;
744     /* size of data for a tile */
745     OPJ_UINT32 l_data_size;
746
747     l_cp = p_tcd->cp;
748     l_tcp = &(l_cp->tcps[p_tile_no]);
749     l_tile = p_tcd->tcd_image->tiles;
750     l_tccp = l_tcp->tccps;
751     l_tilec = l_tile->comps;
752     l_image = p_tcd->image;
753     l_image_comp = p_tcd->image->comps;
754
755     p = p_tile_no % l_cp->tw;       /* tile coordinates */
756     q = p_tile_no / l_cp->tw;
757     /*fprintf(stderr, "Tile coordinate = %d,%d\n", p, q);*/
758
759     /* 4 borders of the tile rescale on the image if necessary */
760     l_tx0 = l_cp->tx0 + p *
761             l_cp->tdx; /* can't be greater than l_image->x1 so won't overflow */
762     l_tile->x0 = (OPJ_INT32)opj_uint_max(l_tx0, l_image->x0);
763     l_tile->x1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, l_cp->tdx),
764                                          l_image->x1);
765     /* all those OPJ_UINT32 are casted to OPJ_INT32, let's do some sanity check */
766     if ((l_tile->x0 < 0) || (l_tile->x1 <= l_tile->x0)) {
767         opj_event_msg(manager, EVT_ERROR, "Tile X coordinates are not supported\n");
768         return OPJ_FALSE;
769     }
770     l_ty0 = l_cp->ty0 + q *
771             l_cp->tdy; /* can't be greater than l_image->y1 so won't overflow */
772     l_tile->y0 = (OPJ_INT32)opj_uint_max(l_ty0, l_image->y0);
773     l_tile->y1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, l_cp->tdy),
774                                          l_image->y1);
775     /* all those OPJ_UINT32 are casted to OPJ_INT32, let's do some sanity check */
776     if ((l_tile->y0 < 0) || (l_tile->y1 <= l_tile->y0)) {
777         opj_event_msg(manager, EVT_ERROR, "Tile Y coordinates are not supported\n");
778         return OPJ_FALSE;
779     }
780
781
782     /* testcase 1888.pdf.asan.35.988 */
783     if (l_tccp->numresolutions == 0) {
784         opj_event_msg(manager, EVT_ERROR, "tiles require at least one resolution\n");
785         return OPJ_FALSE;
786     }
787     /*fprintf(stderr, "Tile border = %d,%d,%d,%d\n", l_tile->x0, l_tile->y0,l_tile->x1,l_tile->y1);*/
788
789     /*tile->numcomps = image->numcomps; */
790     for (compno = 0; compno < l_tile->numcomps; ++compno) {
791         /*fprintf(stderr, "compno = %d/%d\n", compno, l_tile->numcomps);*/
792         l_image_comp->resno_decoded = 0;
793         /* border of each l_tile component (global) */
794         l_tilec->x0 = opj_int_ceildiv(l_tile->x0, (OPJ_INT32)l_image_comp->dx);
795         l_tilec->y0 = opj_int_ceildiv(l_tile->y0, (OPJ_INT32)l_image_comp->dy);
796         l_tilec->x1 = opj_int_ceildiv(l_tile->x1, (OPJ_INT32)l_image_comp->dx);
797         l_tilec->y1 = opj_int_ceildiv(l_tile->y1, (OPJ_INT32)l_image_comp->dy);
798         l_tilec->compno = compno;
799         /*fprintf(stderr, "\tTile compo border = %d,%d,%d,%d\n", l_tilec->x0, l_tilec->y0,l_tilec->x1,l_tilec->y1);*/
800
801         l_tilec->numresolutions = l_tccp->numresolutions;
802         if (l_tccp->numresolutions < l_cp->m_specific_param.m_dec.m_reduce) {
803             l_tilec->minimum_num_resolutions = 1;
804         } else {
805             l_tilec->minimum_num_resolutions = l_tccp->numresolutions -
806                                                l_cp->m_specific_param.m_dec.m_reduce;
807         }
808
809         if (isEncoder) {
810             size_t l_tile_data_size;
811
812             /* compute l_data_size with overflow check */
813             size_t w = (size_t)(l_tilec->x1 - l_tilec->x0);
814             size_t h = (size_t)(l_tilec->y1 - l_tilec->y0);
815
816             /* issue 733, l_data_size == 0U, probably something wrong should be checked before getting here */
817             if (h > 0 && w > SIZE_MAX / h) {
818                 opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
819                 return OPJ_FALSE;
820             }
821             l_tile_data_size = w * h;
822
823             if (SIZE_MAX / sizeof(OPJ_UINT32) < l_tile_data_size) {
824                 opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
825                 return OPJ_FALSE;
826             }
827             l_tile_data_size = l_tile_data_size * sizeof(OPJ_UINT32);
828
829             l_tilec->data_size_needed = l_tile_data_size;
830         }
831
832         l_data_size = l_tilec->numresolutions * (OPJ_UINT32)sizeof(
833                           opj_tcd_resolution_t);
834
835         opj_aligned_free(l_tilec->data_win);
836         l_tilec->data_win = NULL;
837         l_tilec->win_x0 = 0;
838         l_tilec->win_y0 = 0;
839         l_tilec->win_x1 = 0;
840         l_tilec->win_y1 = 0;
841
842         if (l_tilec->resolutions == 00) {
843             l_tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(l_data_size);
844             if (! l_tilec->resolutions) {
845                 return OPJ_FALSE;
846             }
847             /*fprintf(stderr, "\tAllocate resolutions of tilec (opj_tcd_resolution_t): %d\n",l_data_size);*/
848             l_tilec->resolutions_size = l_data_size;
849             memset(l_tilec->resolutions, 0, l_data_size);
850         } else if (l_data_size > l_tilec->resolutions_size) {
851             opj_tcd_resolution_t* new_resolutions = (opj_tcd_resolution_t *) opj_realloc(
852                     l_tilec->resolutions, l_data_size);
853             if (! new_resolutions) {
854                 opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile resolutions\n");
855                 opj_free(l_tilec->resolutions);
856                 l_tilec->resolutions = NULL;
857                 l_tilec->resolutions_size = 0;
858                 return OPJ_FALSE;
859             }
860             l_tilec->resolutions = new_resolutions;
861             /*fprintf(stderr, "\tReallocate data of tilec (int): from %d to %d x OPJ_UINT32\n", l_tilec->resolutions_size, l_data_size);*/
862             memset(((OPJ_BYTE*) l_tilec->resolutions) + l_tilec->resolutions_size, 0,
863                    l_data_size - l_tilec->resolutions_size);
864             l_tilec->resolutions_size = l_data_size;
865         }
866
867         l_level_no = l_tilec->numresolutions;
868         l_res = l_tilec->resolutions;
869         l_step_size = l_tccp->stepsizes;
870         if (l_tccp->qmfbid == 0) {
871             l_gain_ptr = &opj_dwt_getgain_real;
872         } else {
873             l_gain_ptr  = &opj_dwt_getgain;
874         }
875         /*fprintf(stderr, "\tlevel_no=%d\n",l_level_no);*/
876
877         for (resno = 0; resno < l_tilec->numresolutions; ++resno) {
878             /*fprintf(stderr, "\t\tresno = %d/%d\n", resno, l_tilec->numresolutions);*/
879             OPJ_INT32 tlcbgxstart, tlcbgystart /*, brcbgxend, brcbgyend*/;
880             OPJ_UINT32 cbgwidthexpn, cbgheightexpn;
881             OPJ_UINT32 cblkwidthexpn, cblkheightexpn;
882
883             --l_level_no;
884
885             /* border for each resolution level (global) */
886             l_res->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
887             l_res->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
888             l_res->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
889             l_res->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
890
891             /*fprintf(stderr, "\t\t\tres_x0= %d, res_y0 =%d, res_x1=%d, res_y1=%d\n", l_res->x0, l_res->y0, l_res->x1, l_res->y1);*/
892             /* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */
893             l_pdx = l_tccp->prcw[resno];
894             l_pdy = l_tccp->prch[resno];
895             /*fprintf(stderr, "\t\t\tpdx=%d, pdy=%d\n", l_pdx, l_pdy);*/
896             /* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000)  */
897             l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx;
898             l_tl_prc_y_start = opj_int_floordivpow2(l_res->y0, (OPJ_INT32)l_pdy) << l_pdy;
899             l_br_prc_x_end = opj_int_ceildivpow2(l_res->x1, (OPJ_INT32)l_pdx) << l_pdx;
900             l_br_prc_y_end = opj_int_ceildivpow2(l_res->y1, (OPJ_INT32)l_pdy) << l_pdy;
901             /*fprintf(stderr, "\t\t\tprc_x_start=%d, prc_y_start=%d, br_prc_x_end=%d, br_prc_y_end=%d \n", l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end ,l_br_prc_y_end );*/
902
903             l_res->pw = (l_res->x0 == l_res->x1) ? 0U : (OPJ_UINT32)((
904                             l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx);
905             l_res->ph = (l_res->y0 == l_res->y1) ? 0U : (OPJ_UINT32)((
906                             l_br_prc_y_end - l_tl_prc_y_start) >> l_pdy);
907             /*fprintf(stderr, "\t\t\tres_pw=%d, res_ph=%d\n", l_res->pw, l_res->ph );*/
908
909             if ((l_res->pw != 0U) && ((((OPJ_UINT32) - 1) / l_res->pw) < l_res->ph)) {
910                 opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
911                 return OPJ_FALSE;
912             }
913             l_nb_precincts = l_res->pw * l_res->ph;
914
915             if ((((OPJ_UINT32) - 1) / (OPJ_UINT32)sizeof(opj_tcd_precinct_t)) <
916                     l_nb_precincts) {
917                 opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
918                 return OPJ_FALSE;
919             }
920             l_nb_precinct_size = l_nb_precincts * (OPJ_UINT32)sizeof(opj_tcd_precinct_t);
921
922             if (resno == 0) {
923                 tlcbgxstart = l_tl_prc_x_start;
924                 tlcbgystart = l_tl_prc_y_start;
925                 /*brcbgxend = l_br_prc_x_end;*/
926                 /* brcbgyend = l_br_prc_y_end;*/
927                 cbgwidthexpn = l_pdx;
928                 cbgheightexpn = l_pdy;
929                 l_res->numbands = 1;
930             } else {
931                 tlcbgxstart = opj_int_ceildivpow2(l_tl_prc_x_start, 1);
932                 tlcbgystart = opj_int_ceildivpow2(l_tl_prc_y_start, 1);
933                 /*brcbgxend = opj_int_ceildivpow2(l_br_prc_x_end, 1);*/
934                 /*brcbgyend = opj_int_ceildivpow2(l_br_prc_y_end, 1);*/
935                 cbgwidthexpn = l_pdx - 1;
936                 cbgheightexpn = l_pdy - 1;
937                 l_res->numbands = 3;
938             }
939
940             cblkwidthexpn = opj_uint_min(l_tccp->cblkw, cbgwidthexpn);
941             cblkheightexpn = opj_uint_min(l_tccp->cblkh, cbgheightexpn);
942             l_band = l_res->bands;
943
944             for (bandno = 0; bandno < l_res->numbands; ++bandno, ++l_band, ++l_step_size) {
945                 OPJ_INT32 numbps;
946                 /*fprintf(stderr, "\t\t\tband_no=%d/%d\n", bandno, l_res->numbands );*/
947
948                 if (resno == 0) {
949                     l_band->bandno = 0 ;
950                     l_band->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
951                     l_band->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
952                     l_band->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
953                     l_band->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
954                 } else {
955                     l_band->bandno = bandno + 1;
956                     /* x0b = 1 if bandno = 1 or 3 */
957                     l_x0b = l_band->bandno & 1;
958                     /* y0b = 1 if bandno = 2 or 3 */
959                     l_y0b = (OPJ_INT32)((l_band->bandno) >> 1);
960                     /* l_band border (global) */
961                     l_band->x0 = opj_int64_ceildivpow2(l_tilec->x0 - ((OPJ_INT64)l_x0b <<
962                                                        l_level_no), (OPJ_INT32)(l_level_no + 1));
963                     l_band->y0 = opj_int64_ceildivpow2(l_tilec->y0 - ((OPJ_INT64)l_y0b <<
964                                                        l_level_no), (OPJ_INT32)(l_level_no + 1));
965                     l_band->x1 = opj_int64_ceildivpow2(l_tilec->x1 - ((OPJ_INT64)l_x0b <<
966                                                        l_level_no), (OPJ_INT32)(l_level_no + 1));
967                     l_band->y1 = opj_int64_ceildivpow2(l_tilec->y1 - ((OPJ_INT64)l_y0b <<
968                                                        l_level_no), (OPJ_INT32)(l_level_no + 1));
969                 }
970
971                 if (isEncoder) {
972                     /* Skip empty bands */
973                     if (opj_tcd_is_band_empty(l_band)) {
974                         /* Do not zero l_band->precints to avoid leaks */
975                         /* but make sure we don't use it later, since */
976                         /* it will point to precincts of previous bands... */
977                         continue;
978                     }
979                 }
980
981                 /** avoid an if with storing function pointer */
982                 l_gain = (*l_gain_ptr)(l_band->bandno);
983                 numbps = (OPJ_INT32)(l_image_comp->prec + l_gain);
984                 l_band->stepsize = (OPJ_FLOAT32)(((1.0 + l_step_size->mant / 2048.0) * pow(2.0,
985                                                   (OPJ_INT32)(numbps - l_step_size->expn)))) * fraction;
986                 /* Mb value of Equation E-2 in "E.1 Inverse quantization
987                  * procedure" of the standard */
988                 l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits -
989                                  1;
990
991                 if (!l_band->precincts && (l_nb_precincts > 0U)) {
992                     l_band->precincts = (opj_tcd_precinct_t *) opj_malloc(/*3 * */
993                                             l_nb_precinct_size);
994                     if (! l_band->precincts) {
995                         opj_event_msg(manager, EVT_ERROR,
996                                       "Not enough memory to handle band precints\n");
997                         return OPJ_FALSE;
998                     }
999                     /*fprintf(stderr, "\t\t\t\tAllocate precincts of a band (opj_tcd_precinct_t): %d\n",l_nb_precinct_size);     */
1000                     memset(l_band->precincts, 0, l_nb_precinct_size);
1001                     l_band->precincts_data_size = l_nb_precinct_size;
1002                 } else if (l_band->precincts_data_size < l_nb_precinct_size) {
1003
1004                     opj_tcd_precinct_t * new_precincts = (opj_tcd_precinct_t *) opj_realloc(
1005                             l_band->precincts,/*3 * */ l_nb_precinct_size);
1006                     if (! new_precincts) {
1007                         opj_event_msg(manager, EVT_ERROR,
1008                                       "Not enough memory to handle band precints\n");
1009                         opj_free(l_band->precincts);
1010                         l_band->precincts = NULL;
1011                         l_band->precincts_data_size = 0;
1012                         return OPJ_FALSE;
1013                     }
1014                     l_band->precincts = new_precincts;
1015                     /*fprintf(stderr, "\t\t\t\tReallocate precincts of a band (opj_tcd_precinct_t): from %d to %d\n",l_band->precincts_data_size, l_nb_precinct_size);*/
1016                     memset(((OPJ_BYTE *) l_band->precincts) + l_band->precincts_data_size, 0,
1017                            l_nb_precinct_size - l_band->precincts_data_size);
1018                     l_band->precincts_data_size = l_nb_precinct_size;
1019                 }
1020
1021                 l_current_precinct = l_band->precincts;
1022                 for (precno = 0; precno < l_nb_precincts; ++precno) {
1023                     OPJ_INT32 tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend;
1024                     OPJ_INT32 cbgxstart = tlcbgxstart + (OPJ_INT32)(precno % l_res->pw) *
1025                                           (1 << cbgwidthexpn);
1026                     OPJ_INT32 cbgystart = tlcbgystart + (OPJ_INT32)(precno / l_res->pw) *
1027                                           (1 << cbgheightexpn);
1028                     OPJ_INT32 cbgxend = cbgxstart + (1 << cbgwidthexpn);
1029                     OPJ_INT32 cbgyend = cbgystart + (1 << cbgheightexpn);
1030                     /*fprintf(stderr, "\t precno=%d; bandno=%d, resno=%d; compno=%d\n", precno, bandno , resno, compno);*/
1031                     /*fprintf(stderr, "\t tlcbgxstart(=%d) + (precno(=%d) percent res->pw(=%d)) * (1 << cbgwidthexpn(=%d)) \n",tlcbgxstart,precno,l_res->pw,cbgwidthexpn);*/
1032
1033                     /* precinct size (global) */
1034                     /*fprintf(stderr, "\t cbgxstart=%d, l_band->x0 = %d \n",cbgxstart, l_band->x0);*/
1035
1036                     l_current_precinct->x0 = opj_int_max(cbgxstart, l_band->x0);
1037                     l_current_precinct->y0 = opj_int_max(cbgystart, l_band->y0);
1038                     l_current_precinct->x1 = opj_int_min(cbgxend, l_band->x1);
1039                     l_current_precinct->y1 = opj_int_min(cbgyend, l_band->y1);
1040                     /*fprintf(stderr, "\t prc_x0=%d; prc_y0=%d, prc_x1=%d; prc_y1=%d\n",l_current_precinct->x0, l_current_precinct->y0 ,l_current_precinct->x1, l_current_precinct->y1);*/
1041
1042                     tlcblkxstart = opj_int_floordivpow2(l_current_precinct->x0,
1043                                                         (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
1044                     /*fprintf(stderr, "\t tlcblkxstart =%d\n",tlcblkxstart );*/
1045                     tlcblkystart = opj_int_floordivpow2(l_current_precinct->y0,
1046                                                         (OPJ_INT32)cblkheightexpn) << cblkheightexpn;
1047                     /*fprintf(stderr, "\t tlcblkystart =%d\n",tlcblkystart );*/
1048                     brcblkxend = opj_int_ceildivpow2(l_current_precinct->x1,
1049                                                      (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
1050                     /*fprintf(stderr, "\t brcblkxend =%d\n",brcblkxend );*/
1051                     brcblkyend = opj_int_ceildivpow2(l_current_precinct->y1,
1052                                                      (OPJ_INT32)cblkheightexpn) << cblkheightexpn;
1053                     /*fprintf(stderr, "\t brcblkyend =%d\n",brcblkyend );*/
1054                     l_current_precinct->cw = (OPJ_UINT32)((brcblkxend - tlcblkxstart) >>
1055                                                           cblkwidthexpn);
1056                     l_current_precinct->ch = (OPJ_UINT32)((brcblkyend - tlcblkystart) >>
1057                                                           cblkheightexpn);
1058
1059                     l_nb_code_blocks = l_current_precinct->cw * l_current_precinct->ch;
1060                     /*fprintf(stderr, "\t\t\t\t precinct_cw = %d x recinct_ch = %d\n",l_current_precinct->cw, l_current_precinct->ch);      */
1061                     l_nb_code_blocks_size = l_nb_code_blocks * (OPJ_UINT32)sizeof_block;
1062
1063                     if (!l_current_precinct->cblks.blocks && (l_nb_code_blocks > 0U)) {
1064                         l_current_precinct->cblks.blocks = opj_malloc(l_nb_code_blocks_size);
1065                         if (! l_current_precinct->cblks.blocks) {
1066                             return OPJ_FALSE;
1067                         }
1068                         /*fprintf(stderr, "\t\t\t\tAllocate cblks of a precinct (opj_tcd_cblk_dec_t): %d\n",l_nb_code_blocks_size);*/
1069
1070                         memset(l_current_precinct->cblks.blocks, 0, l_nb_code_blocks_size);
1071
1072                         l_current_precinct->block_size = l_nb_code_blocks_size;
1073                     } else if (l_nb_code_blocks_size > l_current_precinct->block_size) {
1074                         void *new_blocks = opj_realloc(l_current_precinct->cblks.blocks,
1075                                                        l_nb_code_blocks_size);
1076                         if (! new_blocks) {
1077                             opj_free(l_current_precinct->cblks.blocks);
1078                             l_current_precinct->cblks.blocks = NULL;
1079                             l_current_precinct->block_size = 0;
1080                             opj_event_msg(manager, EVT_ERROR,
1081                                           "Not enough memory for current precinct codeblock element\n");
1082                             return OPJ_FALSE;
1083                         }
1084                         l_current_precinct->cblks.blocks = new_blocks;
1085                         /*fprintf(stderr, "\t\t\t\tReallocate cblks of a precinct (opj_tcd_cblk_dec_t): from %d to %d\n",l_current_precinct->block_size, l_nb_code_blocks_size);     */
1086
1087                         memset(((OPJ_BYTE *) l_current_precinct->cblks.blocks) +
1088                                l_current_precinct->block_size
1089                                , 0
1090                                , l_nb_code_blocks_size - l_current_precinct->block_size);
1091
1092                         l_current_precinct->block_size = l_nb_code_blocks_size;
1093                     }
1094
1095                     if (! l_current_precinct->incltree) {
1096                         l_current_precinct->incltree = opj_tgt_create(l_current_precinct->cw,
1097                                                        l_current_precinct->ch, manager);
1098                     } else {
1099                         l_current_precinct->incltree = opj_tgt_init(l_current_precinct->incltree,
1100                                                        l_current_precinct->cw, l_current_precinct->ch, manager);
1101                     }
1102
1103                     if (! l_current_precinct->imsbtree) {
1104                         l_current_precinct->imsbtree = opj_tgt_create(l_current_precinct->cw,
1105                                                        l_current_precinct->ch, manager);
1106                     } else {
1107                         l_current_precinct->imsbtree = opj_tgt_init(l_current_precinct->imsbtree,
1108                                                        l_current_precinct->cw, l_current_precinct->ch, manager);
1109                     }
1110
1111                     for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
1112                         OPJ_INT32 cblkxstart = tlcblkxstart + (OPJ_INT32)(cblkno %
1113                                                l_current_precinct->cw) * (1 << cblkwidthexpn);
1114                         OPJ_INT32 cblkystart = tlcblkystart + (OPJ_INT32)(cblkno /
1115                                                l_current_precinct->cw) * (1 << cblkheightexpn);
1116                         OPJ_INT32 cblkxend = cblkxstart + (1 << cblkwidthexpn);
1117                         OPJ_INT32 cblkyend = cblkystart + (1 << cblkheightexpn);
1118
1119                         if (isEncoder) {
1120                             opj_tcd_cblk_enc_t* l_code_block = l_current_precinct->cblks.enc + cblkno;
1121
1122                             if (! opj_tcd_code_block_enc_allocate(l_code_block)) {
1123                                 return OPJ_FALSE;
1124                             }
1125                             /* code-block size (global) */
1126                             l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
1127                             l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
1128                             l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
1129                             l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
1130
1131                             if (! opj_tcd_code_block_enc_allocate_data(l_code_block)) {
1132                                 return OPJ_FALSE;
1133                             }
1134                         } else {
1135                             opj_tcd_cblk_dec_t* l_code_block = l_current_precinct->cblks.dec + cblkno;
1136
1137                             if (! opj_tcd_code_block_dec_allocate(l_code_block)) {
1138                                 return OPJ_FALSE;
1139                             }
1140                             /* code-block size (global) */
1141                             l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
1142                             l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
1143                             l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
1144                             l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
1145                         }
1146                     }
1147                     ++l_current_precinct;
1148                 } /* precno */
1149             } /* bandno */
1150             ++l_res;
1151         } /* resno */
1152         ++l_tccp;
1153         ++l_tilec;
1154         ++l_image_comp;
1155     } /* compno */
1156     return OPJ_TRUE;
1157 }
1158
1159 OPJ_BOOL opj_tcd_init_encode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
1160                                   opj_event_mgr_t* p_manager)
1161 {
1162     return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_TRUE, 1.0F,
1163                              sizeof(opj_tcd_cblk_enc_t), p_manager);
1164 }
1165
1166 OPJ_BOOL opj_tcd_init_decode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
1167                                   opj_event_mgr_t* p_manager)
1168 {
1169     return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_FALSE, 0.5F,
1170                              sizeof(opj_tcd_cblk_dec_t), p_manager);
1171 }
1172
1173 /**
1174  * Allocates memory for an encoding code block (but not data memory).
1175  */
1176 static OPJ_BOOL opj_tcd_code_block_enc_allocate(opj_tcd_cblk_enc_t *
1177         p_code_block)
1178 {
1179     if (! p_code_block->layers) {
1180         /* no memset since data */
1181         p_code_block->layers = (opj_tcd_layer_t*) opj_calloc(100,
1182                                sizeof(opj_tcd_layer_t));
1183         if (! p_code_block->layers) {
1184             return OPJ_FALSE;
1185         }
1186     }
1187     if (! p_code_block->passes) {
1188         p_code_block->passes = (opj_tcd_pass_t*) opj_calloc(100,
1189                                sizeof(opj_tcd_pass_t));
1190         if (! p_code_block->passes) {
1191             return OPJ_FALSE;
1192         }
1193     }
1194     return OPJ_TRUE;
1195 }
1196
1197 /**
1198  * Allocates data memory for an encoding code block.
1199  */
1200 static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *
1201         p_code_block)
1202 {
1203     OPJ_UINT32 l_data_size;
1204
1205     /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */
1206     /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */
1207     /* TODO: is there a theoretical upper-bound for the compressed code */
1208     /* block size ? */
1209     l_data_size = 2 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *
1210                                    (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));
1211
1212     if (l_data_size > p_code_block->data_size) {
1213         if (p_code_block->data) {
1214             /* We refer to data - 1 since below we incremented it */
1215             opj_free(p_code_block->data - 1);
1216         }
1217         p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);
1218         if (! p_code_block->data) {
1219             p_code_block->data_size = 0U;
1220             return OPJ_FALSE;
1221         }
1222         p_code_block->data_size = l_data_size;
1223
1224         /* We reserve the initial byte as a fake byte to a non-FF value */
1225         /* and increment the data pointer, so that opj_mqc_init_enc() */
1226         /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */
1227         /* it. */
1228         p_code_block->data[0] = 0;
1229         p_code_block->data += 1; /*why +1 ?*/
1230     }
1231     return OPJ_TRUE;
1232 }
1233
1234
1235 void opj_tcd_reinit_segment(opj_tcd_seg_t* seg)
1236 {
1237     memset(seg, 0, sizeof(opj_tcd_seg_t));
1238 }
1239
1240 /**
1241  * Allocates memory for a decoding code block.
1242  */
1243 static OPJ_BOOL opj_tcd_code_block_dec_allocate(opj_tcd_cblk_dec_t *
1244         p_code_block)
1245 {
1246     if (! p_code_block->segs) {
1247
1248         p_code_block->segs = (opj_tcd_seg_t *) opj_calloc(OPJ_J2K_DEFAULT_NB_SEGS,
1249                              sizeof(opj_tcd_seg_t));
1250         if (! p_code_block->segs) {
1251             return OPJ_FALSE;
1252         }
1253         /*fprintf(stderr, "Allocate %d elements of code_block->data\n", OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t));*/
1254
1255         p_code_block->m_current_max_segs = OPJ_J2K_DEFAULT_NB_SEGS;
1256         /*fprintf(stderr, "m_current_max_segs of code_block->data = %d\n", p_code_block->m_current_max_segs);*/
1257     } else {
1258         /* sanitize */
1259         opj_tcd_seg_t * l_segs = p_code_block->segs;
1260         OPJ_UINT32 l_current_max_segs = p_code_block->m_current_max_segs;
1261         opj_tcd_seg_data_chunk_t* l_chunks = p_code_block->chunks;
1262         OPJ_UINT32 l_numchunksalloc = p_code_block->numchunksalloc;
1263         OPJ_UINT32 i;
1264
1265         opj_free(p_code_block->decoded_data);
1266         p_code_block->decoded_data = 00;
1267
1268         memset(p_code_block, 0, sizeof(opj_tcd_cblk_dec_t));
1269         p_code_block->segs = l_segs;
1270         p_code_block->m_current_max_segs = l_current_max_segs;
1271         for (i = 0; i < l_current_max_segs; ++i) {
1272             opj_tcd_reinit_segment(&l_segs[i]);
1273         }
1274         p_code_block->chunks = l_chunks;
1275         p_code_block->numchunksalloc = l_numchunksalloc;
1276     }
1277
1278     return OPJ_TRUE;
1279 }
1280
1281 OPJ_UINT32 opj_tcd_get_decoded_tile_size(opj_tcd_t *p_tcd,
1282         OPJ_BOOL take_into_account_partial_decoding)
1283 {
1284     OPJ_UINT32 i;
1285     OPJ_UINT32 l_data_size = 0;
1286     opj_image_comp_t * l_img_comp = 00;
1287     opj_tcd_tilecomp_t * l_tile_comp = 00;
1288     opj_tcd_resolution_t * l_res = 00;
1289     OPJ_UINT32 l_size_comp, l_remaining;
1290     OPJ_UINT32 l_temp;
1291
1292     l_tile_comp = p_tcd->tcd_image->tiles->comps;
1293     l_img_comp = p_tcd->image->comps;
1294
1295     for (i = 0; i < p_tcd->image->numcomps; ++i) {
1296         OPJ_UINT32 w, h;
1297         l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
1298         l_remaining = l_img_comp->prec & 7;  /* (%8) */
1299
1300         if (l_remaining) {
1301             ++l_size_comp;
1302         }
1303
1304         if (l_size_comp == 3) {
1305             l_size_comp = 4;
1306         }
1307
1308         l_res = l_tile_comp->resolutions + l_tile_comp->minimum_num_resolutions - 1;
1309         if (take_into_account_partial_decoding && !p_tcd->whole_tile_decoding) {
1310             w = l_res->win_x1 - l_res->win_x0;
1311             h = l_res->win_y1 - l_res->win_y0;
1312         } else {
1313             w = (OPJ_UINT32)(l_res->x1 - l_res->x0);
1314             h = (OPJ_UINT32)(l_res->y1 - l_res->y0);
1315         }
1316         if (h > 0 && UINT_MAX / w < h) {
1317             return UINT_MAX;
1318         }
1319         l_temp = w * h;
1320         if (l_size_comp && UINT_MAX / l_size_comp < l_temp) {
1321             return UINT_MAX;
1322         }
1323         l_temp *= l_size_comp;
1324
1325         if (l_temp > UINT_MAX - l_data_size) {
1326             return UINT_MAX;
1327         }
1328         l_data_size += l_temp;
1329         ++l_img_comp;
1330         ++l_tile_comp;
1331     }
1332
1333     return l_data_size;
1334 }
1335
1336 OPJ_BOOL opj_tcd_encode_tile(opj_tcd_t *p_tcd,
1337                              OPJ_UINT32 p_tile_no,
1338                              OPJ_BYTE *p_dest,
1339                              OPJ_UINT32 * p_data_written,
1340                              OPJ_UINT32 p_max_length,
1341                              opj_codestream_info_t *p_cstr_info,
1342                              opj_event_mgr_t *p_manager)
1343 {
1344
1345     if (p_tcd->cur_tp_num == 0) {
1346
1347         p_tcd->tcd_tileno = p_tile_no;
1348         p_tcd->tcp = &p_tcd->cp->tcps[p_tile_no];
1349
1350         /* INDEX >> "Precinct_nb_X et Precinct_nb_Y" */
1351         if (p_cstr_info)  {
1352             OPJ_UINT32 l_num_packs = 0;
1353             OPJ_UINT32 i;
1354             opj_tcd_tilecomp_t *l_tilec_idx =
1355                 &p_tcd->tcd_image->tiles->comps[0];        /* based on component 0 */
1356             opj_tccp_t *l_tccp = p_tcd->tcp->tccps; /* based on component 0 */
1357
1358             for (i = 0; i < l_tilec_idx->numresolutions; i++) {
1359                 opj_tcd_resolution_t *l_res_idx = &l_tilec_idx->resolutions[i];
1360
1361                 p_cstr_info->tile[p_tile_no].pw[i] = (int)l_res_idx->pw;
1362                 p_cstr_info->tile[p_tile_no].ph[i] = (int)l_res_idx->ph;
1363
1364                 l_num_packs += l_res_idx->pw * l_res_idx->ph;
1365                 p_cstr_info->tile[p_tile_no].pdx[i] = (int)l_tccp->prcw[i];
1366                 p_cstr_info->tile[p_tile_no].pdy[i] = (int)l_tccp->prch[i];
1367             }
1368             p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t*) opj_calloc((
1369                     size_t)p_cstr_info->numcomps * (size_t)p_cstr_info->numlayers * l_num_packs,
1370                                                   sizeof(opj_packet_info_t));
1371             if (!p_cstr_info->tile[p_tile_no].packet) {
1372                 /* FIXME event manager error callback */
1373                 return OPJ_FALSE;
1374             }
1375         }
1376         /* << INDEX */
1377
1378         /* FIXME _ProfStart(PGROUP_DC_SHIFT); */
1379         /*---------------TILE-------------------*/
1380         if (! opj_tcd_dc_level_shift_encode(p_tcd)) {
1381             return OPJ_FALSE;
1382         }
1383         /* FIXME _ProfStop(PGROUP_DC_SHIFT); */
1384
1385         /* FIXME _ProfStart(PGROUP_MCT); */
1386         if (! opj_tcd_mct_encode(p_tcd)) {
1387             return OPJ_FALSE;
1388         }
1389         /* FIXME _ProfStop(PGROUP_MCT); */
1390
1391         /* FIXME _ProfStart(PGROUP_DWT); */
1392         if (! opj_tcd_dwt_encode(p_tcd)) {
1393             return OPJ_FALSE;
1394         }
1395         /* FIXME  _ProfStop(PGROUP_DWT); */
1396
1397         /* FIXME  _ProfStart(PGROUP_T1); */
1398         if (! opj_tcd_t1_encode(p_tcd)) {
1399             return OPJ_FALSE;
1400         }
1401         /* FIXME _ProfStop(PGROUP_T1); */
1402
1403         /* FIXME _ProfStart(PGROUP_RATE); */
1404         if (! opj_tcd_rate_allocate_encode(p_tcd, p_dest, p_max_length,
1405                                            p_cstr_info, p_manager)) {
1406             return OPJ_FALSE;
1407         }
1408         /* FIXME _ProfStop(PGROUP_RATE); */
1409
1410     }
1411     /*--------------TIER2------------------*/
1412
1413     /* INDEX */
1414     if (p_cstr_info) {
1415         p_cstr_info->index_write = 1;
1416     }
1417     /* FIXME _ProfStart(PGROUP_T2); */
1418
1419     if (! opj_tcd_t2_encode(p_tcd, p_dest, p_data_written, p_max_length,
1420                             p_cstr_info, p_manager)) {
1421         return OPJ_FALSE;
1422     }
1423     /* FIXME _ProfStop(PGROUP_T2); */
1424
1425     /*---------------CLEAN-------------------*/
1426
1427     return OPJ_TRUE;
1428 }
1429
1430 OPJ_BOOL opj_tcd_decode_tile(opj_tcd_t *p_tcd,
1431                              OPJ_UINT32 win_x0,
1432                              OPJ_UINT32 win_y0,
1433                              OPJ_UINT32 win_x1,
1434                              OPJ_UINT32 win_y1,
1435                              OPJ_BYTE *p_src,
1436                              OPJ_UINT32 p_max_length,
1437                              OPJ_UINT32 p_tile_no,
1438                              opj_codestream_index_t *p_cstr_index,
1439                              opj_event_mgr_t *p_manager
1440                             )
1441 {
1442     OPJ_UINT32 l_data_read;
1443     OPJ_UINT32 compno;
1444
1445     p_tcd->tcd_tileno = p_tile_no;
1446     p_tcd->tcp = &(p_tcd->cp->tcps[p_tile_no]);
1447     p_tcd->win_x0 = win_x0;
1448     p_tcd->win_y0 = win_y0;
1449     p_tcd->win_x1 = win_x1;
1450     p_tcd->win_y1 = win_y1;
1451     p_tcd->whole_tile_decoding = OPJ_TRUE;
1452
1453     for (compno = 0; compno < p_tcd->image->numcomps; compno++) {
1454         if (!opj_tcd_is_whole_tilecomp_decoding(p_tcd, compno)) {
1455             p_tcd->whole_tile_decoding = OPJ_FALSE;
1456             break;
1457         }
1458     }
1459
1460     if (p_tcd->whole_tile_decoding) {
1461         for (compno = 0; compno < p_tcd->image->numcomps; compno++) {
1462             opj_tcd_tilecomp_t* tilec = &(p_tcd->tcd_image->tiles->comps[compno]);
1463             opj_tcd_resolution_t *l_res = &
1464                                           (tilec->resolutions[tilec->minimum_num_resolutions - 1]);
1465             size_t l_data_size;
1466
1467             /* compute l_data_size with overflow check */
1468             size_t res_w = (size_t)(l_res->x1 - l_res->x0);
1469             size_t res_h = (size_t)(l_res->y1 - l_res->y0);
1470
1471             /* issue 733, l_data_size == 0U, probably something wrong should be checked before getting here */
1472             if (res_h > 0 && res_w > SIZE_MAX / res_h) {
1473                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for tile data\n");
1474                 return OPJ_FALSE;
1475             }
1476             l_data_size = res_w * res_h;
1477
1478             if (SIZE_MAX / sizeof(OPJ_UINT32) < l_data_size) {
1479                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for tile data\n");
1480                 return OPJ_FALSE;
1481             }
1482             l_data_size *= sizeof(OPJ_UINT32);
1483
1484             tilec->data_size_needed = l_data_size;
1485
1486             if (!opj_alloc_tile_component_data(tilec)) {
1487                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for tile data\n");
1488                 return OPJ_FALSE;
1489             }
1490         }
1491     } else {
1492         /* Compute restricted tile-component and tile-resolution coordinates */
1493         /* of the window of interest, but defer the memory allocation until */
1494         /* we know the resno_decoded */
1495         for (compno = 0; compno < p_tcd->image->numcomps; compno++) {
1496             OPJ_UINT32 resno;
1497             opj_tcd_tilecomp_t* tilec = &(p_tcd->tcd_image->tiles->comps[compno]);
1498             opj_image_comp_t* image_comp = &(p_tcd->image->comps[compno]);
1499             /* Compute the intersection of the area of interest, expressed in tile coordinates */
1500             /* with the tile coordinates */
1501             tilec->win_x0 = opj_uint_max(
1502                                 (OPJ_UINT32)tilec->x0,
1503                                 opj_uint_ceildiv(p_tcd->win_x0, image_comp->dx));
1504             tilec->win_y0 = opj_uint_max(
1505                                 (OPJ_UINT32)tilec->y0,
1506                                 opj_uint_ceildiv(p_tcd->win_y0, image_comp->dy));
1507             tilec->win_x1 = opj_uint_min(
1508                                 (OPJ_UINT32)tilec->x1,
1509                                 opj_uint_ceildiv(p_tcd->win_x1, image_comp->dx));
1510             tilec->win_y1 = opj_uint_min(
1511                                 (OPJ_UINT32)tilec->y1,
1512                                 opj_uint_ceildiv(p_tcd->win_y1, image_comp->dy));
1513
1514             for (resno = 0; resno < tilec->numresolutions; ++resno) {
1515                 opj_tcd_resolution_t *res = tilec->resolutions + resno;
1516                 res->win_x0 = opj_uint_ceildivpow2(tilec->win_x0,
1517                                                    tilec->numresolutions - 1 - resno);
1518                 res->win_y0 = opj_uint_ceildivpow2(tilec->win_y0,
1519                                                    tilec->numresolutions - 1 - resno);
1520                 res->win_x1 = opj_uint_ceildivpow2(tilec->win_x1,
1521                                                    tilec->numresolutions - 1 - resno);
1522                 res->win_y1 = opj_uint_ceildivpow2(tilec->win_y1,
1523                                                    tilec->numresolutions - 1 - resno);
1524             }
1525         }
1526     }
1527
1528 #ifdef TODO_MSD /* FIXME */
1529     /* INDEX >>  */
1530     if (p_cstr_info) {
1531         OPJ_UINT32 resno, compno, numprec = 0;
1532         for (compno = 0; compno < (OPJ_UINT32) p_cstr_info->numcomps; compno++) {
1533             opj_tcp_t *tcp = &p_tcd->cp->tcps[0];
1534             opj_tccp_t *tccp = &tcp->tccps[compno];
1535             opj_tcd_tilecomp_t *tilec_idx = &p_tcd->tcd_image->tiles->comps[compno];
1536             for (resno = 0; resno < tilec_idx->numresolutions; resno++) {
1537                 opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[resno];
1538                 p_cstr_info->tile[p_tile_no].pw[resno] = res_idx->pw;
1539                 p_cstr_info->tile[p_tile_no].ph[resno] = res_idx->ph;
1540                 numprec += res_idx->pw * res_idx->ph;
1541                 p_cstr_info->tile[p_tile_no].pdx[resno] = tccp->prcw[resno];
1542                 p_cstr_info->tile[p_tile_no].pdy[resno] = tccp->prch[resno];
1543             }
1544         }
1545         p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t *) opj_malloc(
1546                 p_cstr_info->numlayers * numprec * sizeof(opj_packet_info_t));
1547         p_cstr_info->packno = 0;
1548     }
1549     /* << INDEX */
1550 #endif
1551
1552     /*--------------TIER2------------------*/
1553     /* FIXME _ProfStart(PGROUP_T2); */
1554     l_data_read = 0;
1555     if (! opj_tcd_t2_decode(p_tcd, p_src, &l_data_read, p_max_length, p_cstr_index,
1556                             p_manager)) {
1557         return OPJ_FALSE;
1558     }
1559     /* FIXME _ProfStop(PGROUP_T2); */
1560
1561     /*------------------TIER1-----------------*/
1562
1563     /* FIXME _ProfStart(PGROUP_T1); */
1564     if (! opj_tcd_t1_decode(p_tcd, p_manager)) {
1565         return OPJ_FALSE;
1566     }
1567     /* FIXME _ProfStop(PGROUP_T1); */
1568
1569
1570     /* For subtile decoding, now we know the resno_decoded, we can allocate */
1571     /* the tile data buffer */
1572     if (!p_tcd->whole_tile_decoding) {
1573         for (compno = 0; compno < p_tcd->image->numcomps; compno++) {
1574             opj_tcd_tilecomp_t* tilec = &(p_tcd->tcd_image->tiles->comps[compno]);
1575             opj_image_comp_t* image_comp = &(p_tcd->image->comps[compno]);
1576             opj_tcd_resolution_t *res = tilec->resolutions + image_comp->resno_decoded;
1577             size_t w = res->win_x1 - res->win_x0;
1578             size_t h = res->win_y1 - res->win_y0;
1579             size_t l_data_size;
1580
1581             opj_aligned_free(tilec->data_win);
1582             tilec->data_win = NULL;
1583
1584             if (w > 0 && h > 0) {
1585                 if (w > SIZE_MAX / h) {
1586                     opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for tile data\n");
1587                     return OPJ_FALSE;
1588                 }
1589                 l_data_size = w * h;
1590                 if (l_data_size > SIZE_MAX / sizeof(OPJ_INT32)) {
1591                     opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for tile data\n");
1592                     return OPJ_FALSE;
1593                 }
1594                 l_data_size *= sizeof(OPJ_INT32);
1595
1596                 tilec->data_win = opj_aligned_malloc(l_data_size);
1597                 if (tilec->data_win == NULL) {
1598                     opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for tile data\n");
1599                     return OPJ_FALSE;
1600                 }
1601             }
1602         }
1603     }
1604
1605     /*----------------DWT---------------------*/
1606
1607     /* FIXME _ProfStart(PGROUP_DWT); */
1608     if
1609     (! opj_tcd_dwt_decode(p_tcd)) {
1610         return OPJ_FALSE;
1611     }
1612     /* FIXME _ProfStop(PGROUP_DWT); */
1613
1614     /*----------------MCT-------------------*/
1615     /* FIXME _ProfStart(PGROUP_MCT); */
1616     if
1617     (! opj_tcd_mct_decode(p_tcd, p_manager)) {
1618         return OPJ_FALSE;
1619     }
1620     /* FIXME _ProfStop(PGROUP_MCT); */
1621
1622     /* FIXME _ProfStart(PGROUP_DC_SHIFT); */
1623     if
1624     (! opj_tcd_dc_level_shift_decode(p_tcd)) {
1625         return OPJ_FALSE;
1626     }
1627     /* FIXME _ProfStop(PGROUP_DC_SHIFT); */
1628
1629
1630     /*---------------TILE-------------------*/
1631     return OPJ_TRUE;
1632 }
1633
1634 OPJ_BOOL opj_tcd_update_tile_data(opj_tcd_t *p_tcd,
1635                                   OPJ_BYTE * p_dest,
1636                                   OPJ_UINT32 p_dest_length
1637                                  )
1638 {
1639     OPJ_UINT32 i, j, k, l_data_size = 0;
1640     opj_image_comp_t * l_img_comp = 00;
1641     opj_tcd_tilecomp_t * l_tilec = 00;
1642     opj_tcd_resolution_t * l_res;
1643     OPJ_UINT32 l_size_comp, l_remaining;
1644     OPJ_UINT32 l_stride, l_width, l_height;
1645
1646     l_data_size = opj_tcd_get_decoded_tile_size(p_tcd, OPJ_TRUE);
1647     if (l_data_size == UINT_MAX || l_data_size > p_dest_length) {
1648         return OPJ_FALSE;
1649     }
1650
1651     l_tilec = p_tcd->tcd_image->tiles->comps;
1652     l_img_comp = p_tcd->image->comps;
1653
1654     for (i = 0; i < p_tcd->image->numcomps; ++i) {
1655         const OPJ_INT32* l_src_data;
1656         l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
1657         l_remaining = l_img_comp->prec & 7;  /* (%8) */
1658         l_res = l_tilec->resolutions + l_img_comp->resno_decoded;
1659         if (p_tcd->whole_tile_decoding) {
1660             l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0);
1661             l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0);
1662             l_stride = (OPJ_UINT32)(l_tilec->resolutions[l_tilec->minimum_num_resolutions -
1663                                                                      1].x1 -
1664                                     l_tilec->resolutions[l_tilec->minimum_num_resolutions - 1].x0) - l_width;
1665             l_src_data = l_tilec->data;
1666         } else {
1667             l_width = l_res->win_x1 - l_res->win_x0;
1668             l_height = l_res->win_y1 - l_res->win_y0;
1669             l_stride = 0;
1670             l_src_data = l_tilec->data_win;
1671         }
1672
1673         if (l_remaining) {
1674             ++l_size_comp;
1675         }
1676
1677         if (l_size_comp == 3) {
1678             l_size_comp = 4;
1679         }
1680
1681         switch (l_size_comp) {
1682         case 1: {
1683             OPJ_CHAR * l_dest_ptr = (OPJ_CHAR *) p_dest;
1684             const OPJ_INT32 * l_src_ptr = l_src_data;
1685
1686             if (l_img_comp->sgnd) {
1687                 for (j = 0; j < l_height; ++j) {
1688                     for (k = 0; k < l_width; ++k) {
1689                         *(l_dest_ptr++) = (OPJ_CHAR)(*(l_src_ptr++));
1690                     }
1691                     l_src_ptr += l_stride;
1692                 }
1693             } else {
1694                 for (j = 0; j < l_height; ++j) {
1695                     for (k = 0; k < l_width; ++k) {
1696                         *(l_dest_ptr++) = (OPJ_CHAR)((*(l_src_ptr++)) & 0xff);
1697                     }
1698                     l_src_ptr += l_stride;
1699                 }
1700             }
1701
1702             p_dest = (OPJ_BYTE *)l_dest_ptr;
1703         }
1704         break;
1705         case 2: {
1706             const OPJ_INT32 * l_src_ptr = l_src_data;
1707             OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_dest;
1708
1709             if (l_img_comp->sgnd) {
1710                 for (j = 0; j < l_height; ++j) {
1711                     for (k = 0; k < l_width; ++k) {
1712                         OPJ_INT16 val = (OPJ_INT16)(*(l_src_ptr++));
1713                         memcpy(l_dest_ptr, &val, sizeof(val));
1714                         l_dest_ptr ++;
1715                     }
1716                     l_src_ptr += l_stride;
1717                 }
1718             } else {
1719                 for (j = 0; j < l_height; ++j) {
1720                     for (k = 0; k < l_width; ++k) {
1721                         OPJ_INT16 val = (OPJ_INT16)((*(l_src_ptr++)) & 0xffff);
1722                         memcpy(l_dest_ptr, &val, sizeof(val));
1723                         l_dest_ptr ++;
1724                     }
1725                     l_src_ptr += l_stride;
1726                 }
1727             }
1728
1729             p_dest = (OPJ_BYTE*) l_dest_ptr;
1730         }
1731         break;
1732         case 4: {
1733             OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_dest;
1734             const OPJ_INT32 * l_src_ptr = l_src_data;
1735
1736             for (j = 0; j < l_height; ++j) {
1737                 memcpy(l_dest_ptr, l_src_ptr, l_width * sizeof(OPJ_INT32));
1738                 l_dest_ptr += l_width;
1739                 l_src_ptr += l_width + l_stride;
1740             }
1741
1742             p_dest = (OPJ_BYTE*) l_dest_ptr;
1743         }
1744         break;
1745         }
1746
1747         ++l_img_comp;
1748         ++l_tilec;
1749     }
1750
1751     return OPJ_TRUE;
1752 }
1753
1754
1755
1756
1757 static void opj_tcd_free_tile(opj_tcd_t *p_tcd)
1758 {
1759     OPJ_UINT32 compno, resno, bandno, precno;
1760     opj_tcd_tile_t *l_tile = 00;
1761     opj_tcd_tilecomp_t *l_tile_comp = 00;
1762     opj_tcd_resolution_t *l_res = 00;
1763     opj_tcd_band_t *l_band = 00;
1764     opj_tcd_precinct_t *l_precinct = 00;
1765     OPJ_UINT32 l_nb_resolutions, l_nb_precincts;
1766     void (* l_tcd_code_block_deallocate)(opj_tcd_precinct_t *) = 00;
1767
1768     if (! p_tcd) {
1769         return;
1770     }
1771
1772     if (! p_tcd->tcd_image) {
1773         return;
1774     }
1775
1776     if (p_tcd->m_is_decoder) {
1777         l_tcd_code_block_deallocate = opj_tcd_code_block_dec_deallocate;
1778     } else {
1779         l_tcd_code_block_deallocate = opj_tcd_code_block_enc_deallocate;
1780     }
1781
1782     l_tile = p_tcd->tcd_image->tiles;
1783     if (! l_tile) {
1784         return;
1785     }
1786
1787     l_tile_comp = l_tile->comps;
1788
1789     for (compno = 0; compno < l_tile->numcomps; ++compno) {
1790         l_res = l_tile_comp->resolutions;
1791         if (l_res) {
1792
1793             l_nb_resolutions = l_tile_comp->resolutions_size / sizeof(opj_tcd_resolution_t);
1794             for (resno = 0; resno < l_nb_resolutions; ++resno) {
1795                 l_band = l_res->bands;
1796                 for (bandno = 0; bandno < 3; ++bandno) {
1797                     l_precinct = l_band->precincts;
1798                     if (l_precinct) {
1799
1800                         l_nb_precincts = l_band->precincts_data_size / sizeof(opj_tcd_precinct_t);
1801                         for (precno = 0; precno < l_nb_precincts; ++precno) {
1802                             opj_tgt_destroy(l_precinct->incltree);
1803                             l_precinct->incltree = 00;
1804                             opj_tgt_destroy(l_precinct->imsbtree);
1805                             l_precinct->imsbtree = 00;
1806                             (*l_tcd_code_block_deallocate)(l_precinct);
1807                             ++l_precinct;
1808                         }
1809
1810                         opj_free(l_band->precincts);
1811                         l_band->precincts = 00;
1812                     }
1813                     ++l_band;
1814                 } /* for (resno */
1815                 ++l_res;
1816             }
1817
1818             opj_free(l_tile_comp->resolutions);
1819             l_tile_comp->resolutions = 00;
1820         }
1821
1822         if (l_tile_comp->ownsData && l_tile_comp->data) {
1823             opj_image_data_free(l_tile_comp->data);
1824             l_tile_comp->data = 00;
1825             l_tile_comp->ownsData = 0;
1826             l_tile_comp->data_size = 0;
1827             l_tile_comp->data_size_needed = 0;
1828         }
1829
1830         opj_aligned_free(l_tile_comp->data_win);
1831
1832         ++l_tile_comp;
1833     }
1834
1835     opj_free(l_tile->comps);
1836     l_tile->comps = 00;
1837     opj_free(p_tcd->tcd_image->tiles);
1838     p_tcd->tcd_image->tiles = 00;
1839 }
1840
1841
1842 static OPJ_BOOL opj_tcd_t2_decode(opj_tcd_t *p_tcd,
1843                                   OPJ_BYTE * p_src_data,
1844                                   OPJ_UINT32 * p_data_read,
1845                                   OPJ_UINT32 p_max_src_size,
1846                                   opj_codestream_index_t *p_cstr_index,
1847                                   opj_event_mgr_t *p_manager
1848                                  )
1849 {
1850     opj_t2_t * l_t2;
1851
1852     l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
1853     if (l_t2 == 00) {
1854         return OPJ_FALSE;
1855     }
1856
1857     if (! opj_t2_decode_packets(
1858                 p_tcd,
1859                 l_t2,
1860                 p_tcd->tcd_tileno,
1861                 p_tcd->tcd_image->tiles,
1862                 p_src_data,
1863                 p_data_read,
1864                 p_max_src_size,
1865                 p_cstr_index,
1866                 p_manager)) {
1867         opj_t2_destroy(l_t2);
1868         return OPJ_FALSE;
1869     }
1870
1871     opj_t2_destroy(l_t2);
1872
1873     /*---------------CLEAN-------------------*/
1874     return OPJ_TRUE;
1875 }
1876
1877 static OPJ_BOOL opj_tcd_t1_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
1878 {
1879     OPJ_UINT32 compno;
1880     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
1881     opj_tcd_tilecomp_t* l_tile_comp = l_tile->comps;
1882     opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
1883     volatile OPJ_BOOL ret = OPJ_TRUE;
1884     OPJ_BOOL check_pterm = OPJ_FALSE;
1885     opj_mutex_t* p_manager_mutex = NULL;
1886
1887     p_manager_mutex = opj_mutex_create();
1888
1889     /* Only enable PTERM check if we decode all layers */
1890     if (p_tcd->tcp->num_layers_to_decode == p_tcd->tcp->numlayers &&
1891             (l_tccp->cblksty & J2K_CCP_CBLKSTY_PTERM) != 0) {
1892         check_pterm = OPJ_TRUE;
1893     }
1894
1895     for (compno = 0; compno < l_tile->numcomps; ++compno) {
1896         opj_t1_decode_cblks(p_tcd, &ret, l_tile_comp, l_tccp,
1897                             p_manager, p_manager_mutex, check_pterm);
1898         if (!ret) {
1899             break;
1900         }
1901         ++l_tile_comp;
1902         ++l_tccp;
1903     }
1904
1905     opj_thread_pool_wait_completion(p_tcd->thread_pool, 0);
1906     if (p_manager_mutex) {
1907         opj_mutex_destroy(p_manager_mutex);
1908     }
1909     return ret;
1910 }
1911
1912
1913 static OPJ_BOOL opj_tcd_dwt_decode(opj_tcd_t *p_tcd)
1914 {
1915     OPJ_UINT32 compno;
1916     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
1917     opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
1918     opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
1919     opj_image_comp_t * l_img_comp = p_tcd->image->comps;
1920
1921     for (compno = 0; compno < l_tile->numcomps; compno++) {
1922
1923         if (l_tccp->qmfbid == 1) {
1924             if (! opj_dwt_decode(p_tcd, l_tile_comp,
1925                                  l_img_comp->resno_decoded + 1)) {
1926                 return OPJ_FALSE;
1927             }
1928         } else {
1929             if (! opj_dwt_decode_real(p_tcd, l_tile_comp,
1930                                       l_img_comp->resno_decoded + 1)) {
1931                 return OPJ_FALSE;
1932             }
1933         }
1934
1935         ++l_tile_comp;
1936         ++l_img_comp;
1937         ++l_tccp;
1938     }
1939
1940     return OPJ_TRUE;
1941 }
1942
1943 static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
1944 {
1945     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
1946     opj_tcp_t * l_tcp = p_tcd->tcp;
1947     opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
1948     OPJ_UINT32 l_samples, i;
1949
1950     if (! l_tcp->mct) {
1951         return OPJ_TRUE;
1952     }
1953
1954     if (p_tcd->whole_tile_decoding) {
1955         /* A bit inefficient: we process more data than needed if */
1956         /* resno_decoded < l_tile_comp->minimum_num_resolutions-1, */
1957         /* but we would need to take into account a stride then */
1958         l_samples = (OPJ_UINT32)((
1959                                      l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].x1 -
1960                                      l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].x0) *
1961                                  (l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].y1 -
1962                                   l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].y0));
1963     } else {
1964         opj_tcd_resolution_t* l_res;
1965         l_res = l_tile_comp->resolutions + p_tcd->image->comps[0].resno_decoded;
1966         l_samples = (l_res->win_x1 - l_res->win_x0) *
1967                     (l_res->win_y1 - l_res->win_y0);
1968     }
1969
1970     if (l_tile->numcomps >= 3) {
1971         opj_tcd_resolution_t* res_comp0 = l_tile->comps[0].resolutions +
1972                                           p_tcd->image->comps[0].resno_decoded;
1973         opj_tcd_resolution_t* res_comp1 = l_tile->comps[1].resolutions +
1974                                           p_tcd->image->comps[1].resno_decoded;
1975         opj_tcd_resolution_t* res_comp2 = l_tile->comps[2].resolutions +
1976                                           p_tcd->image->comps[2].resno_decoded;
1977         size_t l_res_samples = (size_t)(res_comp0->x1 - res_comp0->x0) *
1978                                (size_t)(res_comp0->y1 - res_comp0->y0);
1979         /* testcase 1336.pdf.asan.47.376 */
1980         if (p_tcd->image->comps[0].resno_decoded !=
1981                 p_tcd->image->comps[1].resno_decoded ||
1982                 p_tcd->image->comps[0].resno_decoded !=
1983                 p_tcd->image->comps[2].resno_decoded ||
1984                 (size_t)(res_comp1->x1 - res_comp1->x0) *
1985                 (size_t)(res_comp1->y1 - res_comp1->y0) != l_res_samples ||
1986                 (size_t)(res_comp2->x1 - res_comp2->x0) *
1987                 (size_t)(res_comp2->y1 - res_comp2->y0) != l_res_samples) {
1988             opj_event_msg(p_manager, EVT_ERROR,
1989                           "Tiles don't all have the same dimension. Skip the MCT step.\n");
1990             return OPJ_FALSE;
1991         } else if (l_tcp->mct == 2) {
1992             OPJ_BYTE ** l_data;
1993
1994             if (! l_tcp->m_mct_decoding_matrix) {
1995                 return OPJ_TRUE;
1996             }
1997
1998             l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*));
1999             if (! l_data) {
2000                 return OPJ_FALSE;
2001             }
2002
2003             for (i = 0; i < l_tile->numcomps; ++i) {
2004                 if (p_tcd->whole_tile_decoding) {
2005                     l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
2006                 } else {
2007                     l_data[i] = (OPJ_BYTE*) l_tile_comp->data_win;
2008                 }
2009                 ++l_tile_comp;
2010             }
2011
2012             if (! opj_mct_decode_custom(/* MCT data */
2013                         (OPJ_BYTE*) l_tcp->m_mct_decoding_matrix,
2014                         /* size of components */
2015                         l_samples,
2016                         /* components */
2017                         l_data,
2018                         /* nb of components (i.e. size of pData) */
2019                         l_tile->numcomps,
2020                         /* tells if the data is signed */
2021                         p_tcd->image->comps->sgnd)) {
2022                 opj_free(l_data);
2023                 return OPJ_FALSE;
2024             }
2025
2026             opj_free(l_data);
2027         } else {
2028             if (l_tcp->tccps->qmfbid == 1) {
2029                 if (p_tcd->whole_tile_decoding) {
2030                     opj_mct_decode(l_tile->comps[0].data,
2031                                    l_tile->comps[1].data,
2032                                    l_tile->comps[2].data,
2033                                    l_samples);
2034                 } else {
2035                     opj_mct_decode(l_tile->comps[0].data_win,
2036                                    l_tile->comps[1].data_win,
2037                                    l_tile->comps[2].data_win,
2038                                    l_samples);
2039                 }
2040             } else {
2041                 if (p_tcd->whole_tile_decoding) {
2042                     opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data,
2043                                         (OPJ_FLOAT32*)l_tile->comps[1].data,
2044                                         (OPJ_FLOAT32*)l_tile->comps[2].data,
2045                                         l_samples);
2046                 } else {
2047                     opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data_win,
2048                                         (OPJ_FLOAT32*)l_tile->comps[1].data_win,
2049                                         (OPJ_FLOAT32*)l_tile->comps[2].data_win,
2050                                         l_samples);
2051                 }
2052             }
2053         }
2054     } else {
2055         opj_event_msg(p_manager, EVT_ERROR,
2056                       "Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n",
2057                       l_tile->numcomps);
2058     }
2059
2060     return OPJ_TRUE;
2061 }
2062
2063
2064 static OPJ_BOOL opj_tcd_dc_level_shift_decode(opj_tcd_t *p_tcd)
2065 {
2066     OPJ_UINT32 compno;
2067     opj_tcd_tilecomp_t * l_tile_comp = 00;
2068     opj_tccp_t * l_tccp = 00;
2069     opj_image_comp_t * l_img_comp = 00;
2070     opj_tcd_resolution_t* l_res = 00;
2071     opj_tcd_tile_t * l_tile;
2072     OPJ_UINT32 l_width, l_height, i, j;
2073     OPJ_INT32 * l_current_ptr;
2074     OPJ_INT32 l_min, l_max;
2075     OPJ_UINT32 l_stride;
2076
2077     l_tile = p_tcd->tcd_image->tiles;
2078     l_tile_comp = l_tile->comps;
2079     l_tccp = p_tcd->tcp->tccps;
2080     l_img_comp = p_tcd->image->comps;
2081
2082     for (compno = 0; compno < l_tile->numcomps; compno++) {
2083         l_res = l_tile_comp->resolutions + l_img_comp->resno_decoded;
2084
2085         if (!p_tcd->whole_tile_decoding) {
2086             l_width = l_res->win_x1 - l_res->win_x0;
2087             l_height = l_res->win_y1 - l_res->win_y0;
2088             l_stride = 0;
2089             l_current_ptr = l_tile_comp->data_win;
2090         } else {
2091             l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0);
2092             l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0);
2093             l_stride = (OPJ_UINT32)(
2094                            l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].x1 -
2095                            l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].x0)
2096                        - l_width;
2097             l_current_ptr = l_tile_comp->data;
2098
2099             assert(l_height == 0 ||
2100                    l_width + l_stride <= l_tile_comp->data_size / l_height); /*MUPDF*/
2101         }
2102
2103         if (l_img_comp->sgnd) {
2104             l_min = -(1 << (l_img_comp->prec - 1));
2105             l_max = (1 << (l_img_comp->prec - 1)) - 1;
2106         } else {
2107             l_min = 0;
2108             l_max = (OPJ_INT32)((1U << l_img_comp->prec) - 1);
2109         }
2110
2111
2112         if (l_tccp->qmfbid == 1) {
2113             for (j = 0; j < l_height; ++j) {
2114                 for (i = 0; i < l_width; ++i) {
2115                     *l_current_ptr = opj_int_clamp(*l_current_ptr + l_tccp->m_dc_level_shift, l_min,
2116                                                    l_max);
2117                     ++l_current_ptr;
2118                 }
2119                 l_current_ptr += l_stride;
2120             }
2121         } else {
2122             for (j = 0; j < l_height; ++j) {
2123                 for (i = 0; i < l_width; ++i) {
2124                     OPJ_FLOAT32 l_value = *((OPJ_FLOAT32 *) l_current_ptr);
2125                     OPJ_INT32 l_value_int = (OPJ_INT32)opj_lrintf(l_value);
2126                     if (l_value > INT_MAX ||
2127                             (l_value_int > 0 && l_tccp->m_dc_level_shift > 0 &&
2128                              l_value_int > INT_MAX - l_tccp->m_dc_level_shift)) {
2129                         *l_current_ptr = l_max;
2130                     } else {
2131                         *l_current_ptr = opj_int_clamp(
2132                                              l_value_int + l_tccp->m_dc_level_shift, l_min, l_max);
2133                     }
2134                     ++l_current_ptr;
2135                 }
2136                 l_current_ptr += l_stride;
2137             }
2138         }
2139
2140         ++l_img_comp;
2141         ++l_tccp;
2142         ++l_tile_comp;
2143     }
2144
2145     return OPJ_TRUE;
2146 }
2147
2148
2149
2150 /**
2151  * Deallocates the encoding data of the given precinct.
2152  */
2153 static void opj_tcd_code_block_dec_deallocate(opj_tcd_precinct_t * p_precinct)
2154 {
2155     OPJ_UINT32 cblkno, l_nb_code_blocks;
2156
2157     opj_tcd_cblk_dec_t * l_code_block = p_precinct->cblks.dec;
2158     if (l_code_block) {
2159         /*fprintf(stderr,"deallocate codeblock:{\n");*/
2160         /*fprintf(stderr,"\t x0=%d, y0=%d, x1=%d, y1=%d\n",l_code_block->x0, l_code_block->y0, l_code_block->x1, l_code_block->y1);*/
2161         /*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ",
2162                         l_code_block->numbps, l_code_block->numlenbits, l_code_block->len, l_code_block->numnewpasses, l_code_block->real_num_segs, l_code_block->m_current_max_segs );*/
2163
2164
2165         l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_dec_t);
2166         /*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/
2167
2168         for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
2169
2170             if (l_code_block->segs) {
2171                 opj_free(l_code_block->segs);
2172                 l_code_block->segs = 00;
2173             }
2174
2175             if (l_code_block->chunks) {
2176                 opj_free(l_code_block->chunks);
2177                 l_code_block->chunks = 00;
2178             }
2179
2180             opj_free(l_code_block->decoded_data);
2181             l_code_block->decoded_data = NULL;
2182
2183             ++l_code_block;
2184         }
2185
2186         opj_free(p_precinct->cblks.dec);
2187         p_precinct->cblks.dec = 00;
2188     }
2189 }
2190
2191 /**
2192  * Deallocates the encoding data of the given precinct.
2193  */
2194 static void opj_tcd_code_block_enc_deallocate(opj_tcd_precinct_t * p_precinct)
2195 {
2196     OPJ_UINT32 cblkno, l_nb_code_blocks;
2197
2198     opj_tcd_cblk_enc_t * l_code_block = p_precinct->cblks.enc;
2199     if (l_code_block) {
2200         l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_enc_t);
2201
2202         for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno)  {
2203             if (l_code_block->data) {
2204                 /* We refer to data - 1 since below we incremented it */
2205                 /* in opj_tcd_code_block_enc_allocate_data() */
2206                 opj_free(l_code_block->data - 1);
2207                 l_code_block->data = 00;
2208             }
2209
2210             if (l_code_block->layers) {
2211                 opj_free(l_code_block->layers);
2212                 l_code_block->layers = 00;
2213             }
2214
2215             if (l_code_block->passes) {
2216                 opj_free(l_code_block->passes);
2217                 l_code_block->passes = 00;
2218             }
2219             ++l_code_block;
2220         }
2221
2222         opj_free(p_precinct->cblks.enc);
2223
2224         p_precinct->cblks.enc = 00;
2225     }
2226 }
2227
2228 OPJ_SIZE_T opj_tcd_get_encoded_tile_size(opj_tcd_t *p_tcd)
2229 {
2230     OPJ_UINT32 i;
2231     OPJ_SIZE_T l_data_size = 0;
2232     opj_image_comp_t * l_img_comp = 00;
2233     opj_tcd_tilecomp_t * l_tilec = 00;
2234     OPJ_UINT32 l_size_comp, l_remaining;
2235
2236     l_tilec = p_tcd->tcd_image->tiles->comps;
2237     l_img_comp = p_tcd->image->comps;
2238     for (i = 0; i < p_tcd->image->numcomps; ++i) {
2239         l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
2240         l_remaining = l_img_comp->prec & 7;  /* (%8) */
2241
2242         if (l_remaining) {
2243             ++l_size_comp;
2244         }
2245
2246         if (l_size_comp == 3) {
2247             l_size_comp = 4;
2248         }
2249
2250         l_data_size += l_size_comp * ((OPJ_SIZE_T)(l_tilec->x1 - l_tilec->x0) *
2251                                       (OPJ_SIZE_T)(l_tilec->y1 - l_tilec->y0));
2252         ++l_img_comp;
2253         ++l_tilec;
2254     }
2255
2256     return l_data_size;
2257 }
2258
2259 static OPJ_BOOL opj_tcd_dc_level_shift_encode(opj_tcd_t *p_tcd)
2260 {
2261     OPJ_UINT32 compno;
2262     opj_tcd_tilecomp_t * l_tile_comp = 00;
2263     opj_tccp_t * l_tccp = 00;
2264     opj_image_comp_t * l_img_comp = 00;
2265     opj_tcd_tile_t * l_tile;
2266     size_t l_nb_elem, i;
2267     OPJ_INT32 * l_current_ptr;
2268
2269     l_tile = p_tcd->tcd_image->tiles;
2270     l_tile_comp = l_tile->comps;
2271     l_tccp = p_tcd->tcp->tccps;
2272     l_img_comp = p_tcd->image->comps;
2273
2274     for (compno = 0; compno < l_tile->numcomps; compno++) {
2275         l_current_ptr = l_tile_comp->data;
2276         l_nb_elem = (size_t)(l_tile_comp->x1 - l_tile_comp->x0) *
2277                     (size_t)(l_tile_comp->y1 - l_tile_comp->y0);
2278
2279         if (l_tccp->qmfbid == 1) {
2280             for (i = 0; i < l_nb_elem; ++i) {
2281                 *l_current_ptr -= l_tccp->m_dc_level_shift ;
2282                 ++l_current_ptr;
2283             }
2284         } else {
2285             for (i = 0; i < l_nb_elem; ++i) {
2286                 *l_current_ptr = (*l_current_ptr - l_tccp->m_dc_level_shift) * (1 << 11);
2287                 ++l_current_ptr;
2288             }
2289         }
2290
2291         ++l_img_comp;
2292         ++l_tccp;
2293         ++l_tile_comp;
2294     }
2295
2296     return OPJ_TRUE;
2297 }
2298
2299 static OPJ_BOOL opj_tcd_mct_encode(opj_tcd_t *p_tcd)
2300 {
2301     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
2302     opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
2303     size_t samples = (size_t)(l_tile_comp->x1 - l_tile_comp->x0) *
2304                      (size_t)(l_tile_comp->y1 - l_tile_comp->y0);
2305     OPJ_UINT32 i;
2306     OPJ_BYTE ** l_data = 00;
2307     opj_tcp_t * l_tcp = p_tcd->tcp;
2308
2309     if (!p_tcd->tcp->mct) {
2310         return OPJ_TRUE;
2311     }
2312
2313     if (p_tcd->tcp->mct == 2) {
2314         if (! p_tcd->tcp->m_mct_coding_matrix) {
2315             return OPJ_TRUE;
2316         }
2317
2318         l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*));
2319         if (! l_data) {
2320             return OPJ_FALSE;
2321         }
2322
2323         for (i = 0; i < l_tile->numcomps; ++i) {
2324             l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
2325             ++l_tile_comp;
2326         }
2327
2328         if (! opj_mct_encode_custom(/* MCT data */
2329                     (OPJ_BYTE*) p_tcd->tcp->m_mct_coding_matrix,
2330                     /* size of components */
2331                     samples,
2332                     /* components */
2333                     l_data,
2334                     /* nb of components (i.e. size of pData) */
2335                     l_tile->numcomps,
2336                     /* tells if the data is signed */
2337                     p_tcd->image->comps->sgnd)) {
2338             opj_free(l_data);
2339             return OPJ_FALSE;
2340         }
2341
2342         opj_free(l_data);
2343     } else if (l_tcp->tccps->qmfbid == 0) {
2344         opj_mct_encode_real(l_tile->comps[0].data, l_tile->comps[1].data,
2345                             l_tile->comps[2].data, samples);
2346     } else {
2347         opj_mct_encode(l_tile->comps[0].data, l_tile->comps[1].data,
2348                        l_tile->comps[2].data, samples);
2349     }
2350
2351     return OPJ_TRUE;
2352 }
2353
2354 static OPJ_BOOL opj_tcd_dwt_encode(opj_tcd_t *p_tcd)
2355 {
2356     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
2357     opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
2358     opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
2359     OPJ_UINT32 compno;
2360
2361     for (compno = 0; compno < l_tile->numcomps; ++compno) {
2362         if (l_tccp->qmfbid == 1) {
2363             if (! opj_dwt_encode(l_tile_comp)) {
2364                 return OPJ_FALSE;
2365             }
2366         } else if (l_tccp->qmfbid == 0) {
2367             if (! opj_dwt_encode_real(l_tile_comp)) {
2368                 return OPJ_FALSE;
2369             }
2370         }
2371
2372         ++l_tile_comp;
2373         ++l_tccp;
2374     }
2375
2376     return OPJ_TRUE;
2377 }
2378
2379 static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd)
2380 {
2381     opj_t1_t * l_t1;
2382     const OPJ_FLOAT64 * l_mct_norms;
2383     OPJ_UINT32 l_mct_numcomps = 0U;
2384     opj_tcp_t * l_tcp = p_tcd->tcp;
2385
2386     l_t1 = opj_t1_create(OPJ_TRUE);
2387     if (l_t1 == 00) {
2388         return OPJ_FALSE;
2389     }
2390
2391     if (l_tcp->mct == 1) {
2392         l_mct_numcomps = 3U;
2393         /* irreversible encoding */
2394         if (l_tcp->tccps->qmfbid == 0) {
2395             l_mct_norms = opj_mct_get_mct_norms_real();
2396         } else {
2397             l_mct_norms = opj_mct_get_mct_norms();
2398         }
2399     } else {
2400         l_mct_numcomps = p_tcd->image->numcomps;
2401         l_mct_norms = (const OPJ_FLOAT64 *)(l_tcp->mct_norms);
2402     }
2403
2404     if (! opj_t1_encode_cblks(l_t1, p_tcd->tcd_image->tiles, l_tcp, l_mct_norms,
2405                               l_mct_numcomps)) {
2406         opj_t1_destroy(l_t1);
2407         return OPJ_FALSE;
2408     }
2409
2410     opj_t1_destroy(l_t1);
2411
2412     return OPJ_TRUE;
2413 }
2414
2415 static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd,
2416                                   OPJ_BYTE * p_dest_data,
2417                                   OPJ_UINT32 * p_data_written,
2418                                   OPJ_UINT32 p_max_dest_size,
2419                                   opj_codestream_info_t *p_cstr_info,
2420                                   opj_event_mgr_t *p_manager)
2421 {
2422     opj_t2_t * l_t2;
2423
2424     l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
2425     if (l_t2 == 00) {
2426         return OPJ_FALSE;
2427     }
2428
2429     if (! opj_t2_encode_packets(
2430                 l_t2,
2431                 p_tcd->tcd_tileno,
2432                 p_tcd->tcd_image->tiles,
2433                 p_tcd->tcp->numlayers,
2434                 p_dest_data,
2435                 p_data_written,
2436                 p_max_dest_size,
2437                 p_cstr_info,
2438                 p_tcd->tp_num,
2439                 p_tcd->tp_pos,
2440                 p_tcd->cur_pino,
2441                 FINAL_PASS,
2442                 p_manager)) {
2443         opj_t2_destroy(l_t2);
2444         return OPJ_FALSE;
2445     }
2446
2447     opj_t2_destroy(l_t2);
2448
2449     /*---------------CLEAN-------------------*/
2450     return OPJ_TRUE;
2451 }
2452
2453
2454 static OPJ_BOOL opj_tcd_rate_allocate_encode(opj_tcd_t *p_tcd,
2455         OPJ_BYTE * p_dest_data,
2456         OPJ_UINT32 p_max_dest_size,
2457         opj_codestream_info_t *p_cstr_info,
2458         opj_event_mgr_t *p_manager)
2459 {
2460     opj_cp_t * l_cp = p_tcd->cp;
2461     OPJ_UINT32 l_nb_written = 0;
2462
2463     if (p_cstr_info)  {
2464         p_cstr_info->index_write = 0;
2465     }
2466
2467     if (l_cp->m_specific_param.m_enc.m_disto_alloc ||
2468             l_cp->m_specific_param.m_enc.m_fixed_quality)  {
2469         /* fixed_quality */
2470         /* Normal Rate/distortion allocation */
2471         if (! opj_tcd_rateallocate(p_tcd, p_dest_data, &l_nb_written, p_max_dest_size,
2472                                    p_cstr_info, p_manager)) {
2473             return OPJ_FALSE;
2474         }
2475     } else {
2476         /* Fixed layer allocation */
2477         opj_tcd_rateallocate_fixed(p_tcd);
2478     }
2479
2480     return OPJ_TRUE;
2481 }
2482
2483
2484 OPJ_BOOL opj_tcd_copy_tile_data(opj_tcd_t *p_tcd,
2485                                 OPJ_BYTE * p_src,
2486                                 OPJ_SIZE_T p_src_length)
2487 {
2488     OPJ_UINT32 i;
2489     OPJ_SIZE_T j;
2490     OPJ_SIZE_T l_data_size = 0;
2491     opj_image_comp_t * l_img_comp = 00;
2492     opj_tcd_tilecomp_t * l_tilec = 00;
2493     OPJ_UINT32 l_size_comp, l_remaining;
2494     OPJ_SIZE_T l_nb_elem;
2495
2496     l_data_size = opj_tcd_get_encoded_tile_size(p_tcd);
2497     if (l_data_size != p_src_length) {
2498         return OPJ_FALSE;
2499     }
2500
2501     l_tilec = p_tcd->tcd_image->tiles->comps;
2502     l_img_comp = p_tcd->image->comps;
2503     for (i = 0; i < p_tcd->image->numcomps; ++i) {
2504         l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
2505         l_remaining = l_img_comp->prec & 7;  /* (%8) */
2506         l_nb_elem = (size_t)(l_tilec->x1 - l_tilec->x0) *
2507                     (size_t)(l_tilec->y1 - l_tilec->y0);
2508
2509         if (l_remaining) {
2510             ++l_size_comp;
2511         }
2512
2513         if (l_size_comp == 3) {
2514             l_size_comp = 4;
2515         }
2516
2517         switch (l_size_comp) {
2518         case 1: {
2519             OPJ_CHAR * l_src_ptr = (OPJ_CHAR *) p_src;
2520             OPJ_INT32 * l_dest_ptr = l_tilec->data;
2521
2522             if (l_img_comp->sgnd) {
2523                 for (j = 0; j < l_nb_elem; ++j) {
2524                     *(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
2525                 }
2526             } else {
2527                 for (j = 0; j < l_nb_elem; ++j) {
2528                     *(l_dest_ptr++) = (*(l_src_ptr++)) & 0xff;
2529                 }
2530             }
2531
2532             p_src = (OPJ_BYTE*) l_src_ptr;
2533         }
2534         break;
2535         case 2: {
2536             OPJ_INT32 * l_dest_ptr = l_tilec->data;
2537             OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_src;
2538
2539             if (l_img_comp->sgnd) {
2540                 for (j = 0; j < l_nb_elem; ++j) {
2541                     *(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
2542                 }
2543             } else {
2544                 for (j = 0; j < l_nb_elem; ++j) {
2545                     *(l_dest_ptr++) = (*(l_src_ptr++)) & 0xffff;
2546                 }
2547             }
2548
2549             p_src = (OPJ_BYTE*) l_src_ptr;
2550         }
2551         break;
2552         case 4: {
2553             OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_src;
2554             OPJ_INT32 * l_dest_ptr = l_tilec->data;
2555
2556             for (j = 0; j < l_nb_elem; ++j) {
2557                 *(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
2558             }
2559
2560             p_src = (OPJ_BYTE*) l_src_ptr;
2561         }
2562         break;
2563         }
2564
2565         ++l_img_comp;
2566         ++l_tilec;
2567     }
2568
2569     return OPJ_TRUE;
2570 }
2571
2572 OPJ_BOOL opj_tcd_is_band_empty(opj_tcd_band_t* band)
2573 {
2574     return (band->x1 - band->x0 == 0) || (band->y1 - band->y0 == 0);
2575 }
2576
2577 OPJ_BOOL opj_tcd_is_subband_area_of_interest(opj_tcd_t *tcd,
2578         OPJ_UINT32 compno,
2579         OPJ_UINT32 resno,
2580         OPJ_UINT32 bandno,
2581         OPJ_UINT32 band_x0,
2582         OPJ_UINT32 band_y0,
2583         OPJ_UINT32 band_x1,
2584         OPJ_UINT32 band_y1)
2585 {
2586     /* Note: those values for filter_margin are in part the result of */
2587     /* experimentation. The value 2 for QMFBID=1 (5x3 filter) can be linked */
2588     /* to the maximum left/right extension given in tables F.2 and F.3 of the */
2589     /* standard. The value 3 for QMFBID=0 (9x7 filter) is more suspicious, */
2590     /* since F.2 and F.3 would lead to 4 instead, so the current 3 might be */
2591     /* needed to be bumped to 4, in case inconsistencies are found while */
2592     /* decoding parts of irreversible coded images. */
2593     /* See opj_dwt_decode_partial_53 and opj_dwt_decode_partial_97 as well */
2594     OPJ_UINT32 filter_margin = (tcd->tcp->tccps[compno].qmfbid == 1) ? 2 : 3;
2595     opj_tcd_tilecomp_t *tilec = &(tcd->tcd_image->tiles->comps[compno]);
2596     opj_image_comp_t* image_comp = &(tcd->image->comps[compno]);
2597     /* Compute the intersection of the area of interest, expressed in tile coordinates */
2598     /* with the tile coordinates */
2599     OPJ_UINT32 tcx0 = opj_uint_max(
2600                           (OPJ_UINT32)tilec->x0,
2601                           opj_uint_ceildiv(tcd->win_x0, image_comp->dx));
2602     OPJ_UINT32 tcy0 = opj_uint_max(
2603                           (OPJ_UINT32)tilec->y0,
2604                           opj_uint_ceildiv(tcd->win_y0, image_comp->dy));
2605     OPJ_UINT32 tcx1 = opj_uint_min(
2606                           (OPJ_UINT32)tilec->x1,
2607                           opj_uint_ceildiv(tcd->win_x1, image_comp->dx));
2608     OPJ_UINT32 tcy1 = opj_uint_min(
2609                           (OPJ_UINT32)tilec->y1,
2610                           opj_uint_ceildiv(tcd->win_y1, image_comp->dy));
2611     /* Compute number of decomposition for this band. See table F-1 */
2612     OPJ_UINT32 nb = (resno == 0) ?
2613                     tilec->numresolutions - 1 :
2614                     tilec->numresolutions - resno;
2615     /* Map above tile-based coordinates to sub-band-based coordinates per */
2616     /* equation B-15 of the standard */
2617     OPJ_UINT32 x0b = bandno & 1;
2618     OPJ_UINT32 y0b = bandno >> 1;
2619     OPJ_UINT32 tbx0 = (nb == 0) ? tcx0 :
2620                       (tcx0 <= (1U << (nb - 1)) * x0b) ? 0 :
2621                       opj_uint_ceildivpow2(tcx0 - (1U << (nb - 1)) * x0b, nb);
2622     OPJ_UINT32 tby0 = (nb == 0) ? tcy0 :
2623                       (tcy0 <= (1U << (nb - 1)) * y0b) ? 0 :
2624                       opj_uint_ceildivpow2(tcy0 - (1U << (nb - 1)) * y0b, nb);
2625     OPJ_UINT32 tbx1 = (nb == 0) ? tcx1 :
2626                       (tcx1 <= (1U << (nb - 1)) * x0b) ? 0 :
2627                       opj_uint_ceildivpow2(tcx1 - (1U << (nb - 1)) * x0b, nb);
2628     OPJ_UINT32 tby1 = (nb == 0) ? tcy1 :
2629                       (tcy1 <= (1U << (nb - 1)) * y0b) ? 0 :
2630                       opj_uint_ceildivpow2(tcy1 - (1U << (nb - 1)) * y0b, nb);
2631     OPJ_BOOL intersects;
2632
2633     if (tbx0 < filter_margin) {
2634         tbx0 = 0;
2635     } else {
2636         tbx0 -= filter_margin;
2637     }
2638     if (tby0 < filter_margin) {
2639         tby0 = 0;
2640     } else {
2641         tby0 -= filter_margin;
2642     }
2643     tbx1 = opj_uint_adds(tbx1, filter_margin);
2644     tby1 = opj_uint_adds(tby1, filter_margin);
2645
2646     intersects = band_x0 < tbx1 && band_y0 < tby1 && band_x1 > tbx0 &&
2647                  band_y1 > tby0;
2648
2649 #ifdef DEBUG_VERBOSE
2650     printf("compno=%u resno=%u nb=%u bandno=%u x0b=%u y0b=%u band=%u,%u,%u,%u tb=%u,%u,%u,%u -> %u\n",
2651            compno, resno, nb, bandno, x0b, y0b,
2652            band_x0, band_y0, band_x1, band_y1,
2653            tbx0, tby0, tbx1, tby1, intersects);
2654 #endif
2655     return intersects;
2656 }
2657
2658 /** Returns whether a tile componenent is fully decoded, taking into account
2659  * p_tcd->win_* members.
2660  *
2661  * @param p_tcd    TCD handle.
2662  * @param compno Component number
2663  * @return OPJ_TRUE whether the tile componenent is fully decoded
2664  */
2665 static OPJ_BOOL opj_tcd_is_whole_tilecomp_decoding(opj_tcd_t *p_tcd,
2666         OPJ_UINT32 compno)
2667 {
2668     opj_tcd_tilecomp_t* tilec = &(p_tcd->tcd_image->tiles->comps[compno]);
2669     opj_image_comp_t* image_comp = &(p_tcd->image->comps[compno]);
2670     /* Compute the intersection of the area of interest, expressed in tile coordinates */
2671     /* with the tile coordinates */
2672     OPJ_UINT32 tcx0 = opj_uint_max(
2673                           (OPJ_UINT32)tilec->x0,
2674                           opj_uint_ceildiv(p_tcd->win_x0, image_comp->dx));
2675     OPJ_UINT32 tcy0 = opj_uint_max(
2676                           (OPJ_UINT32)tilec->y0,
2677                           opj_uint_ceildiv(p_tcd->win_y0, image_comp->dy));
2678     OPJ_UINT32 tcx1 = opj_uint_min(
2679                           (OPJ_UINT32)tilec->x1,
2680                           opj_uint_ceildiv(p_tcd->win_x1, image_comp->dx));
2681     OPJ_UINT32 tcy1 = opj_uint_min(
2682                           (OPJ_UINT32)tilec->y1,
2683                           opj_uint_ceildiv(p_tcd->win_y1, image_comp->dy));
2684
2685     OPJ_UINT32 shift = tilec->numresolutions - tilec->minimum_num_resolutions;
2686     /* Tolerate small margin within the reduced resolution factor to consider if */
2687     /* the whole tile path must be taken */
2688     return (tcx0 >= (OPJ_UINT32)tilec->x0 &&
2689             tcy0 >= (OPJ_UINT32)tilec->y0 &&
2690             tcx1 <= (OPJ_UINT32)tilec->x1 &&
2691             tcy1 <= (OPJ_UINT32)tilec->y1 &&
2692             (shift >= 32 ||
2693              (((tcx0 - (OPJ_UINT32)tilec->x0) >> shift) == 0 &&
2694               ((tcy0 - (OPJ_UINT32)tilec->y0) >> shift) == 0 &&
2695               (((OPJ_UINT32)tilec->x1 - tcx1) >> shift) == 0 &&
2696               (((OPJ_UINT32)tilec->y1 - tcy1) >> shift) == 0)));
2697 }