0ec85891c75201cda25e4d4a783d31ce1f71cf8a
[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, "Size of tile data exceeds system limits\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, "Size of tile data exceeds system limits\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, "Size of tile data exceeds system limits\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, "Size of tile data exceeds system limits\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_aligned_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,
1474                               "Size of tile data exceeds system limits\n");
1475                 return OPJ_FALSE;
1476             }
1477             l_data_size = res_w * res_h;
1478
1479             if (SIZE_MAX / sizeof(OPJ_UINT32) < l_data_size) {
1480                 opj_event_msg(p_manager, EVT_ERROR,
1481                               "Size of tile data exceeds system limits\n");
1482                 return OPJ_FALSE;
1483             }
1484             l_data_size *= sizeof(OPJ_UINT32);
1485
1486             tilec->data_size_needed = l_data_size;
1487
1488             if (!opj_alloc_tile_component_data(tilec)) {
1489                 opj_event_msg(p_manager, EVT_ERROR,
1490                               "Size of tile data exceeds system limits\n");
1491                 return OPJ_FALSE;
1492             }
1493         }
1494     } else {
1495         /* Compute restricted tile-component and tile-resolution coordinates */
1496         /* of the window of interest, but defer the memory allocation until */
1497         /* we know the resno_decoded */
1498         for (compno = 0; compno < p_tcd->image->numcomps; compno++) {
1499             OPJ_UINT32 resno;
1500             opj_tcd_tilecomp_t* tilec = &(p_tcd->tcd_image->tiles->comps[compno]);
1501             opj_image_comp_t* image_comp = &(p_tcd->image->comps[compno]);
1502             /* Compute the intersection of the area of interest, expressed in tile coordinates */
1503             /* with the tile coordinates */
1504             tilec->win_x0 = opj_uint_max(
1505                                 (OPJ_UINT32)tilec->x0,
1506                                 opj_uint_ceildiv(p_tcd->win_x0, image_comp->dx));
1507             tilec->win_y0 = opj_uint_max(
1508                                 (OPJ_UINT32)tilec->y0,
1509                                 opj_uint_ceildiv(p_tcd->win_y0, image_comp->dy));
1510             tilec->win_x1 = opj_uint_min(
1511                                 (OPJ_UINT32)tilec->x1,
1512                                 opj_uint_ceildiv(p_tcd->win_x1, image_comp->dx));
1513             tilec->win_y1 = opj_uint_min(
1514                                 (OPJ_UINT32)tilec->y1,
1515                                 opj_uint_ceildiv(p_tcd->win_y1, image_comp->dy));
1516
1517             for (resno = 0; resno < tilec->numresolutions; ++resno) {
1518                 opj_tcd_resolution_t *res = tilec->resolutions + resno;
1519                 res->win_x0 = opj_uint_ceildivpow2(tilec->win_x0,
1520                                                    tilec->numresolutions - 1 - resno);
1521                 res->win_y0 = opj_uint_ceildivpow2(tilec->win_y0,
1522                                                    tilec->numresolutions - 1 - resno);
1523                 res->win_x1 = opj_uint_ceildivpow2(tilec->win_x1,
1524                                                    tilec->numresolutions - 1 - resno);
1525                 res->win_y1 = opj_uint_ceildivpow2(tilec->win_y1,
1526                                                    tilec->numresolutions - 1 - resno);
1527             }
1528         }
1529     }
1530
1531 #ifdef TODO_MSD /* FIXME */
1532     /* INDEX >>  */
1533     if (p_cstr_info) {
1534         OPJ_UINT32 resno, compno, numprec = 0;
1535         for (compno = 0; compno < (OPJ_UINT32) p_cstr_info->numcomps; compno++) {
1536             opj_tcp_t *tcp = &p_tcd->cp->tcps[0];
1537             opj_tccp_t *tccp = &tcp->tccps[compno];
1538             opj_tcd_tilecomp_t *tilec_idx = &p_tcd->tcd_image->tiles->comps[compno];
1539             for (resno = 0; resno < tilec_idx->numresolutions; resno++) {
1540                 opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[resno];
1541                 p_cstr_info->tile[p_tile_no].pw[resno] = res_idx->pw;
1542                 p_cstr_info->tile[p_tile_no].ph[resno] = res_idx->ph;
1543                 numprec += res_idx->pw * res_idx->ph;
1544                 p_cstr_info->tile[p_tile_no].pdx[resno] = tccp->prcw[resno];
1545                 p_cstr_info->tile[p_tile_no].pdy[resno] = tccp->prch[resno];
1546             }
1547         }
1548         p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t *) opj_malloc(
1549                 p_cstr_info->numlayers * numprec * sizeof(opj_packet_info_t));
1550         p_cstr_info->packno = 0;
1551     }
1552     /* << INDEX */
1553 #endif
1554
1555     /*--------------TIER2------------------*/
1556     /* FIXME _ProfStart(PGROUP_T2); */
1557     l_data_read = 0;
1558     if (! opj_tcd_t2_decode(p_tcd, p_src, &l_data_read, p_max_length, p_cstr_index,
1559                             p_manager)) {
1560         return OPJ_FALSE;
1561     }
1562     /* FIXME _ProfStop(PGROUP_T2); */
1563
1564     /*------------------TIER1-----------------*/
1565
1566     /* FIXME _ProfStart(PGROUP_T1); */
1567     if (! opj_tcd_t1_decode(p_tcd, p_manager)) {
1568         return OPJ_FALSE;
1569     }
1570     /* FIXME _ProfStop(PGROUP_T1); */
1571
1572
1573     /* For subtile decoding, now we know the resno_decoded, we can allocate */
1574     /* the tile data buffer */
1575     if (!p_tcd->whole_tile_decoding) {
1576         for (compno = 0; compno < p_tcd->image->numcomps; compno++) {
1577             opj_tcd_tilecomp_t* tilec = &(p_tcd->tcd_image->tiles->comps[compno]);
1578             opj_image_comp_t* image_comp = &(p_tcd->image->comps[compno]);
1579             opj_tcd_resolution_t *res = tilec->resolutions + image_comp->resno_decoded;
1580             size_t w = res->win_x1 - res->win_x0;
1581             size_t h = res->win_y1 - res->win_y0;
1582             size_t l_data_size;
1583
1584             opj_aligned_free(tilec->data_win);
1585             tilec->data_win = NULL;
1586
1587             if (w > 0 && h > 0) {
1588                 if (w > SIZE_MAX / h) {
1589                     opj_event_msg(p_manager, EVT_ERROR,
1590                                   "Size of tile data exceeds system limits\n");
1591                     return OPJ_FALSE;
1592                 }
1593                 l_data_size = w * h;
1594                 if (l_data_size > SIZE_MAX / sizeof(OPJ_INT32)) {
1595                     opj_event_msg(p_manager, EVT_ERROR,
1596                                   "Size of tile data exceeds system limits\n");
1597                     return OPJ_FALSE;
1598                 }
1599                 l_data_size *= sizeof(OPJ_INT32);
1600
1601                 tilec->data_win = opj_aligned_malloc(l_data_size);
1602                 if (tilec->data_win == NULL) {
1603                     opj_event_msg(p_manager, EVT_ERROR,
1604                                   "Size of tile data exceeds system limits\n");
1605                     return OPJ_FALSE;
1606                 }
1607             }
1608         }
1609     }
1610
1611     /*----------------DWT---------------------*/
1612
1613     /* FIXME _ProfStart(PGROUP_DWT); */
1614     if
1615     (! opj_tcd_dwt_decode(p_tcd)) {
1616         return OPJ_FALSE;
1617     }
1618     /* FIXME _ProfStop(PGROUP_DWT); */
1619
1620     /*----------------MCT-------------------*/
1621     /* FIXME _ProfStart(PGROUP_MCT); */
1622     if
1623     (! opj_tcd_mct_decode(p_tcd, p_manager)) {
1624         return OPJ_FALSE;
1625     }
1626     /* FIXME _ProfStop(PGROUP_MCT); */
1627
1628     /* FIXME _ProfStart(PGROUP_DC_SHIFT); */
1629     if
1630     (! opj_tcd_dc_level_shift_decode(p_tcd)) {
1631         return OPJ_FALSE;
1632     }
1633     /* FIXME _ProfStop(PGROUP_DC_SHIFT); */
1634
1635
1636     /*---------------TILE-------------------*/
1637     return OPJ_TRUE;
1638 }
1639
1640 OPJ_BOOL opj_tcd_update_tile_data(opj_tcd_t *p_tcd,
1641                                   OPJ_BYTE * p_dest,
1642                                   OPJ_UINT32 p_dest_length
1643                                  )
1644 {
1645     OPJ_UINT32 i, j, k, l_data_size = 0;
1646     opj_image_comp_t * l_img_comp = 00;
1647     opj_tcd_tilecomp_t * l_tilec = 00;
1648     opj_tcd_resolution_t * l_res;
1649     OPJ_UINT32 l_size_comp, l_remaining;
1650     OPJ_UINT32 l_stride, l_width, l_height;
1651
1652     l_data_size = opj_tcd_get_decoded_tile_size(p_tcd, OPJ_TRUE);
1653     if (l_data_size == UINT_MAX || l_data_size > p_dest_length) {
1654         return OPJ_FALSE;
1655     }
1656
1657     l_tilec = p_tcd->tcd_image->tiles->comps;
1658     l_img_comp = p_tcd->image->comps;
1659
1660     for (i = 0; i < p_tcd->image->numcomps; ++i) {
1661         const OPJ_INT32* l_src_data;
1662         l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
1663         l_remaining = l_img_comp->prec & 7;  /* (%8) */
1664         l_res = l_tilec->resolutions + l_img_comp->resno_decoded;
1665         if (p_tcd->whole_tile_decoding) {
1666             l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0);
1667             l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0);
1668             l_stride = (OPJ_UINT32)(l_tilec->resolutions[l_tilec->minimum_num_resolutions -
1669                                                                      1].x1 -
1670                                     l_tilec->resolutions[l_tilec->minimum_num_resolutions - 1].x0) - l_width;
1671             l_src_data = l_tilec->data;
1672         } else {
1673             l_width = l_res->win_x1 - l_res->win_x0;
1674             l_height = l_res->win_y1 - l_res->win_y0;
1675             l_stride = 0;
1676             l_src_data = l_tilec->data_win;
1677         }
1678
1679         if (l_remaining) {
1680             ++l_size_comp;
1681         }
1682
1683         if (l_size_comp == 3) {
1684             l_size_comp = 4;
1685         }
1686
1687         switch (l_size_comp) {
1688         case 1: {
1689             OPJ_CHAR * l_dest_ptr = (OPJ_CHAR *) p_dest;
1690             const OPJ_INT32 * l_src_ptr = l_src_data;
1691
1692             if (l_img_comp->sgnd) {
1693                 for (j = 0; j < l_height; ++j) {
1694                     for (k = 0; k < l_width; ++k) {
1695                         *(l_dest_ptr++) = (OPJ_CHAR)(*(l_src_ptr++));
1696                     }
1697                     l_src_ptr += l_stride;
1698                 }
1699             } else {
1700                 for (j = 0; j < l_height; ++j) {
1701                     for (k = 0; k < l_width; ++k) {
1702                         *(l_dest_ptr++) = (OPJ_CHAR)((*(l_src_ptr++)) & 0xff);
1703                     }
1704                     l_src_ptr += l_stride;
1705                 }
1706             }
1707
1708             p_dest = (OPJ_BYTE *)l_dest_ptr;
1709         }
1710         break;
1711         case 2: {
1712             const OPJ_INT32 * l_src_ptr = l_src_data;
1713             OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_dest;
1714
1715             if (l_img_comp->sgnd) {
1716                 for (j = 0; j < l_height; ++j) {
1717                     for (k = 0; k < l_width; ++k) {
1718                         OPJ_INT16 val = (OPJ_INT16)(*(l_src_ptr++));
1719                         memcpy(l_dest_ptr, &val, sizeof(val));
1720                         l_dest_ptr ++;
1721                     }
1722                     l_src_ptr += l_stride;
1723                 }
1724             } else {
1725                 for (j = 0; j < l_height; ++j) {
1726                     for (k = 0; k < l_width; ++k) {
1727                         OPJ_INT16 val = (OPJ_INT16)((*(l_src_ptr++)) & 0xffff);
1728                         memcpy(l_dest_ptr, &val, sizeof(val));
1729                         l_dest_ptr ++;
1730                     }
1731                     l_src_ptr += l_stride;
1732                 }
1733             }
1734
1735             p_dest = (OPJ_BYTE*) l_dest_ptr;
1736         }
1737         break;
1738         case 4: {
1739             OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_dest;
1740             const OPJ_INT32 * l_src_ptr = l_src_data;
1741
1742             for (j = 0; j < l_height; ++j) {
1743                 memcpy(l_dest_ptr, l_src_ptr, l_width * sizeof(OPJ_INT32));
1744                 l_dest_ptr += l_width;
1745                 l_src_ptr += l_width + l_stride;
1746             }
1747
1748             p_dest = (OPJ_BYTE*) l_dest_ptr;
1749         }
1750         break;
1751         }
1752
1753         ++l_img_comp;
1754         ++l_tilec;
1755     }
1756
1757     return OPJ_TRUE;
1758 }
1759
1760
1761
1762
1763 static void opj_tcd_free_tile(opj_tcd_t *p_tcd)
1764 {
1765     OPJ_UINT32 compno, resno, bandno, precno;
1766     opj_tcd_tile_t *l_tile = 00;
1767     opj_tcd_tilecomp_t *l_tile_comp = 00;
1768     opj_tcd_resolution_t *l_res = 00;
1769     opj_tcd_band_t *l_band = 00;
1770     opj_tcd_precinct_t *l_precinct = 00;
1771     OPJ_UINT32 l_nb_resolutions, l_nb_precincts;
1772     void (* l_tcd_code_block_deallocate)(opj_tcd_precinct_t *) = 00;
1773
1774     if (! p_tcd) {
1775         return;
1776     }
1777
1778     if (! p_tcd->tcd_image) {
1779         return;
1780     }
1781
1782     if (p_tcd->m_is_decoder) {
1783         l_tcd_code_block_deallocate = opj_tcd_code_block_dec_deallocate;
1784     } else {
1785         l_tcd_code_block_deallocate = opj_tcd_code_block_enc_deallocate;
1786     }
1787
1788     l_tile = p_tcd->tcd_image->tiles;
1789     if (! l_tile) {
1790         return;
1791     }
1792
1793     l_tile_comp = l_tile->comps;
1794
1795     for (compno = 0; compno < l_tile->numcomps; ++compno) {
1796         l_res = l_tile_comp->resolutions;
1797         if (l_res) {
1798
1799             l_nb_resolutions = l_tile_comp->resolutions_size / sizeof(opj_tcd_resolution_t);
1800             for (resno = 0; resno < l_nb_resolutions; ++resno) {
1801                 l_band = l_res->bands;
1802                 for (bandno = 0; bandno < 3; ++bandno) {
1803                     l_precinct = l_band->precincts;
1804                     if (l_precinct) {
1805
1806                         l_nb_precincts = l_band->precincts_data_size / sizeof(opj_tcd_precinct_t);
1807                         for (precno = 0; precno < l_nb_precincts; ++precno) {
1808                             opj_tgt_destroy(l_precinct->incltree);
1809                             l_precinct->incltree = 00;
1810                             opj_tgt_destroy(l_precinct->imsbtree);
1811                             l_precinct->imsbtree = 00;
1812                             (*l_tcd_code_block_deallocate)(l_precinct);
1813                             ++l_precinct;
1814                         }
1815
1816                         opj_free(l_band->precincts);
1817                         l_band->precincts = 00;
1818                     }
1819                     ++l_band;
1820                 } /* for (resno */
1821                 ++l_res;
1822             }
1823
1824             opj_free(l_tile_comp->resolutions);
1825             l_tile_comp->resolutions = 00;
1826         }
1827
1828         if (l_tile_comp->ownsData && l_tile_comp->data) {
1829             opj_image_data_free(l_tile_comp->data);
1830             l_tile_comp->data = 00;
1831             l_tile_comp->ownsData = 0;
1832             l_tile_comp->data_size = 0;
1833             l_tile_comp->data_size_needed = 0;
1834         }
1835
1836         opj_aligned_free(l_tile_comp->data_win);
1837
1838         ++l_tile_comp;
1839     }
1840
1841     opj_free(l_tile->comps);
1842     l_tile->comps = 00;
1843     opj_free(p_tcd->tcd_image->tiles);
1844     p_tcd->tcd_image->tiles = 00;
1845 }
1846
1847
1848 static OPJ_BOOL opj_tcd_t2_decode(opj_tcd_t *p_tcd,
1849                                   OPJ_BYTE * p_src_data,
1850                                   OPJ_UINT32 * p_data_read,
1851                                   OPJ_UINT32 p_max_src_size,
1852                                   opj_codestream_index_t *p_cstr_index,
1853                                   opj_event_mgr_t *p_manager
1854                                  )
1855 {
1856     opj_t2_t * l_t2;
1857
1858     l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
1859     if (l_t2 == 00) {
1860         return OPJ_FALSE;
1861     }
1862
1863     if (! opj_t2_decode_packets(
1864                 p_tcd,
1865                 l_t2,
1866                 p_tcd->tcd_tileno,
1867                 p_tcd->tcd_image->tiles,
1868                 p_src_data,
1869                 p_data_read,
1870                 p_max_src_size,
1871                 p_cstr_index,
1872                 p_manager)) {
1873         opj_t2_destroy(l_t2);
1874         return OPJ_FALSE;
1875     }
1876
1877     opj_t2_destroy(l_t2);
1878
1879     /*---------------CLEAN-------------------*/
1880     return OPJ_TRUE;
1881 }
1882
1883 static OPJ_BOOL opj_tcd_t1_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
1884 {
1885     OPJ_UINT32 compno;
1886     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
1887     opj_tcd_tilecomp_t* l_tile_comp = l_tile->comps;
1888     opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
1889     volatile OPJ_BOOL ret = OPJ_TRUE;
1890     OPJ_BOOL check_pterm = OPJ_FALSE;
1891     opj_mutex_t* p_manager_mutex = NULL;
1892
1893     p_manager_mutex = opj_mutex_create();
1894
1895     /* Only enable PTERM check if we decode all layers */
1896     if (p_tcd->tcp->num_layers_to_decode == p_tcd->tcp->numlayers &&
1897             (l_tccp->cblksty & J2K_CCP_CBLKSTY_PTERM) != 0) {
1898         check_pterm = OPJ_TRUE;
1899     }
1900
1901     for (compno = 0; compno < l_tile->numcomps; ++compno) {
1902         opj_t1_decode_cblks(p_tcd, &ret, l_tile_comp, l_tccp,
1903                             p_manager, p_manager_mutex, check_pterm);
1904         if (!ret) {
1905             break;
1906         }
1907         ++l_tile_comp;
1908         ++l_tccp;
1909     }
1910
1911     opj_thread_pool_wait_completion(p_tcd->thread_pool, 0);
1912     if (p_manager_mutex) {
1913         opj_mutex_destroy(p_manager_mutex);
1914     }
1915     return ret;
1916 }
1917
1918
1919 static OPJ_BOOL opj_tcd_dwt_decode(opj_tcd_t *p_tcd)
1920 {
1921     OPJ_UINT32 compno;
1922     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
1923     opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
1924     opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
1925     opj_image_comp_t * l_img_comp = p_tcd->image->comps;
1926
1927     for (compno = 0; compno < l_tile->numcomps; compno++) {
1928
1929         if (l_tccp->qmfbid == 1) {
1930             if (! opj_dwt_decode(p_tcd, l_tile_comp,
1931                                  l_img_comp->resno_decoded + 1)) {
1932                 return OPJ_FALSE;
1933             }
1934         } else {
1935             if (! opj_dwt_decode_real(p_tcd, l_tile_comp,
1936                                       l_img_comp->resno_decoded + 1)) {
1937                 return OPJ_FALSE;
1938             }
1939         }
1940
1941         ++l_tile_comp;
1942         ++l_img_comp;
1943         ++l_tccp;
1944     }
1945
1946     return OPJ_TRUE;
1947 }
1948
1949 static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
1950 {
1951     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
1952     opj_tcp_t * l_tcp = p_tcd->tcp;
1953     opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
1954     OPJ_UINT32 l_samples, i;
1955
1956     if (! l_tcp->mct) {
1957         return OPJ_TRUE;
1958     }
1959
1960     if (p_tcd->whole_tile_decoding) {
1961         /* A bit inefficient: we process more data than needed if */
1962         /* resno_decoded < l_tile_comp->minimum_num_resolutions-1, */
1963         /* but we would need to take into account a stride then */
1964         l_samples = (OPJ_UINT32)((
1965                                      l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].x1 -
1966                                      l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].x0) *
1967                                  (l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].y1 -
1968                                   l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].y0));
1969     } else {
1970         opj_tcd_resolution_t* l_res;
1971         l_res = l_tile_comp->resolutions + p_tcd->image->comps[0].resno_decoded;
1972         l_samples = (l_res->win_x1 - l_res->win_x0) *
1973                     (l_res->win_y1 - l_res->win_y0);
1974     }
1975
1976     if (l_tile->numcomps >= 3) {
1977         opj_tcd_resolution_t* res_comp0 = l_tile->comps[0].resolutions +
1978                                           p_tcd->image->comps[0].resno_decoded;
1979         opj_tcd_resolution_t* res_comp1 = l_tile->comps[1].resolutions +
1980                                           p_tcd->image->comps[1].resno_decoded;
1981         opj_tcd_resolution_t* res_comp2 = l_tile->comps[2].resolutions +
1982                                           p_tcd->image->comps[2].resno_decoded;
1983         size_t l_res_samples = (size_t)(res_comp0->x1 - res_comp0->x0) *
1984                                (size_t)(res_comp0->y1 - res_comp0->y0);
1985         /* testcase 1336.pdf.asan.47.376 */
1986         if (p_tcd->image->comps[0].resno_decoded !=
1987                 p_tcd->image->comps[1].resno_decoded ||
1988                 p_tcd->image->comps[0].resno_decoded !=
1989                 p_tcd->image->comps[2].resno_decoded ||
1990                 (size_t)(res_comp1->x1 - res_comp1->x0) *
1991                 (size_t)(res_comp1->y1 - res_comp1->y0) != l_res_samples ||
1992                 (size_t)(res_comp2->x1 - res_comp2->x0) *
1993                 (size_t)(res_comp2->y1 - res_comp2->y0) != l_res_samples) {
1994             opj_event_msg(p_manager, EVT_ERROR,
1995                           "Tiles don't all have the same dimension. Skip the MCT step.\n");
1996             return OPJ_FALSE;
1997         } else if (l_tcp->mct == 2) {
1998             OPJ_BYTE ** l_data;
1999
2000             if (! l_tcp->m_mct_decoding_matrix) {
2001                 return OPJ_TRUE;
2002             }
2003
2004             l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*));
2005             if (! l_data) {
2006                 return OPJ_FALSE;
2007             }
2008
2009             for (i = 0; i < l_tile->numcomps; ++i) {
2010                 if (p_tcd->whole_tile_decoding) {
2011                     l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
2012                 } else {
2013                     l_data[i] = (OPJ_BYTE*) l_tile_comp->data_win;
2014                 }
2015                 ++l_tile_comp;
2016             }
2017
2018             if (! opj_mct_decode_custom(/* MCT data */
2019                         (OPJ_BYTE*) l_tcp->m_mct_decoding_matrix,
2020                         /* size of components */
2021                         l_samples,
2022                         /* components */
2023                         l_data,
2024                         /* nb of components (i.e. size of pData) */
2025                         l_tile->numcomps,
2026                         /* tells if the data is signed */
2027                         p_tcd->image->comps->sgnd)) {
2028                 opj_free(l_data);
2029                 return OPJ_FALSE;
2030             }
2031
2032             opj_free(l_data);
2033         } else {
2034             if (l_tcp->tccps->qmfbid == 1) {
2035                 if (p_tcd->whole_tile_decoding) {
2036                     opj_mct_decode(l_tile->comps[0].data,
2037                                    l_tile->comps[1].data,
2038                                    l_tile->comps[2].data,
2039                                    l_samples);
2040                 } else {
2041                     opj_mct_decode(l_tile->comps[0].data_win,
2042                                    l_tile->comps[1].data_win,
2043                                    l_tile->comps[2].data_win,
2044                                    l_samples);
2045                 }
2046             } else {
2047                 if (p_tcd->whole_tile_decoding) {
2048                     opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data,
2049                                         (OPJ_FLOAT32*)l_tile->comps[1].data,
2050                                         (OPJ_FLOAT32*)l_tile->comps[2].data,
2051                                         l_samples);
2052                 } else {
2053                     opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data_win,
2054                                         (OPJ_FLOAT32*)l_tile->comps[1].data_win,
2055                                         (OPJ_FLOAT32*)l_tile->comps[2].data_win,
2056                                         l_samples);
2057                 }
2058             }
2059         }
2060     } else {
2061         opj_event_msg(p_manager, EVT_ERROR,
2062                       "Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n",
2063                       l_tile->numcomps);
2064     }
2065
2066     return OPJ_TRUE;
2067 }
2068
2069
2070 static OPJ_BOOL opj_tcd_dc_level_shift_decode(opj_tcd_t *p_tcd)
2071 {
2072     OPJ_UINT32 compno;
2073     opj_tcd_tilecomp_t * l_tile_comp = 00;
2074     opj_tccp_t * l_tccp = 00;
2075     opj_image_comp_t * l_img_comp = 00;
2076     opj_tcd_resolution_t* l_res = 00;
2077     opj_tcd_tile_t * l_tile;
2078     OPJ_UINT32 l_width, l_height, i, j;
2079     OPJ_INT32 * l_current_ptr;
2080     OPJ_INT32 l_min, l_max;
2081     OPJ_UINT32 l_stride;
2082
2083     l_tile = p_tcd->tcd_image->tiles;
2084     l_tile_comp = l_tile->comps;
2085     l_tccp = p_tcd->tcp->tccps;
2086     l_img_comp = p_tcd->image->comps;
2087
2088     for (compno = 0; compno < l_tile->numcomps; compno++) {
2089         l_res = l_tile_comp->resolutions + l_img_comp->resno_decoded;
2090
2091         if (!p_tcd->whole_tile_decoding) {
2092             l_width = l_res->win_x1 - l_res->win_x0;
2093             l_height = l_res->win_y1 - l_res->win_y0;
2094             l_stride = 0;
2095             l_current_ptr = l_tile_comp->data_win;
2096         } else {
2097             l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0);
2098             l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0);
2099             l_stride = (OPJ_UINT32)(
2100                            l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].x1 -
2101                            l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].x0)
2102                        - l_width;
2103             l_current_ptr = l_tile_comp->data;
2104
2105             assert(l_height == 0 ||
2106                    l_width + l_stride <= l_tile_comp->data_size / l_height); /*MUPDF*/
2107         }
2108
2109         if (l_img_comp->sgnd) {
2110             l_min = -(1 << (l_img_comp->prec - 1));
2111             l_max = (1 << (l_img_comp->prec - 1)) - 1;
2112         } else {
2113             l_min = 0;
2114             l_max = (OPJ_INT32)((1U << l_img_comp->prec) - 1);
2115         }
2116
2117
2118         if (l_tccp->qmfbid == 1) {
2119             for (j = 0; j < l_height; ++j) {
2120                 for (i = 0; i < l_width; ++i) {
2121                     /* TODO: do addition on int64 ? */
2122                     *l_current_ptr = opj_int_clamp(*l_current_ptr + l_tccp->m_dc_level_shift, l_min,
2123                                                    l_max);
2124                     ++l_current_ptr;
2125                 }
2126                 l_current_ptr += l_stride;
2127             }
2128         } else {
2129             for (j = 0; j < l_height; ++j) {
2130                 for (i = 0; i < l_width; ++i) {
2131                     OPJ_FLOAT32 l_value = *((OPJ_FLOAT32 *) l_current_ptr);
2132                     if (l_value > INT_MAX) {
2133                         *l_current_ptr = l_max;
2134                     } else if (l_value < INT_MIN) {
2135                         *l_current_ptr = l_min;
2136                     } else {
2137                         /* Do addition on int64 to avoid overflows */
2138                         OPJ_INT64 l_value_int = (OPJ_INT64)opj_lrintf(l_value);
2139                         *l_current_ptr = (OPJ_INT32)opj_int64_clamp(
2140                                              l_value_int + l_tccp->m_dc_level_shift, l_min, l_max);
2141                     }
2142                     ++l_current_ptr;
2143                 }
2144                 l_current_ptr += l_stride;
2145             }
2146         }
2147
2148         ++l_img_comp;
2149         ++l_tccp;
2150         ++l_tile_comp;
2151     }
2152
2153     return OPJ_TRUE;
2154 }
2155
2156
2157
2158 /**
2159  * Deallocates the encoding data of the given precinct.
2160  */
2161 static void opj_tcd_code_block_dec_deallocate(opj_tcd_precinct_t * p_precinct)
2162 {
2163     OPJ_UINT32 cblkno, l_nb_code_blocks;
2164
2165     opj_tcd_cblk_dec_t * l_code_block = p_precinct->cblks.dec;
2166     if (l_code_block) {
2167         /*fprintf(stderr,"deallocate codeblock:{\n");*/
2168         /*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);*/
2169         /*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ",
2170                         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 );*/
2171
2172
2173         l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_dec_t);
2174         /*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/
2175
2176         for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
2177
2178             if (l_code_block->segs) {
2179                 opj_free(l_code_block->segs);
2180                 l_code_block->segs = 00;
2181             }
2182
2183             if (l_code_block->chunks) {
2184                 opj_free(l_code_block->chunks);
2185                 l_code_block->chunks = 00;
2186             }
2187
2188             opj_aligned_free(l_code_block->decoded_data);
2189             l_code_block->decoded_data = NULL;
2190
2191             ++l_code_block;
2192         }
2193
2194         opj_free(p_precinct->cblks.dec);
2195         p_precinct->cblks.dec = 00;
2196     }
2197 }
2198
2199 /**
2200  * Deallocates the encoding data of the given precinct.
2201  */
2202 static void opj_tcd_code_block_enc_deallocate(opj_tcd_precinct_t * p_precinct)
2203 {
2204     OPJ_UINT32 cblkno, l_nb_code_blocks;
2205
2206     opj_tcd_cblk_enc_t * l_code_block = p_precinct->cblks.enc;
2207     if (l_code_block) {
2208         l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_enc_t);
2209
2210         for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno)  {
2211             if (l_code_block->data) {
2212                 /* We refer to data - 1 since below we incremented it */
2213                 /* in opj_tcd_code_block_enc_allocate_data() */
2214                 opj_free(l_code_block->data - 1);
2215                 l_code_block->data = 00;
2216             }
2217
2218             if (l_code_block->layers) {
2219                 opj_free(l_code_block->layers);
2220                 l_code_block->layers = 00;
2221             }
2222
2223             if (l_code_block->passes) {
2224                 opj_free(l_code_block->passes);
2225                 l_code_block->passes = 00;
2226             }
2227             ++l_code_block;
2228         }
2229
2230         opj_free(p_precinct->cblks.enc);
2231
2232         p_precinct->cblks.enc = 00;
2233     }
2234 }
2235
2236 OPJ_SIZE_T opj_tcd_get_encoded_tile_size(opj_tcd_t *p_tcd)
2237 {
2238     OPJ_UINT32 i;
2239     OPJ_SIZE_T l_data_size = 0;
2240     opj_image_comp_t * l_img_comp = 00;
2241     opj_tcd_tilecomp_t * l_tilec = 00;
2242     OPJ_UINT32 l_size_comp, l_remaining;
2243
2244     l_tilec = p_tcd->tcd_image->tiles->comps;
2245     l_img_comp = p_tcd->image->comps;
2246     for (i = 0; i < p_tcd->image->numcomps; ++i) {
2247         l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
2248         l_remaining = l_img_comp->prec & 7;  /* (%8) */
2249
2250         if (l_remaining) {
2251             ++l_size_comp;
2252         }
2253
2254         if (l_size_comp == 3) {
2255             l_size_comp = 4;
2256         }
2257
2258         l_data_size += l_size_comp * ((OPJ_SIZE_T)(l_tilec->x1 - l_tilec->x0) *
2259                                       (OPJ_SIZE_T)(l_tilec->y1 - l_tilec->y0));
2260         ++l_img_comp;
2261         ++l_tilec;
2262     }
2263
2264     return l_data_size;
2265 }
2266
2267 static OPJ_BOOL opj_tcd_dc_level_shift_encode(opj_tcd_t *p_tcd)
2268 {
2269     OPJ_UINT32 compno;
2270     opj_tcd_tilecomp_t * l_tile_comp = 00;
2271     opj_tccp_t * l_tccp = 00;
2272     opj_image_comp_t * l_img_comp = 00;
2273     opj_tcd_tile_t * l_tile;
2274     size_t l_nb_elem, i;
2275     OPJ_INT32 * l_current_ptr;
2276
2277     l_tile = p_tcd->tcd_image->tiles;
2278     l_tile_comp = l_tile->comps;
2279     l_tccp = p_tcd->tcp->tccps;
2280     l_img_comp = p_tcd->image->comps;
2281
2282     for (compno = 0; compno < l_tile->numcomps; compno++) {
2283         l_current_ptr = l_tile_comp->data;
2284         l_nb_elem = (size_t)(l_tile_comp->x1 - l_tile_comp->x0) *
2285                     (size_t)(l_tile_comp->y1 - l_tile_comp->y0);
2286
2287         if (l_tccp->qmfbid == 1) {
2288             for (i = 0; i < l_nb_elem; ++i) {
2289                 *l_current_ptr -= l_tccp->m_dc_level_shift ;
2290                 ++l_current_ptr;
2291             }
2292         } else {
2293             for (i = 0; i < l_nb_elem; ++i) {
2294                 *l_current_ptr = (*l_current_ptr - l_tccp->m_dc_level_shift) * (1 << 11);
2295                 ++l_current_ptr;
2296             }
2297         }
2298
2299         ++l_img_comp;
2300         ++l_tccp;
2301         ++l_tile_comp;
2302     }
2303
2304     return OPJ_TRUE;
2305 }
2306
2307 static OPJ_BOOL opj_tcd_mct_encode(opj_tcd_t *p_tcd)
2308 {
2309     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
2310     opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
2311     size_t samples = (size_t)(l_tile_comp->x1 - l_tile_comp->x0) *
2312                      (size_t)(l_tile_comp->y1 - l_tile_comp->y0);
2313     OPJ_UINT32 i;
2314     OPJ_BYTE ** l_data = 00;
2315     opj_tcp_t * l_tcp = p_tcd->tcp;
2316
2317     if (!p_tcd->tcp->mct) {
2318         return OPJ_TRUE;
2319     }
2320
2321     if (p_tcd->tcp->mct == 2) {
2322         if (! p_tcd->tcp->m_mct_coding_matrix) {
2323             return OPJ_TRUE;
2324         }
2325
2326         l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*));
2327         if (! l_data) {
2328             return OPJ_FALSE;
2329         }
2330
2331         for (i = 0; i < l_tile->numcomps; ++i) {
2332             l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
2333             ++l_tile_comp;
2334         }
2335
2336         if (! opj_mct_encode_custom(/* MCT data */
2337                     (OPJ_BYTE*) p_tcd->tcp->m_mct_coding_matrix,
2338                     /* size of components */
2339                     samples,
2340                     /* components */
2341                     l_data,
2342                     /* nb of components (i.e. size of pData) */
2343                     l_tile->numcomps,
2344                     /* tells if the data is signed */
2345                     p_tcd->image->comps->sgnd)) {
2346             opj_free(l_data);
2347             return OPJ_FALSE;
2348         }
2349
2350         opj_free(l_data);
2351     } else if (l_tcp->tccps->qmfbid == 0) {
2352         opj_mct_encode_real(l_tile->comps[0].data, l_tile->comps[1].data,
2353                             l_tile->comps[2].data, samples);
2354     } else {
2355         opj_mct_encode(l_tile->comps[0].data, l_tile->comps[1].data,
2356                        l_tile->comps[2].data, samples);
2357     }
2358
2359     return OPJ_TRUE;
2360 }
2361
2362 static OPJ_BOOL opj_tcd_dwt_encode(opj_tcd_t *p_tcd)
2363 {
2364     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
2365     opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
2366     opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
2367     OPJ_UINT32 compno;
2368
2369     for (compno = 0; compno < l_tile->numcomps; ++compno) {
2370         if (l_tccp->qmfbid == 1) {
2371             if (! opj_dwt_encode(l_tile_comp)) {
2372                 return OPJ_FALSE;
2373             }
2374         } else if (l_tccp->qmfbid == 0) {
2375             if (! opj_dwt_encode_real(l_tile_comp)) {
2376                 return OPJ_FALSE;
2377             }
2378         }
2379
2380         ++l_tile_comp;
2381         ++l_tccp;
2382     }
2383
2384     return OPJ_TRUE;
2385 }
2386
2387 static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd)
2388 {
2389     opj_t1_t * l_t1;
2390     const OPJ_FLOAT64 * l_mct_norms;
2391     OPJ_UINT32 l_mct_numcomps = 0U;
2392     opj_tcp_t * l_tcp = p_tcd->tcp;
2393
2394     l_t1 = opj_t1_create(OPJ_TRUE);
2395     if (l_t1 == 00) {
2396         return OPJ_FALSE;
2397     }
2398
2399     if (l_tcp->mct == 1) {
2400         l_mct_numcomps = 3U;
2401         /* irreversible encoding */
2402         if (l_tcp->tccps->qmfbid == 0) {
2403             l_mct_norms = opj_mct_get_mct_norms_real();
2404         } else {
2405             l_mct_norms = opj_mct_get_mct_norms();
2406         }
2407     } else {
2408         l_mct_numcomps = p_tcd->image->numcomps;
2409         l_mct_norms = (const OPJ_FLOAT64 *)(l_tcp->mct_norms);
2410     }
2411
2412     if (! opj_t1_encode_cblks(l_t1, p_tcd->tcd_image->tiles, l_tcp, l_mct_norms,
2413                               l_mct_numcomps)) {
2414         opj_t1_destroy(l_t1);
2415         return OPJ_FALSE;
2416     }
2417
2418     opj_t1_destroy(l_t1);
2419
2420     return OPJ_TRUE;
2421 }
2422
2423 static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd,
2424                                   OPJ_BYTE * p_dest_data,
2425                                   OPJ_UINT32 * p_data_written,
2426                                   OPJ_UINT32 p_max_dest_size,
2427                                   opj_codestream_info_t *p_cstr_info,
2428                                   opj_event_mgr_t *p_manager)
2429 {
2430     opj_t2_t * l_t2;
2431
2432     l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
2433     if (l_t2 == 00) {
2434         return OPJ_FALSE;
2435     }
2436
2437     if (! opj_t2_encode_packets(
2438                 l_t2,
2439                 p_tcd->tcd_tileno,
2440                 p_tcd->tcd_image->tiles,
2441                 p_tcd->tcp->numlayers,
2442                 p_dest_data,
2443                 p_data_written,
2444                 p_max_dest_size,
2445                 p_cstr_info,
2446                 p_tcd->tp_num,
2447                 p_tcd->tp_pos,
2448                 p_tcd->cur_pino,
2449                 FINAL_PASS,
2450                 p_manager)) {
2451         opj_t2_destroy(l_t2);
2452         return OPJ_FALSE;
2453     }
2454
2455     opj_t2_destroy(l_t2);
2456
2457     /*---------------CLEAN-------------------*/
2458     return OPJ_TRUE;
2459 }
2460
2461
2462 static OPJ_BOOL opj_tcd_rate_allocate_encode(opj_tcd_t *p_tcd,
2463         OPJ_BYTE * p_dest_data,
2464         OPJ_UINT32 p_max_dest_size,
2465         opj_codestream_info_t *p_cstr_info,
2466         opj_event_mgr_t *p_manager)
2467 {
2468     opj_cp_t * l_cp = p_tcd->cp;
2469     OPJ_UINT32 l_nb_written = 0;
2470
2471     if (p_cstr_info)  {
2472         p_cstr_info->index_write = 0;
2473     }
2474
2475     if (l_cp->m_specific_param.m_enc.m_disto_alloc ||
2476             l_cp->m_specific_param.m_enc.m_fixed_quality)  {
2477         /* fixed_quality */
2478         /* Normal Rate/distortion allocation */
2479         if (! opj_tcd_rateallocate(p_tcd, p_dest_data, &l_nb_written, p_max_dest_size,
2480                                    p_cstr_info, p_manager)) {
2481             return OPJ_FALSE;
2482         }
2483     } else {
2484         /* Fixed layer allocation */
2485         opj_tcd_rateallocate_fixed(p_tcd);
2486     }
2487
2488     return OPJ_TRUE;
2489 }
2490
2491
2492 OPJ_BOOL opj_tcd_copy_tile_data(opj_tcd_t *p_tcd,
2493                                 OPJ_BYTE * p_src,
2494                                 OPJ_SIZE_T p_src_length)
2495 {
2496     OPJ_UINT32 i;
2497     OPJ_SIZE_T j;
2498     OPJ_SIZE_T l_data_size = 0;
2499     opj_image_comp_t * l_img_comp = 00;
2500     opj_tcd_tilecomp_t * l_tilec = 00;
2501     OPJ_UINT32 l_size_comp, l_remaining;
2502     OPJ_SIZE_T l_nb_elem;
2503
2504     l_data_size = opj_tcd_get_encoded_tile_size(p_tcd);
2505     if (l_data_size != p_src_length) {
2506         return OPJ_FALSE;
2507     }
2508
2509     l_tilec = p_tcd->tcd_image->tiles->comps;
2510     l_img_comp = p_tcd->image->comps;
2511     for (i = 0; i < p_tcd->image->numcomps; ++i) {
2512         l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
2513         l_remaining = l_img_comp->prec & 7;  /* (%8) */
2514         l_nb_elem = (size_t)(l_tilec->x1 - l_tilec->x0) *
2515                     (size_t)(l_tilec->y1 - l_tilec->y0);
2516
2517         if (l_remaining) {
2518             ++l_size_comp;
2519         }
2520
2521         if (l_size_comp == 3) {
2522             l_size_comp = 4;
2523         }
2524
2525         switch (l_size_comp) {
2526         case 1: {
2527             OPJ_CHAR * l_src_ptr = (OPJ_CHAR *) p_src;
2528             OPJ_INT32 * l_dest_ptr = l_tilec->data;
2529
2530             if (l_img_comp->sgnd) {
2531                 for (j = 0; j < l_nb_elem; ++j) {
2532                     *(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
2533                 }
2534             } else {
2535                 for (j = 0; j < l_nb_elem; ++j) {
2536                     *(l_dest_ptr++) = (*(l_src_ptr++)) & 0xff;
2537                 }
2538             }
2539
2540             p_src = (OPJ_BYTE*) l_src_ptr;
2541         }
2542         break;
2543         case 2: {
2544             OPJ_INT32 * l_dest_ptr = l_tilec->data;
2545             OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_src;
2546
2547             if (l_img_comp->sgnd) {
2548                 for (j = 0; j < l_nb_elem; ++j) {
2549                     *(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
2550                 }
2551             } else {
2552                 for (j = 0; j < l_nb_elem; ++j) {
2553                     *(l_dest_ptr++) = (*(l_src_ptr++)) & 0xffff;
2554                 }
2555             }
2556
2557             p_src = (OPJ_BYTE*) l_src_ptr;
2558         }
2559         break;
2560         case 4: {
2561             OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_src;
2562             OPJ_INT32 * l_dest_ptr = l_tilec->data;
2563
2564             for (j = 0; j < l_nb_elem; ++j) {
2565                 *(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
2566             }
2567
2568             p_src = (OPJ_BYTE*) l_src_ptr;
2569         }
2570         break;
2571         }
2572
2573         ++l_img_comp;
2574         ++l_tilec;
2575     }
2576
2577     return OPJ_TRUE;
2578 }
2579
2580 OPJ_BOOL opj_tcd_is_band_empty(opj_tcd_band_t* band)
2581 {
2582     return (band->x1 - band->x0 == 0) || (band->y1 - band->y0 == 0);
2583 }
2584
2585 OPJ_BOOL opj_tcd_is_subband_area_of_interest(opj_tcd_t *tcd,
2586         OPJ_UINT32 compno,
2587         OPJ_UINT32 resno,
2588         OPJ_UINT32 bandno,
2589         OPJ_UINT32 band_x0,
2590         OPJ_UINT32 band_y0,
2591         OPJ_UINT32 band_x1,
2592         OPJ_UINT32 band_y1)
2593 {
2594     /* Note: those values for filter_margin are in part the result of */
2595     /* experimentation. The value 2 for QMFBID=1 (5x3 filter) can be linked */
2596     /* to the maximum left/right extension given in tables F.2 and F.3 of the */
2597     /* standard. The value 3 for QMFBID=0 (9x7 filter) is more suspicious, */
2598     /* since F.2 and F.3 would lead to 4 instead, so the current 3 might be */
2599     /* needed to be bumped to 4, in case inconsistencies are found while */
2600     /* decoding parts of irreversible coded images. */
2601     /* See opj_dwt_decode_partial_53 and opj_dwt_decode_partial_97 as well */
2602     OPJ_UINT32 filter_margin = (tcd->tcp->tccps[compno].qmfbid == 1) ? 2 : 3;
2603     opj_tcd_tilecomp_t *tilec = &(tcd->tcd_image->tiles->comps[compno]);
2604     opj_image_comp_t* image_comp = &(tcd->image->comps[compno]);
2605     /* Compute the intersection of the area of interest, expressed in tile coordinates */
2606     /* with the tile coordinates */
2607     OPJ_UINT32 tcx0 = opj_uint_max(
2608                           (OPJ_UINT32)tilec->x0,
2609                           opj_uint_ceildiv(tcd->win_x0, image_comp->dx));
2610     OPJ_UINT32 tcy0 = opj_uint_max(
2611                           (OPJ_UINT32)tilec->y0,
2612                           opj_uint_ceildiv(tcd->win_y0, image_comp->dy));
2613     OPJ_UINT32 tcx1 = opj_uint_min(
2614                           (OPJ_UINT32)tilec->x1,
2615                           opj_uint_ceildiv(tcd->win_x1, image_comp->dx));
2616     OPJ_UINT32 tcy1 = opj_uint_min(
2617                           (OPJ_UINT32)tilec->y1,
2618                           opj_uint_ceildiv(tcd->win_y1, image_comp->dy));
2619     /* Compute number of decomposition for this band. See table F-1 */
2620     OPJ_UINT32 nb = (resno == 0) ?
2621                     tilec->numresolutions - 1 :
2622                     tilec->numresolutions - resno;
2623     /* Map above tile-based coordinates to sub-band-based coordinates per */
2624     /* equation B-15 of the standard */
2625     OPJ_UINT32 x0b = bandno & 1;
2626     OPJ_UINT32 y0b = bandno >> 1;
2627     OPJ_UINT32 tbx0 = (nb == 0) ? tcx0 :
2628                       (tcx0 <= (1U << (nb - 1)) * x0b) ? 0 :
2629                       opj_uint_ceildivpow2(tcx0 - (1U << (nb - 1)) * x0b, nb);
2630     OPJ_UINT32 tby0 = (nb == 0) ? tcy0 :
2631                       (tcy0 <= (1U << (nb - 1)) * y0b) ? 0 :
2632                       opj_uint_ceildivpow2(tcy0 - (1U << (nb - 1)) * y0b, nb);
2633     OPJ_UINT32 tbx1 = (nb == 0) ? tcx1 :
2634                       (tcx1 <= (1U << (nb - 1)) * x0b) ? 0 :
2635                       opj_uint_ceildivpow2(tcx1 - (1U << (nb - 1)) * x0b, nb);
2636     OPJ_UINT32 tby1 = (nb == 0) ? tcy1 :
2637                       (tcy1 <= (1U << (nb - 1)) * y0b) ? 0 :
2638                       opj_uint_ceildivpow2(tcy1 - (1U << (nb - 1)) * y0b, nb);
2639     OPJ_BOOL intersects;
2640
2641     if (tbx0 < filter_margin) {
2642         tbx0 = 0;
2643     } else {
2644         tbx0 -= filter_margin;
2645     }
2646     if (tby0 < filter_margin) {
2647         tby0 = 0;
2648     } else {
2649         tby0 -= filter_margin;
2650     }
2651     tbx1 = opj_uint_adds(tbx1, filter_margin);
2652     tby1 = opj_uint_adds(tby1, filter_margin);
2653
2654     intersects = band_x0 < tbx1 && band_y0 < tby1 && band_x1 > tbx0 &&
2655                  band_y1 > tby0;
2656
2657 #ifdef DEBUG_VERBOSE
2658     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",
2659            compno, resno, nb, bandno, x0b, y0b,
2660            band_x0, band_y0, band_x1, band_y1,
2661            tbx0, tby0, tbx1, tby1, intersects);
2662 #endif
2663     return intersects;
2664 }
2665
2666 /** Returns whether a tile componenent is fully decoded, taking into account
2667  * p_tcd->win_* members.
2668  *
2669  * @param p_tcd    TCD handle.
2670  * @param compno Component number
2671  * @return OPJ_TRUE whether the tile componenent is fully decoded
2672  */
2673 static OPJ_BOOL opj_tcd_is_whole_tilecomp_decoding(opj_tcd_t *p_tcd,
2674         OPJ_UINT32 compno)
2675 {
2676     opj_tcd_tilecomp_t* tilec = &(p_tcd->tcd_image->tiles->comps[compno]);
2677     opj_image_comp_t* image_comp = &(p_tcd->image->comps[compno]);
2678     /* Compute the intersection of the area of interest, expressed in tile coordinates */
2679     /* with the tile coordinates */
2680     OPJ_UINT32 tcx0 = opj_uint_max(
2681                           (OPJ_UINT32)tilec->x0,
2682                           opj_uint_ceildiv(p_tcd->win_x0, image_comp->dx));
2683     OPJ_UINT32 tcy0 = opj_uint_max(
2684                           (OPJ_UINT32)tilec->y0,
2685                           opj_uint_ceildiv(p_tcd->win_y0, image_comp->dy));
2686     OPJ_UINT32 tcx1 = opj_uint_min(
2687                           (OPJ_UINT32)tilec->x1,
2688                           opj_uint_ceildiv(p_tcd->win_x1, image_comp->dx));
2689     OPJ_UINT32 tcy1 = opj_uint_min(
2690                           (OPJ_UINT32)tilec->y1,
2691                           opj_uint_ceildiv(p_tcd->win_y1, image_comp->dy));
2692
2693     OPJ_UINT32 shift = tilec->numresolutions - tilec->minimum_num_resolutions;
2694     /* Tolerate small margin within the reduced resolution factor to consider if */
2695     /* the whole tile path must be taken */
2696     return (tcx0 >= (OPJ_UINT32)tilec->x0 &&
2697             tcy0 >= (OPJ_UINT32)tilec->y0 &&
2698             tcx1 <= (OPJ_UINT32)tilec->x1 &&
2699             tcy1 <= (OPJ_UINT32)tilec->y1 &&
2700             (shift >= 32 ||
2701              (((tcx0 - (OPJ_UINT32)tilec->x0) >> shift) == 0 &&
2702               ((tcy0 - (OPJ_UINT32)tilec->y0) >> shift) == 0 &&
2703               (((OPJ_UINT32)tilec->x1 - tcx1) >> shift) == 0 &&
2704               (((OPJ_UINT32)tilec->y1 - tcy1) >> shift) == 0)));
2705 }