opj_tcd_init_tile(): fix typo on overflow detection condition (introduced in previous...
[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             /* compute l_data_size with overflow check */
811             l_data_size = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0);
812             /* issue 733, l_data_size == 0U, probably something wrong should be checked before getting here */
813             if ((l_data_size > 0U) &&
814                     ((((OPJ_UINT32) - 1) / l_data_size) < (OPJ_UINT32)(l_tilec->y1 -
815                             l_tilec->y0))) {
816                 opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
817                 return OPJ_FALSE;
818             }
819             l_data_size = l_data_size * (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0);
820
821             if ((((OPJ_UINT32) - 1) / (OPJ_UINT32)sizeof(OPJ_UINT32)) < l_data_size) {
822                 opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
823                 return OPJ_FALSE;
824             }
825             l_data_size = l_data_size * (OPJ_UINT32)sizeof(OPJ_UINT32);
826
827             l_tilec->data_size_needed = l_data_size;
828         }
829
830         l_data_size = l_tilec->numresolutions * (OPJ_UINT32)sizeof(
831                           opj_tcd_resolution_t);
832
833         opj_aligned_free(l_tilec->data_win);
834         l_tilec->data_win = NULL;
835         l_tilec->win_x0 = 0;
836         l_tilec->win_y0 = 0;
837         l_tilec->win_x1 = 0;
838         l_tilec->win_y1 = 0;
839
840         if (l_tilec->resolutions == 00) {
841             l_tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(l_data_size);
842             if (! l_tilec->resolutions) {
843                 return OPJ_FALSE;
844             }
845             /*fprintf(stderr, "\tAllocate resolutions of tilec (opj_tcd_resolution_t): %d\n",l_data_size);*/
846             l_tilec->resolutions_size = l_data_size;
847             memset(l_tilec->resolutions, 0, l_data_size);
848         } else if (l_data_size > l_tilec->resolutions_size) {
849             opj_tcd_resolution_t* new_resolutions = (opj_tcd_resolution_t *) opj_realloc(
850                     l_tilec->resolutions, l_data_size);
851             if (! new_resolutions) {
852                 opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile resolutions\n");
853                 opj_free(l_tilec->resolutions);
854                 l_tilec->resolutions = NULL;
855                 l_tilec->resolutions_size = 0;
856                 return OPJ_FALSE;
857             }
858             l_tilec->resolutions = new_resolutions;
859             /*fprintf(stderr, "\tReallocate data of tilec (int): from %d to %d x OPJ_UINT32\n", l_tilec->resolutions_size, l_data_size);*/
860             memset(((OPJ_BYTE*) l_tilec->resolutions) + l_tilec->resolutions_size, 0,
861                    l_data_size - l_tilec->resolutions_size);
862             l_tilec->resolutions_size = l_data_size;
863         }
864
865         l_level_no = l_tilec->numresolutions;
866         l_res = l_tilec->resolutions;
867         l_step_size = l_tccp->stepsizes;
868         if (l_tccp->qmfbid == 0) {
869             l_gain_ptr = &opj_dwt_getgain_real;
870         } else {
871             l_gain_ptr  = &opj_dwt_getgain;
872         }
873         /*fprintf(stderr, "\tlevel_no=%d\n",l_level_no);*/
874
875         for (resno = 0; resno < l_tilec->numresolutions; ++resno) {
876             /*fprintf(stderr, "\t\tresno = %d/%d\n", resno, l_tilec->numresolutions);*/
877             OPJ_INT32 tlcbgxstart, tlcbgystart /*, brcbgxend, brcbgyend*/;
878             OPJ_UINT32 cbgwidthexpn, cbgheightexpn;
879             OPJ_UINT32 cblkwidthexpn, cblkheightexpn;
880
881             --l_level_no;
882
883             /* border for each resolution level (global) */
884             l_res->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
885             l_res->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
886             l_res->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
887             l_res->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
888
889             if (!isEncoder && resno + 1 == l_tilec->minimum_num_resolutions) {
890                 /* compute l_data_size with overflow check */
891                 OPJ_UINT32 res_w = (OPJ_UINT32)(l_res->x1 - l_res->x0);
892                 OPJ_UINT32 res_h = (OPJ_UINT32)(l_res->y1 - l_res->y0);
893
894                 /* issue 733, l_data_size == 0U, probably something wrong should be checked before getting here */
895                 if (res_h > 0 && res_w > (((OPJ_UINT32) - 1) / res_h)) {
896                     opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
897                     return OPJ_FALSE;
898                 }
899                 l_data_size = res_w * res_h;
900
901                 if ((((OPJ_UINT32) - 1) / (OPJ_UINT32)sizeof(OPJ_UINT32)) < l_data_size) {
902                     opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
903                     return OPJ_FALSE;
904                 }
905                 l_data_size *= (OPJ_UINT32)sizeof(OPJ_UINT32);
906
907                 l_tilec->data_size_needed = l_data_size;
908             }
909
910             /*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);*/
911             /* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */
912             l_pdx = l_tccp->prcw[resno];
913             l_pdy = l_tccp->prch[resno];
914             /*fprintf(stderr, "\t\t\tpdx=%d, pdy=%d\n", l_pdx, l_pdy);*/
915             /* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000)  */
916             l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx;
917             l_tl_prc_y_start = opj_int_floordivpow2(l_res->y0, (OPJ_INT32)l_pdy) << l_pdy;
918             l_br_prc_x_end = opj_int_ceildivpow2(l_res->x1, (OPJ_INT32)l_pdx) << l_pdx;
919             l_br_prc_y_end = opj_int_ceildivpow2(l_res->y1, (OPJ_INT32)l_pdy) << l_pdy;
920             /*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 );*/
921
922             l_res->pw = (l_res->x0 == l_res->x1) ? 0U : (OPJ_UINT32)((
923                             l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx);
924             l_res->ph = (l_res->y0 == l_res->y1) ? 0U : (OPJ_UINT32)((
925                             l_br_prc_y_end - l_tl_prc_y_start) >> l_pdy);
926             /*fprintf(stderr, "\t\t\tres_pw=%d, res_ph=%d\n", l_res->pw, l_res->ph );*/
927
928             if ((l_res->pw != 0U) && ((((OPJ_UINT32) - 1) / l_res->pw) < l_res->ph)) {
929                 opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
930                 return OPJ_FALSE;
931             }
932             l_nb_precincts = l_res->pw * l_res->ph;
933
934             if ((((OPJ_UINT32) - 1) / (OPJ_UINT32)sizeof(opj_tcd_precinct_t)) <
935                     l_nb_precincts) {
936                 opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
937                 return OPJ_FALSE;
938             }
939             l_nb_precinct_size = l_nb_precincts * (OPJ_UINT32)sizeof(opj_tcd_precinct_t);
940
941             if (resno == 0) {
942                 tlcbgxstart = l_tl_prc_x_start;
943                 tlcbgystart = l_tl_prc_y_start;
944                 /*brcbgxend = l_br_prc_x_end;*/
945                 /* brcbgyend = l_br_prc_y_end;*/
946                 cbgwidthexpn = l_pdx;
947                 cbgheightexpn = l_pdy;
948                 l_res->numbands = 1;
949             } else {
950                 tlcbgxstart = opj_int_ceildivpow2(l_tl_prc_x_start, 1);
951                 tlcbgystart = opj_int_ceildivpow2(l_tl_prc_y_start, 1);
952                 /*brcbgxend = opj_int_ceildivpow2(l_br_prc_x_end, 1);*/
953                 /*brcbgyend = opj_int_ceildivpow2(l_br_prc_y_end, 1);*/
954                 cbgwidthexpn = l_pdx - 1;
955                 cbgheightexpn = l_pdy - 1;
956                 l_res->numbands = 3;
957             }
958
959             cblkwidthexpn = opj_uint_min(l_tccp->cblkw, cbgwidthexpn);
960             cblkheightexpn = opj_uint_min(l_tccp->cblkh, cbgheightexpn);
961             l_band = l_res->bands;
962
963             for (bandno = 0; bandno < l_res->numbands; ++bandno, ++l_band, ++l_step_size) {
964                 OPJ_INT32 numbps;
965                 /*fprintf(stderr, "\t\t\tband_no=%d/%d\n", bandno, l_res->numbands );*/
966
967                 if (resno == 0) {
968                     l_band->bandno = 0 ;
969                     l_band->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
970                     l_band->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
971                     l_band->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
972                     l_band->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
973                 } else {
974                     l_band->bandno = bandno + 1;
975                     /* x0b = 1 if bandno = 1 or 3 */
976                     l_x0b = l_band->bandno & 1;
977                     /* y0b = 1 if bandno = 2 or 3 */
978                     l_y0b = (OPJ_INT32)((l_band->bandno) >> 1);
979                     /* l_band border (global) */
980                     l_band->x0 = opj_int64_ceildivpow2(l_tilec->x0 - ((OPJ_INT64)l_x0b <<
981                                                        l_level_no), (OPJ_INT32)(l_level_no + 1));
982                     l_band->y0 = opj_int64_ceildivpow2(l_tilec->y0 - ((OPJ_INT64)l_y0b <<
983                                                        l_level_no), (OPJ_INT32)(l_level_no + 1));
984                     l_band->x1 = opj_int64_ceildivpow2(l_tilec->x1 - ((OPJ_INT64)l_x0b <<
985                                                        l_level_no), (OPJ_INT32)(l_level_no + 1));
986                     l_band->y1 = opj_int64_ceildivpow2(l_tilec->y1 - ((OPJ_INT64)l_y0b <<
987                                                        l_level_no), (OPJ_INT32)(l_level_no + 1));
988                 }
989
990                 if (isEncoder) {
991                     /* Skip empty bands */
992                     if (opj_tcd_is_band_empty(l_band)) {
993                         /* Do not zero l_band->precints to avoid leaks */
994                         /* but make sure we don't use it later, since */
995                         /* it will point to precincts of previous bands... */
996                         continue;
997                     }
998                 }
999
1000                 /** avoid an if with storing function pointer */
1001                 l_gain = (*l_gain_ptr)(l_band->bandno);
1002                 numbps = (OPJ_INT32)(l_image_comp->prec + l_gain);
1003                 l_band->stepsize = (OPJ_FLOAT32)(((1.0 + l_step_size->mant / 2048.0) * pow(2.0,
1004                                                   (OPJ_INT32)(numbps - l_step_size->expn)))) * fraction;
1005                 /* Mb value of Equation E-2 in "E.1 Inverse quantization
1006                  * procedure" of the standard */
1007                 l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits -
1008                                  1;
1009
1010                 if (!l_band->precincts && (l_nb_precincts > 0U)) {
1011                     l_band->precincts = (opj_tcd_precinct_t *) opj_malloc(/*3 * */
1012                                             l_nb_precinct_size);
1013                     if (! l_band->precincts) {
1014                         opj_event_msg(manager, EVT_ERROR,
1015                                       "Not enough memory to handle band precints\n");
1016                         return OPJ_FALSE;
1017                     }
1018                     /*fprintf(stderr, "\t\t\t\tAllocate precincts of a band (opj_tcd_precinct_t): %d\n",l_nb_precinct_size);     */
1019                     memset(l_band->precincts, 0, l_nb_precinct_size);
1020                     l_band->precincts_data_size = l_nb_precinct_size;
1021                 } else if (l_band->precincts_data_size < l_nb_precinct_size) {
1022
1023                     opj_tcd_precinct_t * new_precincts = (opj_tcd_precinct_t *) opj_realloc(
1024                             l_band->precincts,/*3 * */ l_nb_precinct_size);
1025                     if (! new_precincts) {
1026                         opj_event_msg(manager, EVT_ERROR,
1027                                       "Not enough memory to handle band precints\n");
1028                         opj_free(l_band->precincts);
1029                         l_band->precincts = NULL;
1030                         l_band->precincts_data_size = 0;
1031                         return OPJ_FALSE;
1032                     }
1033                     l_band->precincts = new_precincts;
1034                     /*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);*/
1035                     memset(((OPJ_BYTE *) l_band->precincts) + l_band->precincts_data_size, 0,
1036                            l_nb_precinct_size - l_band->precincts_data_size);
1037                     l_band->precincts_data_size = l_nb_precinct_size;
1038                 }
1039
1040                 l_current_precinct = l_band->precincts;
1041                 for (precno = 0; precno < l_nb_precincts; ++precno) {
1042                     OPJ_INT32 tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend;
1043                     OPJ_INT32 cbgxstart = tlcbgxstart + (OPJ_INT32)(precno % l_res->pw) *
1044                                           (1 << cbgwidthexpn);
1045                     OPJ_INT32 cbgystart = tlcbgystart + (OPJ_INT32)(precno / l_res->pw) *
1046                                           (1 << cbgheightexpn);
1047                     OPJ_INT32 cbgxend = cbgxstart + (1 << cbgwidthexpn);
1048                     OPJ_INT32 cbgyend = cbgystart + (1 << cbgheightexpn);
1049                     /*fprintf(stderr, "\t precno=%d; bandno=%d, resno=%d; compno=%d\n", precno, bandno , resno, compno);*/
1050                     /*fprintf(stderr, "\t tlcbgxstart(=%d) + (precno(=%d) percent res->pw(=%d)) * (1 << cbgwidthexpn(=%d)) \n",tlcbgxstart,precno,l_res->pw,cbgwidthexpn);*/
1051
1052                     /* precinct size (global) */
1053                     /*fprintf(stderr, "\t cbgxstart=%d, l_band->x0 = %d \n",cbgxstart, l_band->x0);*/
1054
1055                     l_current_precinct->x0 = opj_int_max(cbgxstart, l_band->x0);
1056                     l_current_precinct->y0 = opj_int_max(cbgystart, l_band->y0);
1057                     l_current_precinct->x1 = opj_int_min(cbgxend, l_band->x1);
1058                     l_current_precinct->y1 = opj_int_min(cbgyend, l_band->y1);
1059                     /*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);*/
1060
1061                     tlcblkxstart = opj_int_floordivpow2(l_current_precinct->x0,
1062                                                         (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
1063                     /*fprintf(stderr, "\t tlcblkxstart =%d\n",tlcblkxstart );*/
1064                     tlcblkystart = opj_int_floordivpow2(l_current_precinct->y0,
1065                                                         (OPJ_INT32)cblkheightexpn) << cblkheightexpn;
1066                     /*fprintf(stderr, "\t tlcblkystart =%d\n",tlcblkystart );*/
1067                     brcblkxend = opj_int_ceildivpow2(l_current_precinct->x1,
1068                                                      (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
1069                     /*fprintf(stderr, "\t brcblkxend =%d\n",brcblkxend );*/
1070                     brcblkyend = opj_int_ceildivpow2(l_current_precinct->y1,
1071                                                      (OPJ_INT32)cblkheightexpn) << cblkheightexpn;
1072                     /*fprintf(stderr, "\t brcblkyend =%d\n",brcblkyend );*/
1073                     l_current_precinct->cw = (OPJ_UINT32)((brcblkxend - tlcblkxstart) >>
1074                                                           cblkwidthexpn);
1075                     l_current_precinct->ch = (OPJ_UINT32)((brcblkyend - tlcblkystart) >>
1076                                                           cblkheightexpn);
1077
1078                     l_nb_code_blocks = l_current_precinct->cw * l_current_precinct->ch;
1079                     /*fprintf(stderr, "\t\t\t\t precinct_cw = %d x recinct_ch = %d\n",l_current_precinct->cw, l_current_precinct->ch);      */
1080                     l_nb_code_blocks_size = l_nb_code_blocks * (OPJ_UINT32)sizeof_block;
1081
1082                     if (!l_current_precinct->cblks.blocks && (l_nb_code_blocks > 0U)) {
1083                         l_current_precinct->cblks.blocks = opj_malloc(l_nb_code_blocks_size);
1084                         if (! l_current_precinct->cblks.blocks) {
1085                             return OPJ_FALSE;
1086                         }
1087                         /*fprintf(stderr, "\t\t\t\tAllocate cblks of a precinct (opj_tcd_cblk_dec_t): %d\n",l_nb_code_blocks_size);*/
1088
1089                         memset(l_current_precinct->cblks.blocks, 0, l_nb_code_blocks_size);
1090
1091                         l_current_precinct->block_size = l_nb_code_blocks_size;
1092                     } else if (l_nb_code_blocks_size > l_current_precinct->block_size) {
1093                         void *new_blocks = opj_realloc(l_current_precinct->cblks.blocks,
1094                                                        l_nb_code_blocks_size);
1095                         if (! new_blocks) {
1096                             opj_free(l_current_precinct->cblks.blocks);
1097                             l_current_precinct->cblks.blocks = NULL;
1098                             l_current_precinct->block_size = 0;
1099                             opj_event_msg(manager, EVT_ERROR,
1100                                           "Not enough memory for current precinct codeblock element\n");
1101                             return OPJ_FALSE;
1102                         }
1103                         l_current_precinct->cblks.blocks = new_blocks;
1104                         /*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);     */
1105
1106                         memset(((OPJ_BYTE *) l_current_precinct->cblks.blocks) +
1107                                l_current_precinct->block_size
1108                                , 0
1109                                , l_nb_code_blocks_size - l_current_precinct->block_size);
1110
1111                         l_current_precinct->block_size = l_nb_code_blocks_size;
1112                     }
1113
1114                     if (! l_current_precinct->incltree) {
1115                         l_current_precinct->incltree = opj_tgt_create(l_current_precinct->cw,
1116                                                        l_current_precinct->ch, manager);
1117                     } else {
1118                         l_current_precinct->incltree = opj_tgt_init(l_current_precinct->incltree,
1119                                                        l_current_precinct->cw, l_current_precinct->ch, manager);
1120                     }
1121
1122                     if (! l_current_precinct->imsbtree) {
1123                         l_current_precinct->imsbtree = opj_tgt_create(l_current_precinct->cw,
1124                                                        l_current_precinct->ch, manager);
1125                     } else {
1126                         l_current_precinct->imsbtree = opj_tgt_init(l_current_precinct->imsbtree,
1127                                                        l_current_precinct->cw, l_current_precinct->ch, manager);
1128                     }
1129
1130                     for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
1131                         OPJ_INT32 cblkxstart = tlcblkxstart + (OPJ_INT32)(cblkno %
1132                                                l_current_precinct->cw) * (1 << cblkwidthexpn);
1133                         OPJ_INT32 cblkystart = tlcblkystart + (OPJ_INT32)(cblkno /
1134                                                l_current_precinct->cw) * (1 << cblkheightexpn);
1135                         OPJ_INT32 cblkxend = cblkxstart + (1 << cblkwidthexpn);
1136                         OPJ_INT32 cblkyend = cblkystart + (1 << cblkheightexpn);
1137
1138                         if (isEncoder) {
1139                             opj_tcd_cblk_enc_t* l_code_block = l_current_precinct->cblks.enc + cblkno;
1140
1141                             if (! opj_tcd_code_block_enc_allocate(l_code_block)) {
1142                                 return OPJ_FALSE;
1143                             }
1144                             /* code-block size (global) */
1145                             l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
1146                             l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
1147                             l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
1148                             l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
1149
1150                             if (! opj_tcd_code_block_enc_allocate_data(l_code_block)) {
1151                                 return OPJ_FALSE;
1152                             }
1153                         } else {
1154                             opj_tcd_cblk_dec_t* l_code_block = l_current_precinct->cblks.dec + cblkno;
1155
1156                             if (! opj_tcd_code_block_dec_allocate(l_code_block)) {
1157                                 return OPJ_FALSE;
1158                             }
1159                             /* code-block size (global) */
1160                             l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
1161                             l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
1162                             l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
1163                             l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
1164                         }
1165                     }
1166                     ++l_current_precinct;
1167                 } /* precno */
1168             } /* bandno */
1169             ++l_res;
1170         } /* resno */
1171         ++l_tccp;
1172         ++l_tilec;
1173         ++l_image_comp;
1174     } /* compno */
1175     return OPJ_TRUE;
1176 }
1177
1178 OPJ_BOOL opj_tcd_init_encode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
1179                                   opj_event_mgr_t* p_manager)
1180 {
1181     return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_TRUE, 1.0F,
1182                              sizeof(opj_tcd_cblk_enc_t), p_manager);
1183 }
1184
1185 OPJ_BOOL opj_tcd_init_decode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
1186                                   opj_event_mgr_t* p_manager)
1187 {
1188     return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_FALSE, 0.5F,
1189                              sizeof(opj_tcd_cblk_dec_t), p_manager);
1190 }
1191
1192 /**
1193  * Allocates memory for an encoding code block (but not data memory).
1194  */
1195 static OPJ_BOOL opj_tcd_code_block_enc_allocate(opj_tcd_cblk_enc_t *
1196         p_code_block)
1197 {
1198     if (! p_code_block->layers) {
1199         /* no memset since data */
1200         p_code_block->layers = (opj_tcd_layer_t*) opj_calloc(100,
1201                                sizeof(opj_tcd_layer_t));
1202         if (! p_code_block->layers) {
1203             return OPJ_FALSE;
1204         }
1205     }
1206     if (! p_code_block->passes) {
1207         p_code_block->passes = (opj_tcd_pass_t*) opj_calloc(100,
1208                                sizeof(opj_tcd_pass_t));
1209         if (! p_code_block->passes) {
1210             return OPJ_FALSE;
1211         }
1212     }
1213     return OPJ_TRUE;
1214 }
1215
1216 /**
1217  * Allocates data memory for an encoding code block.
1218  */
1219 static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *
1220         p_code_block)
1221 {
1222     OPJ_UINT32 l_data_size;
1223
1224     /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */
1225     /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */
1226     /* TODO: is there a theoretical upper-bound for the compressed code */
1227     /* block size ? */
1228     l_data_size = 2 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *
1229                                    (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));
1230
1231     if (l_data_size > p_code_block->data_size) {
1232         if (p_code_block->data) {
1233             /* We refer to data - 1 since below we incremented it */
1234             opj_free(p_code_block->data - 1);
1235         }
1236         p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);
1237         if (! p_code_block->data) {
1238             p_code_block->data_size = 0U;
1239             return OPJ_FALSE;
1240         }
1241         p_code_block->data_size = l_data_size;
1242
1243         /* We reserve the initial byte as a fake byte to a non-FF value */
1244         /* and increment the data pointer, so that opj_mqc_init_enc() */
1245         /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */
1246         /* it. */
1247         p_code_block->data[0] = 0;
1248         p_code_block->data += 1; /*why +1 ?*/
1249     }
1250     return OPJ_TRUE;
1251 }
1252
1253
1254 void opj_tcd_reinit_segment(opj_tcd_seg_t* seg)
1255 {
1256     memset(seg, 0, sizeof(opj_tcd_seg_t));
1257 }
1258
1259 /**
1260  * Allocates memory for a decoding code block.
1261  */
1262 static OPJ_BOOL opj_tcd_code_block_dec_allocate(opj_tcd_cblk_dec_t *
1263         p_code_block)
1264 {
1265     if (! p_code_block->segs) {
1266
1267         p_code_block->segs = (opj_tcd_seg_t *) opj_calloc(OPJ_J2K_DEFAULT_NB_SEGS,
1268                              sizeof(opj_tcd_seg_t));
1269         if (! p_code_block->segs) {
1270             return OPJ_FALSE;
1271         }
1272         /*fprintf(stderr, "Allocate %d elements of code_block->data\n", OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t));*/
1273
1274         p_code_block->m_current_max_segs = OPJ_J2K_DEFAULT_NB_SEGS;
1275         /*fprintf(stderr, "m_current_max_segs of code_block->data = %d\n", p_code_block->m_current_max_segs);*/
1276     } else {
1277         /* sanitize */
1278         opj_tcd_seg_t * l_segs = p_code_block->segs;
1279         OPJ_UINT32 l_current_max_segs = p_code_block->m_current_max_segs;
1280         opj_tcd_seg_data_chunk_t* l_chunks = p_code_block->chunks;
1281         OPJ_UINT32 l_numchunksalloc = p_code_block->numchunksalloc;
1282         OPJ_UINT32 i;
1283
1284         opj_free(p_code_block->decoded_data);
1285         p_code_block->decoded_data = 00;
1286
1287         memset(p_code_block, 0, sizeof(opj_tcd_cblk_dec_t));
1288         p_code_block->segs = l_segs;
1289         p_code_block->m_current_max_segs = l_current_max_segs;
1290         for (i = 0; i < l_current_max_segs; ++i) {
1291             opj_tcd_reinit_segment(&l_segs[i]);
1292         }
1293         p_code_block->chunks = l_chunks;
1294         p_code_block->numchunksalloc = l_numchunksalloc;
1295     }
1296
1297     return OPJ_TRUE;
1298 }
1299
1300 OPJ_UINT32 opj_tcd_get_decoded_tile_size(opj_tcd_t *p_tcd,
1301         OPJ_BOOL take_into_account_partial_decoding)
1302 {
1303     OPJ_UINT32 i;
1304     OPJ_UINT32 l_data_size = 0;
1305     opj_image_comp_t * l_img_comp = 00;
1306     opj_tcd_tilecomp_t * l_tile_comp = 00;
1307     opj_tcd_resolution_t * l_res = 00;
1308     OPJ_UINT32 l_size_comp, l_remaining;
1309     OPJ_UINT32 l_temp;
1310
1311     l_tile_comp = p_tcd->tcd_image->tiles->comps;
1312     l_img_comp = p_tcd->image->comps;
1313
1314     for (i = 0; i < p_tcd->image->numcomps; ++i) {
1315         l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
1316         l_remaining = l_img_comp->prec & 7;  /* (%8) */
1317
1318         if (l_remaining) {
1319             ++l_size_comp;
1320         }
1321
1322         if (l_size_comp == 3) {
1323             l_size_comp = 4;
1324         }
1325
1326         l_res = l_tile_comp->resolutions + l_tile_comp->minimum_num_resolutions - 1;
1327         if (take_into_account_partial_decoding && !p_tcd->whole_tile_decoding) {
1328             l_temp = (l_res->win_x1 - l_res->win_x0) *
1329                      (l_res->win_y1 - l_res->win_y0);
1330         } else {
1331             l_temp = (OPJ_UINT32)((l_res->x1 - l_res->x0) * (l_res->y1 -
1332                                   l_res->y0)); /* x1*y1 can't overflow */
1333         }
1334         if (l_size_comp && UINT_MAX / l_size_comp < l_temp) {
1335             return UINT_MAX;
1336         }
1337         l_temp *= l_size_comp;
1338
1339         if (l_temp > UINT_MAX - l_data_size) {
1340             return UINT_MAX;
1341         }
1342         l_data_size += l_temp;
1343         ++l_img_comp;
1344         ++l_tile_comp;
1345     }
1346
1347     return l_data_size;
1348 }
1349
1350 OPJ_BOOL opj_tcd_encode_tile(opj_tcd_t *p_tcd,
1351                              OPJ_UINT32 p_tile_no,
1352                              OPJ_BYTE *p_dest,
1353                              OPJ_UINT32 * p_data_written,
1354                              OPJ_UINT32 p_max_length,
1355                              opj_codestream_info_t *p_cstr_info,
1356                              opj_event_mgr_t *p_manager)
1357 {
1358
1359     if (p_tcd->cur_tp_num == 0) {
1360
1361         p_tcd->tcd_tileno = p_tile_no;
1362         p_tcd->tcp = &p_tcd->cp->tcps[p_tile_no];
1363
1364         /* INDEX >> "Precinct_nb_X et Precinct_nb_Y" */
1365         if (p_cstr_info)  {
1366             OPJ_UINT32 l_num_packs = 0;
1367             OPJ_UINT32 i;
1368             opj_tcd_tilecomp_t *l_tilec_idx =
1369                 &p_tcd->tcd_image->tiles->comps[0];        /* based on component 0 */
1370             opj_tccp_t *l_tccp = p_tcd->tcp->tccps; /* based on component 0 */
1371
1372             for (i = 0; i < l_tilec_idx->numresolutions; i++) {
1373                 opj_tcd_resolution_t *l_res_idx = &l_tilec_idx->resolutions[i];
1374
1375                 p_cstr_info->tile[p_tile_no].pw[i] = (int)l_res_idx->pw;
1376                 p_cstr_info->tile[p_tile_no].ph[i] = (int)l_res_idx->ph;
1377
1378                 l_num_packs += l_res_idx->pw * l_res_idx->ph;
1379                 p_cstr_info->tile[p_tile_no].pdx[i] = (int)l_tccp->prcw[i];
1380                 p_cstr_info->tile[p_tile_no].pdy[i] = (int)l_tccp->prch[i];
1381             }
1382             p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t*) opj_calloc((
1383                     size_t)p_cstr_info->numcomps * (size_t)p_cstr_info->numlayers * l_num_packs,
1384                                                   sizeof(opj_packet_info_t));
1385             if (!p_cstr_info->tile[p_tile_no].packet) {
1386                 /* FIXME event manager error callback */
1387                 return OPJ_FALSE;
1388             }
1389         }
1390         /* << INDEX */
1391
1392         /* FIXME _ProfStart(PGROUP_DC_SHIFT); */
1393         /*---------------TILE-------------------*/
1394         if (! opj_tcd_dc_level_shift_encode(p_tcd)) {
1395             return OPJ_FALSE;
1396         }
1397         /* FIXME _ProfStop(PGROUP_DC_SHIFT); */
1398
1399         /* FIXME _ProfStart(PGROUP_MCT); */
1400         if (! opj_tcd_mct_encode(p_tcd)) {
1401             return OPJ_FALSE;
1402         }
1403         /* FIXME _ProfStop(PGROUP_MCT); */
1404
1405         /* FIXME _ProfStart(PGROUP_DWT); */
1406         if (! opj_tcd_dwt_encode(p_tcd)) {
1407             return OPJ_FALSE;
1408         }
1409         /* FIXME  _ProfStop(PGROUP_DWT); */
1410
1411         /* FIXME  _ProfStart(PGROUP_T1); */
1412         if (! opj_tcd_t1_encode(p_tcd)) {
1413             return OPJ_FALSE;
1414         }
1415         /* FIXME _ProfStop(PGROUP_T1); */
1416
1417         /* FIXME _ProfStart(PGROUP_RATE); */
1418         if (! opj_tcd_rate_allocate_encode(p_tcd, p_dest, p_max_length,
1419                                            p_cstr_info, p_manager)) {
1420             return OPJ_FALSE;
1421         }
1422         /* FIXME _ProfStop(PGROUP_RATE); */
1423
1424     }
1425     /*--------------TIER2------------------*/
1426
1427     /* INDEX */
1428     if (p_cstr_info) {
1429         p_cstr_info->index_write = 1;
1430     }
1431     /* FIXME _ProfStart(PGROUP_T2); */
1432
1433     if (! opj_tcd_t2_encode(p_tcd, p_dest, p_data_written, p_max_length,
1434                             p_cstr_info, p_manager)) {
1435         return OPJ_FALSE;
1436     }
1437     /* FIXME _ProfStop(PGROUP_T2); */
1438
1439     /*---------------CLEAN-------------------*/
1440
1441     return OPJ_TRUE;
1442 }
1443
1444 OPJ_BOOL opj_tcd_decode_tile(opj_tcd_t *p_tcd,
1445                              OPJ_UINT32 win_x0,
1446                              OPJ_UINT32 win_y0,
1447                              OPJ_UINT32 win_x1,
1448                              OPJ_UINT32 win_y1,
1449                              OPJ_BYTE *p_src,
1450                              OPJ_UINT32 p_max_length,
1451                              OPJ_UINT32 p_tile_no,
1452                              opj_codestream_index_t *p_cstr_index,
1453                              opj_event_mgr_t *p_manager
1454                             )
1455 {
1456     OPJ_UINT32 l_data_read;
1457     OPJ_UINT32 compno;
1458
1459     p_tcd->tcd_tileno = p_tile_no;
1460     p_tcd->tcp = &(p_tcd->cp->tcps[p_tile_no]);
1461     p_tcd->win_x0 = win_x0;
1462     p_tcd->win_y0 = win_y0;
1463     p_tcd->win_x1 = win_x1;
1464     p_tcd->win_y1 = win_y1;
1465     p_tcd->whole_tile_decoding = OPJ_TRUE;
1466
1467     for (compno = 0; compno < p_tcd->image->numcomps; compno++) {
1468         if (!opj_tcd_is_whole_tilecomp_decoding(p_tcd, compno)) {
1469             p_tcd->whole_tile_decoding = OPJ_FALSE;
1470             break;
1471         }
1472     }
1473
1474     if (p_tcd->whole_tile_decoding) {
1475         for (compno = 0; compno < p_tcd->image->numcomps; compno++) {
1476             if (!opj_alloc_tile_component_data(&(p_tcd->tcd_image->tiles->comps[compno]))) {
1477                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for tile data\n");
1478                 return OPJ_FALSE;
1479             }
1480         }
1481     } else {
1482         /* Compute restricted tile-component and tile-resolution coordinates */
1483         /* of the window of interest, but defer the memory allocation until */
1484         /* we know the resno_decoded */
1485         for (compno = 0; compno < p_tcd->image->numcomps; compno++) {
1486             OPJ_UINT32 resno;
1487             opj_tcd_tilecomp_t* tilec = &(p_tcd->tcd_image->tiles->comps[compno]);
1488             opj_image_comp_t* image_comp = &(p_tcd->image->comps[compno]);
1489             /* Compute the intersection of the area of interest, expressed in tile coordinates */
1490             /* with the tile coordinates */
1491             tilec->win_x0 = opj_uint_max(
1492                                 (OPJ_UINT32)tilec->x0,
1493                                 opj_uint_ceildiv(p_tcd->win_x0, image_comp->dx));
1494             tilec->win_y0 = opj_uint_max(
1495                                 (OPJ_UINT32)tilec->y0,
1496                                 opj_uint_ceildiv(p_tcd->win_y0, image_comp->dy));
1497             tilec->win_x1 = opj_uint_min(
1498                                 (OPJ_UINT32)tilec->x1,
1499                                 opj_uint_ceildiv(p_tcd->win_x1, image_comp->dx));
1500             tilec->win_y1 = opj_uint_min(
1501                                 (OPJ_UINT32)tilec->y1,
1502                                 opj_uint_ceildiv(p_tcd->win_y1, image_comp->dy));
1503
1504             for (resno = 0; resno < tilec->numresolutions; ++resno) {
1505                 opj_tcd_resolution_t *res = tilec->resolutions + resno;
1506                 res->win_x0 = opj_uint_ceildivpow2(tilec->win_x0,
1507                                                    tilec->numresolutions - 1 - resno);
1508                 res->win_y0 = opj_uint_ceildivpow2(tilec->win_y0,
1509                                                    tilec->numresolutions - 1 - resno);
1510                 res->win_x1 = opj_uint_ceildivpow2(tilec->win_x1,
1511                                                    tilec->numresolutions - 1 - resno);
1512                 res->win_y1 = opj_uint_ceildivpow2(tilec->win_y1,
1513                                                    tilec->numresolutions - 1 - resno);
1514             }
1515         }
1516     }
1517
1518 #ifdef TODO_MSD /* FIXME */
1519     /* INDEX >>  */
1520     if (p_cstr_info) {
1521         OPJ_UINT32 resno, compno, numprec = 0;
1522         for (compno = 0; compno < (OPJ_UINT32) p_cstr_info->numcomps; compno++) {
1523             opj_tcp_t *tcp = &p_tcd->cp->tcps[0];
1524             opj_tccp_t *tccp = &tcp->tccps[compno];
1525             opj_tcd_tilecomp_t *tilec_idx = &p_tcd->tcd_image->tiles->comps[compno];
1526             for (resno = 0; resno < tilec_idx->numresolutions; resno++) {
1527                 opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[resno];
1528                 p_cstr_info->tile[p_tile_no].pw[resno] = res_idx->pw;
1529                 p_cstr_info->tile[p_tile_no].ph[resno] = res_idx->ph;
1530                 numprec += res_idx->pw * res_idx->ph;
1531                 p_cstr_info->tile[p_tile_no].pdx[resno] = tccp->prcw[resno];
1532                 p_cstr_info->tile[p_tile_no].pdy[resno] = tccp->prch[resno];
1533             }
1534         }
1535         p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t *) opj_malloc(
1536                 p_cstr_info->numlayers * numprec * sizeof(opj_packet_info_t));
1537         p_cstr_info->packno = 0;
1538     }
1539     /* << INDEX */
1540 #endif
1541
1542     /*--------------TIER2------------------*/
1543     /* FIXME _ProfStart(PGROUP_T2); */
1544     l_data_read = 0;
1545     if (! opj_tcd_t2_decode(p_tcd, p_src, &l_data_read, p_max_length, p_cstr_index,
1546                             p_manager)) {
1547         return OPJ_FALSE;
1548     }
1549     /* FIXME _ProfStop(PGROUP_T2); */
1550
1551     /*------------------TIER1-----------------*/
1552
1553     /* FIXME _ProfStart(PGROUP_T1); */
1554     if (! opj_tcd_t1_decode(p_tcd, p_manager)) {
1555         return OPJ_FALSE;
1556     }
1557     /* FIXME _ProfStop(PGROUP_T1); */
1558
1559
1560     /* For subtile decoding, now we know the resno_decoded, we can allocate */
1561     /* the tile data buffer */
1562     if (!p_tcd->whole_tile_decoding) {
1563         for (compno = 0; compno < p_tcd->image->numcomps; compno++) {
1564             opj_tcd_tilecomp_t* tilec = &(p_tcd->tcd_image->tiles->comps[compno]);
1565             opj_image_comp_t* image_comp = &(p_tcd->image->comps[compno]);
1566             opj_tcd_resolution_t *res = tilec->resolutions + image_comp->resno_decoded;
1567             OPJ_UINT32 w = res->win_x1 - res->win_x0;
1568             OPJ_UINT32 h = res->win_y1 - res->win_y0;
1569             OPJ_UINT32 l_data_size;
1570
1571             opj_aligned_free(tilec->data_win);
1572             tilec->data_win = NULL;
1573
1574             if (w > 0 && h > 0) {
1575                 if (w > ((OPJ_UINT32) - 1) / h) {
1576                     opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for tile data\n");
1577                     return OPJ_FALSE;
1578                 }
1579                 l_data_size = w * h;
1580                 if (l_data_size > ((OPJ_UINT32) - 1) / sizeof(OPJ_INT32)) {
1581                     opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for tile data\n");
1582                     return OPJ_FALSE;
1583                 }
1584                 l_data_size *= (OPJ_UINT32)sizeof(OPJ_INT32);
1585
1586                 tilec->data_win = opj_aligned_malloc(l_data_size);
1587                 if (tilec->data_win == NULL) {
1588                     opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for tile data\n");
1589                     return OPJ_FALSE;
1590                 }
1591             }
1592         }
1593     }
1594
1595     /*----------------DWT---------------------*/
1596
1597     /* FIXME _ProfStart(PGROUP_DWT); */
1598     if
1599     (! opj_tcd_dwt_decode(p_tcd)) {
1600         return OPJ_FALSE;
1601     }
1602     /* FIXME _ProfStop(PGROUP_DWT); */
1603
1604     /*----------------MCT-------------------*/
1605     /* FIXME _ProfStart(PGROUP_MCT); */
1606     if
1607     (! opj_tcd_mct_decode(p_tcd, p_manager)) {
1608         return OPJ_FALSE;
1609     }
1610     /* FIXME _ProfStop(PGROUP_MCT); */
1611
1612     /* FIXME _ProfStart(PGROUP_DC_SHIFT); */
1613     if
1614     (! opj_tcd_dc_level_shift_decode(p_tcd)) {
1615         return OPJ_FALSE;
1616     }
1617     /* FIXME _ProfStop(PGROUP_DC_SHIFT); */
1618
1619
1620     /*---------------TILE-------------------*/
1621     return OPJ_TRUE;
1622 }
1623
1624 OPJ_BOOL opj_tcd_update_tile_data(opj_tcd_t *p_tcd,
1625                                   OPJ_BYTE * p_dest,
1626                                   OPJ_UINT32 p_dest_length
1627                                  )
1628 {
1629     OPJ_UINT32 i, j, k, l_data_size = 0;
1630     opj_image_comp_t * l_img_comp = 00;
1631     opj_tcd_tilecomp_t * l_tilec = 00;
1632     opj_tcd_resolution_t * l_res;
1633     OPJ_UINT32 l_size_comp, l_remaining;
1634     OPJ_UINT32 l_stride, l_width, l_height;
1635
1636     l_data_size = opj_tcd_get_decoded_tile_size(p_tcd, OPJ_TRUE);
1637     if (l_data_size == UINT_MAX || l_data_size > p_dest_length) {
1638         return OPJ_FALSE;
1639     }
1640
1641     l_tilec = p_tcd->tcd_image->tiles->comps;
1642     l_img_comp = p_tcd->image->comps;
1643
1644     for (i = 0; i < p_tcd->image->numcomps; ++i) {
1645         const OPJ_INT32* l_src_data;
1646         l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
1647         l_remaining = l_img_comp->prec & 7;  /* (%8) */
1648         l_res = l_tilec->resolutions + l_img_comp->resno_decoded;
1649         if (p_tcd->whole_tile_decoding) {
1650             l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0);
1651             l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0);
1652             l_stride = (OPJ_UINT32)(l_tilec->resolutions[l_tilec->minimum_num_resolutions -
1653                                                                      1].x1 -
1654                                     l_tilec->resolutions[l_tilec->minimum_num_resolutions - 1].x0) - l_width;
1655             l_src_data = l_tilec->data;
1656         } else {
1657             l_width = l_res->win_x1 - l_res->win_x0;
1658             l_height = l_res->win_y1 - l_res->win_y0;
1659             l_stride = 0;
1660             l_src_data = l_tilec->data_win;
1661         }
1662
1663         if (l_remaining) {
1664             ++l_size_comp;
1665         }
1666
1667         if (l_size_comp == 3) {
1668             l_size_comp = 4;
1669         }
1670
1671         switch (l_size_comp) {
1672         case 1: {
1673             OPJ_CHAR * l_dest_ptr = (OPJ_CHAR *) p_dest;
1674             const OPJ_INT32 * l_src_ptr = l_src_data;
1675
1676             if (l_img_comp->sgnd) {
1677                 for (j = 0; j < l_height; ++j) {
1678                     for (k = 0; k < l_width; ++k) {
1679                         *(l_dest_ptr++) = (OPJ_CHAR)(*(l_src_ptr++));
1680                     }
1681                     l_src_ptr += l_stride;
1682                 }
1683             } else {
1684                 for (j = 0; j < l_height; ++j) {
1685                     for (k = 0; k < l_width; ++k) {
1686                         *(l_dest_ptr++) = (OPJ_CHAR)((*(l_src_ptr++)) & 0xff);
1687                     }
1688                     l_src_ptr += l_stride;
1689                 }
1690             }
1691
1692             p_dest = (OPJ_BYTE *)l_dest_ptr;
1693         }
1694         break;
1695         case 2: {
1696             const OPJ_INT32 * l_src_ptr = l_src_data;
1697             OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_dest;
1698
1699             if (l_img_comp->sgnd) {
1700                 for (j = 0; j < l_height; ++j) {
1701                     for (k = 0; k < l_width; ++k) {
1702                         OPJ_INT16 val = (OPJ_INT16)(*(l_src_ptr++));
1703                         memcpy(l_dest_ptr, &val, sizeof(val));
1704                         l_dest_ptr ++;
1705                     }
1706                     l_src_ptr += l_stride;
1707                 }
1708             } else {
1709                 for (j = 0; j < l_height; ++j) {
1710                     for (k = 0; k < l_width; ++k) {
1711                         OPJ_INT16 val = (OPJ_INT16)((*(l_src_ptr++)) & 0xffff);
1712                         memcpy(l_dest_ptr, &val, sizeof(val));
1713                         l_dest_ptr ++;
1714                     }
1715                     l_src_ptr += l_stride;
1716                 }
1717             }
1718
1719             p_dest = (OPJ_BYTE*) l_dest_ptr;
1720         }
1721         break;
1722         case 4: {
1723             OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_dest;
1724             const OPJ_INT32 * l_src_ptr = l_src_data;
1725
1726             for (j = 0; j < l_height; ++j) {
1727                 memcpy(l_dest_ptr, l_src_ptr, l_width * sizeof(OPJ_INT32));
1728                 l_dest_ptr += l_width;
1729                 l_src_ptr += l_width + l_stride;
1730             }
1731
1732             p_dest = (OPJ_BYTE*) l_dest_ptr;
1733         }
1734         break;
1735         }
1736
1737         ++l_img_comp;
1738         ++l_tilec;
1739     }
1740
1741     return OPJ_TRUE;
1742 }
1743
1744
1745
1746
1747 static void opj_tcd_free_tile(opj_tcd_t *p_tcd)
1748 {
1749     OPJ_UINT32 compno, resno, bandno, precno;
1750     opj_tcd_tile_t *l_tile = 00;
1751     opj_tcd_tilecomp_t *l_tile_comp = 00;
1752     opj_tcd_resolution_t *l_res = 00;
1753     opj_tcd_band_t *l_band = 00;
1754     opj_tcd_precinct_t *l_precinct = 00;
1755     OPJ_UINT32 l_nb_resolutions, l_nb_precincts;
1756     void (* l_tcd_code_block_deallocate)(opj_tcd_precinct_t *) = 00;
1757
1758     if (! p_tcd) {
1759         return;
1760     }
1761
1762     if (! p_tcd->tcd_image) {
1763         return;
1764     }
1765
1766     if (p_tcd->m_is_decoder) {
1767         l_tcd_code_block_deallocate = opj_tcd_code_block_dec_deallocate;
1768     } else {
1769         l_tcd_code_block_deallocate = opj_tcd_code_block_enc_deallocate;
1770     }
1771
1772     l_tile = p_tcd->tcd_image->tiles;
1773     if (! l_tile) {
1774         return;
1775     }
1776
1777     l_tile_comp = l_tile->comps;
1778
1779     for (compno = 0; compno < l_tile->numcomps; ++compno) {
1780         l_res = l_tile_comp->resolutions;
1781         if (l_res) {
1782
1783             l_nb_resolutions = l_tile_comp->resolutions_size / sizeof(opj_tcd_resolution_t);
1784             for (resno = 0; resno < l_nb_resolutions; ++resno) {
1785                 l_band = l_res->bands;
1786                 for (bandno = 0; bandno < 3; ++bandno) {
1787                     l_precinct = l_band->precincts;
1788                     if (l_precinct) {
1789
1790                         l_nb_precincts = l_band->precincts_data_size / sizeof(opj_tcd_precinct_t);
1791                         for (precno = 0; precno < l_nb_precincts; ++precno) {
1792                             opj_tgt_destroy(l_precinct->incltree);
1793                             l_precinct->incltree = 00;
1794                             opj_tgt_destroy(l_precinct->imsbtree);
1795                             l_precinct->imsbtree = 00;
1796                             (*l_tcd_code_block_deallocate)(l_precinct);
1797                             ++l_precinct;
1798                         }
1799
1800                         opj_free(l_band->precincts);
1801                         l_band->precincts = 00;
1802                     }
1803                     ++l_band;
1804                 } /* for (resno */
1805                 ++l_res;
1806             }
1807
1808             opj_free(l_tile_comp->resolutions);
1809             l_tile_comp->resolutions = 00;
1810         }
1811
1812         if (l_tile_comp->ownsData && l_tile_comp->data) {
1813             opj_image_data_free(l_tile_comp->data);
1814             l_tile_comp->data = 00;
1815             l_tile_comp->ownsData = 0;
1816             l_tile_comp->data_size = 0;
1817             l_tile_comp->data_size_needed = 0;
1818         }
1819
1820         opj_aligned_free(l_tile_comp->data_win);
1821
1822         ++l_tile_comp;
1823     }
1824
1825     opj_free(l_tile->comps);
1826     l_tile->comps = 00;
1827     opj_free(p_tcd->tcd_image->tiles);
1828     p_tcd->tcd_image->tiles = 00;
1829 }
1830
1831
1832 static OPJ_BOOL opj_tcd_t2_decode(opj_tcd_t *p_tcd,
1833                                   OPJ_BYTE * p_src_data,
1834                                   OPJ_UINT32 * p_data_read,
1835                                   OPJ_UINT32 p_max_src_size,
1836                                   opj_codestream_index_t *p_cstr_index,
1837                                   opj_event_mgr_t *p_manager
1838                                  )
1839 {
1840     opj_t2_t * l_t2;
1841
1842     l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
1843     if (l_t2 == 00) {
1844         return OPJ_FALSE;
1845     }
1846
1847     if (! opj_t2_decode_packets(
1848                 p_tcd,
1849                 l_t2,
1850                 p_tcd->tcd_tileno,
1851                 p_tcd->tcd_image->tiles,
1852                 p_src_data,
1853                 p_data_read,
1854                 p_max_src_size,
1855                 p_cstr_index,
1856                 p_manager)) {
1857         opj_t2_destroy(l_t2);
1858         return OPJ_FALSE;
1859     }
1860
1861     opj_t2_destroy(l_t2);
1862
1863     /*---------------CLEAN-------------------*/
1864     return OPJ_TRUE;
1865 }
1866
1867 static OPJ_BOOL opj_tcd_t1_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
1868 {
1869     OPJ_UINT32 compno;
1870     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
1871     opj_tcd_tilecomp_t* l_tile_comp = l_tile->comps;
1872     opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
1873     volatile OPJ_BOOL ret = OPJ_TRUE;
1874     OPJ_BOOL check_pterm = OPJ_FALSE;
1875     opj_mutex_t* p_manager_mutex = NULL;
1876
1877     p_manager_mutex = opj_mutex_create();
1878
1879     /* Only enable PTERM check if we decode all layers */
1880     if (p_tcd->tcp->num_layers_to_decode == p_tcd->tcp->numlayers &&
1881             (l_tccp->cblksty & J2K_CCP_CBLKSTY_PTERM) != 0) {
1882         check_pterm = OPJ_TRUE;
1883     }
1884
1885     for (compno = 0; compno < l_tile->numcomps; ++compno) {
1886         opj_t1_decode_cblks(p_tcd, &ret, l_tile_comp, l_tccp,
1887                             p_manager, p_manager_mutex, check_pterm);
1888         if (!ret) {
1889             break;
1890         }
1891         ++l_tile_comp;
1892         ++l_tccp;
1893     }
1894
1895     opj_thread_pool_wait_completion(p_tcd->thread_pool, 0);
1896     if (p_manager_mutex) {
1897         opj_mutex_destroy(p_manager_mutex);
1898     }
1899     return ret;
1900 }
1901
1902
1903 static OPJ_BOOL opj_tcd_dwt_decode(opj_tcd_t *p_tcd)
1904 {
1905     OPJ_UINT32 compno;
1906     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
1907     opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
1908     opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
1909     opj_image_comp_t * l_img_comp = p_tcd->image->comps;
1910
1911     for (compno = 0; compno < l_tile->numcomps; compno++) {
1912
1913         if (l_tccp->qmfbid == 1) {
1914             if (! opj_dwt_decode(p_tcd, l_tile_comp,
1915                                  l_img_comp->resno_decoded + 1)) {
1916                 return OPJ_FALSE;
1917             }
1918         } else {
1919             if (! opj_dwt_decode_real(p_tcd, l_tile_comp,
1920                                       l_img_comp->resno_decoded + 1)) {
1921                 return OPJ_FALSE;
1922             }
1923         }
1924
1925         ++l_tile_comp;
1926         ++l_img_comp;
1927         ++l_tccp;
1928     }
1929
1930     return OPJ_TRUE;
1931 }
1932
1933 static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
1934 {
1935     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
1936     opj_tcp_t * l_tcp = p_tcd->tcp;
1937     opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
1938     OPJ_UINT32 l_samples, i;
1939
1940     if (! l_tcp->mct) {
1941         return OPJ_TRUE;
1942     }
1943
1944     if (p_tcd->whole_tile_decoding) {
1945         /* A bit inefficient: we process more data than needed if */
1946         /* resno_decoded < l_tile_comp->minimum_num_resolutions-1, */
1947         /* but we would need to take into account a stride then */
1948         l_samples = (OPJ_UINT32)((
1949                                      l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].x1 -
1950                                      l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].x0) *
1951                                  (l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].y1 -
1952                                   l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].y0));
1953     } else {
1954         opj_tcd_resolution_t* l_res;
1955         l_res = l_tile_comp->resolutions + p_tcd->image->comps[0].resno_decoded;
1956         l_samples = (l_res->win_x1 - l_res->win_x0) *
1957                     (l_res->win_y1 - l_res->win_y0);
1958     }
1959
1960     if (l_tile->numcomps >= 3) {
1961         opj_tcd_resolution_t* res_comp0 = l_tile->comps[0].resolutions +
1962                                           p_tcd->image->comps[0].resno_decoded;
1963         opj_tcd_resolution_t* res_comp1 = l_tile->comps[1].resolutions +
1964                                           p_tcd->image->comps[1].resno_decoded;
1965         opj_tcd_resolution_t* res_comp2 = l_tile->comps[2].resolutions +
1966                                           p_tcd->image->comps[2].resno_decoded;
1967         OPJ_INT32 l_res_samples = (OPJ_INT32)(res_comp0->x1 - res_comp0->x0) *
1968                                   (res_comp0->y1 - res_comp0->y0);
1969         /* testcase 1336.pdf.asan.47.376 */
1970         if (p_tcd->image->comps[0].resno_decoded !=
1971                 p_tcd->image->comps[1].resno_decoded ||
1972                 p_tcd->image->comps[0].resno_decoded !=
1973                 p_tcd->image->comps[2].resno_decoded ||
1974                 (res_comp1->x1 - res_comp1->x0) * (res_comp1->y1 -
1975                         res_comp1->y0) != l_res_samples ||
1976                 (res_comp2->x1 - res_comp2->x0) * (res_comp2->y1 -
1977                         res_comp2->y0) != l_res_samples) {
1978             opj_event_msg(p_manager, EVT_ERROR,
1979                           "Tiles don't all have the same dimension. Skip the MCT step.\n");
1980             return OPJ_FALSE;
1981         } else if (l_tcp->mct == 2) {
1982             OPJ_BYTE ** l_data;
1983
1984             if (! l_tcp->m_mct_decoding_matrix) {
1985                 return OPJ_TRUE;
1986             }
1987
1988             l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*));
1989             if (! l_data) {
1990                 return OPJ_FALSE;
1991             }
1992
1993             for (i = 0; i < l_tile->numcomps; ++i) {
1994                 if (p_tcd->whole_tile_decoding) {
1995                     l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
1996                 } else {
1997                     l_data[i] = (OPJ_BYTE*) l_tile_comp->data_win;
1998                 }
1999                 ++l_tile_comp;
2000             }
2001
2002             if (! opj_mct_decode_custom(/* MCT data */
2003                         (OPJ_BYTE*) l_tcp->m_mct_decoding_matrix,
2004                         /* size of components */
2005                         l_samples,
2006                         /* components */
2007                         l_data,
2008                         /* nb of components (i.e. size of pData) */
2009                         l_tile->numcomps,
2010                         /* tells if the data is signed */
2011                         p_tcd->image->comps->sgnd)) {
2012                 opj_free(l_data);
2013                 return OPJ_FALSE;
2014             }
2015
2016             opj_free(l_data);
2017         } else {
2018             if (l_tcp->tccps->qmfbid == 1) {
2019                 if (p_tcd->whole_tile_decoding) {
2020                     opj_mct_decode(l_tile->comps[0].data,
2021                                    l_tile->comps[1].data,
2022                                    l_tile->comps[2].data,
2023                                    l_samples);
2024                 } else {
2025                     opj_mct_decode(l_tile->comps[0].data_win,
2026                                    l_tile->comps[1].data_win,
2027                                    l_tile->comps[2].data_win,
2028                                    l_samples);
2029                 }
2030             } else {
2031                 if (p_tcd->whole_tile_decoding) {
2032                     opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data,
2033                                         (OPJ_FLOAT32*)l_tile->comps[1].data,
2034                                         (OPJ_FLOAT32*)l_tile->comps[2].data,
2035                                         l_samples);
2036                 } else {
2037                     opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data_win,
2038                                         (OPJ_FLOAT32*)l_tile->comps[1].data_win,
2039                                         (OPJ_FLOAT32*)l_tile->comps[2].data_win,
2040                                         l_samples);
2041                 }
2042             }
2043         }
2044     } else {
2045         opj_event_msg(p_manager, EVT_ERROR,
2046                       "Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n",
2047                       l_tile->numcomps);
2048     }
2049
2050     return OPJ_TRUE;
2051 }
2052
2053
2054 static OPJ_BOOL opj_tcd_dc_level_shift_decode(opj_tcd_t *p_tcd)
2055 {
2056     OPJ_UINT32 compno;
2057     opj_tcd_tilecomp_t * l_tile_comp = 00;
2058     opj_tccp_t * l_tccp = 00;
2059     opj_image_comp_t * l_img_comp = 00;
2060     opj_tcd_resolution_t* l_res = 00;
2061     opj_tcd_tile_t * l_tile;
2062     OPJ_UINT32 l_width, l_height, i, j;
2063     OPJ_INT32 * l_current_ptr;
2064     OPJ_INT32 l_min, l_max;
2065     OPJ_UINT32 l_stride;
2066
2067     l_tile = p_tcd->tcd_image->tiles;
2068     l_tile_comp = l_tile->comps;
2069     l_tccp = p_tcd->tcp->tccps;
2070     l_img_comp = p_tcd->image->comps;
2071
2072     for (compno = 0; compno < l_tile->numcomps; compno++) {
2073         l_res = l_tile_comp->resolutions + l_img_comp->resno_decoded;
2074
2075         if (!p_tcd->whole_tile_decoding) {
2076             l_width = l_res->win_x1 - l_res->win_x0;
2077             l_height = l_res->win_y1 - l_res->win_y0;
2078             l_stride = 0;
2079             l_current_ptr = l_tile_comp->data_win;
2080         } else {
2081             l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0);
2082             l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0);
2083             l_stride = (OPJ_UINT32)(
2084                            l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].x1 -
2085                            l_tile_comp->resolutions[l_tile_comp->minimum_num_resolutions - 1].x0)
2086                        - l_width;
2087             l_current_ptr = l_tile_comp->data;
2088
2089             assert(l_height == 0 ||
2090                    l_width + l_stride <= l_tile_comp->data_size / l_height); /*MUPDF*/
2091         }
2092
2093         if (l_img_comp->sgnd) {
2094             l_min = -(1 << (l_img_comp->prec - 1));
2095             l_max = (1 << (l_img_comp->prec - 1)) - 1;
2096         } else {
2097             l_min = 0;
2098             l_max = (OPJ_INT32)((1U << l_img_comp->prec) - 1);
2099         }
2100
2101
2102         if (l_tccp->qmfbid == 1) {
2103             for (j = 0; j < l_height; ++j) {
2104                 for (i = 0; i < l_width; ++i) {
2105                     *l_current_ptr = opj_int_clamp(*l_current_ptr + l_tccp->m_dc_level_shift, l_min,
2106                                                    l_max);
2107                     ++l_current_ptr;
2108                 }
2109                 l_current_ptr += l_stride;
2110             }
2111         } else {
2112             for (j = 0; j < l_height; ++j) {
2113                 for (i = 0; i < l_width; ++i) {
2114                     OPJ_FLOAT32 l_value = *((OPJ_FLOAT32 *) l_current_ptr);
2115                     OPJ_INT32 l_value_int = (OPJ_INT32)opj_lrintf(l_value);
2116                     if (l_value > INT_MAX ||
2117                             (l_value_int > 0 && l_tccp->m_dc_level_shift > 0 &&
2118                              l_value_int > INT_MAX - l_tccp->m_dc_level_shift)) {
2119                         *l_current_ptr = l_max;
2120                     } else {
2121                         *l_current_ptr = opj_int_clamp(
2122                                              l_value_int + l_tccp->m_dc_level_shift, l_min, l_max);
2123                     }
2124                     ++l_current_ptr;
2125                 }
2126                 l_current_ptr += l_stride;
2127             }
2128         }
2129
2130         ++l_img_comp;
2131         ++l_tccp;
2132         ++l_tile_comp;
2133     }
2134
2135     return OPJ_TRUE;
2136 }
2137
2138
2139
2140 /**
2141  * Deallocates the encoding data of the given precinct.
2142  */
2143 static void opj_tcd_code_block_dec_deallocate(opj_tcd_precinct_t * p_precinct)
2144 {
2145     OPJ_UINT32 cblkno, l_nb_code_blocks;
2146
2147     opj_tcd_cblk_dec_t * l_code_block = p_precinct->cblks.dec;
2148     if (l_code_block) {
2149         /*fprintf(stderr,"deallocate codeblock:{\n");*/
2150         /*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);*/
2151         /*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ",
2152                         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 );*/
2153
2154
2155         l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_dec_t);
2156         /*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/
2157
2158         for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
2159
2160             if (l_code_block->segs) {
2161                 opj_free(l_code_block->segs);
2162                 l_code_block->segs = 00;
2163             }
2164
2165             if (l_code_block->chunks) {
2166                 opj_free(l_code_block->chunks);
2167                 l_code_block->chunks = 00;
2168             }
2169
2170             opj_free(l_code_block->decoded_data);
2171             l_code_block->decoded_data = NULL;
2172
2173             ++l_code_block;
2174         }
2175
2176         opj_free(p_precinct->cblks.dec);
2177         p_precinct->cblks.dec = 00;
2178     }
2179 }
2180
2181 /**
2182  * Deallocates the encoding data of the given precinct.
2183  */
2184 static void opj_tcd_code_block_enc_deallocate(opj_tcd_precinct_t * p_precinct)
2185 {
2186     OPJ_UINT32 cblkno, l_nb_code_blocks;
2187
2188     opj_tcd_cblk_enc_t * l_code_block = p_precinct->cblks.enc;
2189     if (l_code_block) {
2190         l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_enc_t);
2191
2192         for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno)  {
2193             if (l_code_block->data) {
2194                 /* We refer to data - 1 since below we incremented it */
2195                 /* in opj_tcd_code_block_enc_allocate_data() */
2196                 opj_free(l_code_block->data - 1);
2197                 l_code_block->data = 00;
2198             }
2199
2200             if (l_code_block->layers) {
2201                 opj_free(l_code_block->layers);
2202                 l_code_block->layers = 00;
2203             }
2204
2205             if (l_code_block->passes) {
2206                 opj_free(l_code_block->passes);
2207                 l_code_block->passes = 00;
2208             }
2209             ++l_code_block;
2210         }
2211
2212         opj_free(p_precinct->cblks.enc);
2213
2214         p_precinct->cblks.enc = 00;
2215     }
2216 }
2217
2218 OPJ_UINT32 opj_tcd_get_encoded_tile_size(opj_tcd_t *p_tcd)
2219 {
2220     OPJ_UINT32 i, l_data_size = 0;
2221     opj_image_comp_t * l_img_comp = 00;
2222     opj_tcd_tilecomp_t * l_tilec = 00;
2223     OPJ_UINT32 l_size_comp, l_remaining;
2224
2225     l_tilec = p_tcd->tcd_image->tiles->comps;
2226     l_img_comp = p_tcd->image->comps;
2227     for (i = 0; i < p_tcd->image->numcomps; ++i) {
2228         l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
2229         l_remaining = l_img_comp->prec & 7;  /* (%8) */
2230
2231         if (l_remaining) {
2232             ++l_size_comp;
2233         }
2234
2235         if (l_size_comp == 3) {
2236             l_size_comp = 4;
2237         }
2238
2239         l_data_size += l_size_comp * (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) *
2240                        (l_tilec->y1 - l_tilec->y0));
2241         ++l_img_comp;
2242         ++l_tilec;
2243     }
2244
2245     return l_data_size;
2246 }
2247
2248 static OPJ_BOOL opj_tcd_dc_level_shift_encode(opj_tcd_t *p_tcd)
2249 {
2250     OPJ_UINT32 compno;
2251     opj_tcd_tilecomp_t * l_tile_comp = 00;
2252     opj_tccp_t * l_tccp = 00;
2253     opj_image_comp_t * l_img_comp = 00;
2254     opj_tcd_tile_t * l_tile;
2255     OPJ_UINT32 l_nb_elem, i;
2256     OPJ_INT32 * l_current_ptr;
2257
2258     l_tile = p_tcd->tcd_image->tiles;
2259     l_tile_comp = l_tile->comps;
2260     l_tccp = p_tcd->tcp->tccps;
2261     l_img_comp = p_tcd->image->comps;
2262
2263     for (compno = 0; compno < l_tile->numcomps; compno++) {
2264         l_current_ptr = l_tile_comp->data;
2265         l_nb_elem = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) *
2266                                  (l_tile_comp->y1 - l_tile_comp->y0));
2267
2268         if (l_tccp->qmfbid == 1) {
2269             for (i = 0; i < l_nb_elem; ++i) {
2270                 *l_current_ptr -= l_tccp->m_dc_level_shift ;
2271                 ++l_current_ptr;
2272             }
2273         } else {
2274             for (i = 0; i < l_nb_elem; ++i) {
2275                 *l_current_ptr = (*l_current_ptr - l_tccp->m_dc_level_shift) * (1 << 11);
2276                 ++l_current_ptr;
2277             }
2278         }
2279
2280         ++l_img_comp;
2281         ++l_tccp;
2282         ++l_tile_comp;
2283     }
2284
2285     return OPJ_TRUE;
2286 }
2287
2288 static OPJ_BOOL opj_tcd_mct_encode(opj_tcd_t *p_tcd)
2289 {
2290     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
2291     opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
2292     OPJ_UINT32 samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) *
2293                                       (l_tile_comp->y1 - l_tile_comp->y0));
2294     OPJ_UINT32 i;
2295     OPJ_BYTE ** l_data = 00;
2296     opj_tcp_t * l_tcp = p_tcd->tcp;
2297
2298     if (!p_tcd->tcp->mct) {
2299         return OPJ_TRUE;
2300     }
2301
2302     if (p_tcd->tcp->mct == 2) {
2303         if (! p_tcd->tcp->m_mct_coding_matrix) {
2304             return OPJ_TRUE;
2305         }
2306
2307         l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*));
2308         if (! l_data) {
2309             return OPJ_FALSE;
2310         }
2311
2312         for (i = 0; i < l_tile->numcomps; ++i) {
2313             l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
2314             ++l_tile_comp;
2315         }
2316
2317         if (! opj_mct_encode_custom(/* MCT data */
2318                     (OPJ_BYTE*) p_tcd->tcp->m_mct_coding_matrix,
2319                     /* size of components */
2320                     samples,
2321                     /* components */
2322                     l_data,
2323                     /* nb of components (i.e. size of pData) */
2324                     l_tile->numcomps,
2325                     /* tells if the data is signed */
2326                     p_tcd->image->comps->sgnd)) {
2327             opj_free(l_data);
2328             return OPJ_FALSE;
2329         }
2330
2331         opj_free(l_data);
2332     } else if (l_tcp->tccps->qmfbid == 0) {
2333         opj_mct_encode_real(l_tile->comps[0].data, l_tile->comps[1].data,
2334                             l_tile->comps[2].data, samples);
2335     } else {
2336         opj_mct_encode(l_tile->comps[0].data, l_tile->comps[1].data,
2337                        l_tile->comps[2].data, samples);
2338     }
2339
2340     return OPJ_TRUE;
2341 }
2342
2343 static OPJ_BOOL opj_tcd_dwt_encode(opj_tcd_t *p_tcd)
2344 {
2345     opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
2346     opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
2347     opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
2348     OPJ_UINT32 compno;
2349
2350     for (compno = 0; compno < l_tile->numcomps; ++compno) {
2351         if (l_tccp->qmfbid == 1) {
2352             if (! opj_dwt_encode(l_tile_comp)) {
2353                 return OPJ_FALSE;
2354             }
2355         } else if (l_tccp->qmfbid == 0) {
2356             if (! opj_dwt_encode_real(l_tile_comp)) {
2357                 return OPJ_FALSE;
2358             }
2359         }
2360
2361         ++l_tile_comp;
2362         ++l_tccp;
2363     }
2364
2365     return OPJ_TRUE;
2366 }
2367
2368 static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd)
2369 {
2370     opj_t1_t * l_t1;
2371     const OPJ_FLOAT64 * l_mct_norms;
2372     OPJ_UINT32 l_mct_numcomps = 0U;
2373     opj_tcp_t * l_tcp = p_tcd->tcp;
2374
2375     l_t1 = opj_t1_create(OPJ_TRUE);
2376     if (l_t1 == 00) {
2377         return OPJ_FALSE;
2378     }
2379
2380     if (l_tcp->mct == 1) {
2381         l_mct_numcomps = 3U;
2382         /* irreversible encoding */
2383         if (l_tcp->tccps->qmfbid == 0) {
2384             l_mct_norms = opj_mct_get_mct_norms_real();
2385         } else {
2386             l_mct_norms = opj_mct_get_mct_norms();
2387         }
2388     } else {
2389         l_mct_numcomps = p_tcd->image->numcomps;
2390         l_mct_norms = (const OPJ_FLOAT64 *)(l_tcp->mct_norms);
2391     }
2392
2393     if (! opj_t1_encode_cblks(l_t1, p_tcd->tcd_image->tiles, l_tcp, l_mct_norms,
2394                               l_mct_numcomps)) {
2395         opj_t1_destroy(l_t1);
2396         return OPJ_FALSE;
2397     }
2398
2399     opj_t1_destroy(l_t1);
2400
2401     return OPJ_TRUE;
2402 }
2403
2404 static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd,
2405                                   OPJ_BYTE * p_dest_data,
2406                                   OPJ_UINT32 * p_data_written,
2407                                   OPJ_UINT32 p_max_dest_size,
2408                                   opj_codestream_info_t *p_cstr_info,
2409                                   opj_event_mgr_t *p_manager)
2410 {
2411     opj_t2_t * l_t2;
2412
2413     l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
2414     if (l_t2 == 00) {
2415         return OPJ_FALSE;
2416     }
2417
2418     if (! opj_t2_encode_packets(
2419                 l_t2,
2420                 p_tcd->tcd_tileno,
2421                 p_tcd->tcd_image->tiles,
2422                 p_tcd->tcp->numlayers,
2423                 p_dest_data,
2424                 p_data_written,
2425                 p_max_dest_size,
2426                 p_cstr_info,
2427                 p_tcd->tp_num,
2428                 p_tcd->tp_pos,
2429                 p_tcd->cur_pino,
2430                 FINAL_PASS,
2431                 p_manager)) {
2432         opj_t2_destroy(l_t2);
2433         return OPJ_FALSE;
2434     }
2435
2436     opj_t2_destroy(l_t2);
2437
2438     /*---------------CLEAN-------------------*/
2439     return OPJ_TRUE;
2440 }
2441
2442
2443 static OPJ_BOOL opj_tcd_rate_allocate_encode(opj_tcd_t *p_tcd,
2444         OPJ_BYTE * p_dest_data,
2445         OPJ_UINT32 p_max_dest_size,
2446         opj_codestream_info_t *p_cstr_info,
2447         opj_event_mgr_t *p_manager)
2448 {
2449     opj_cp_t * l_cp = p_tcd->cp;
2450     OPJ_UINT32 l_nb_written = 0;
2451
2452     if (p_cstr_info)  {
2453         p_cstr_info->index_write = 0;
2454     }
2455
2456     if (l_cp->m_specific_param.m_enc.m_disto_alloc ||
2457             l_cp->m_specific_param.m_enc.m_fixed_quality)  {
2458         /* fixed_quality */
2459         /* Normal Rate/distortion allocation */
2460         if (! opj_tcd_rateallocate(p_tcd, p_dest_data, &l_nb_written, p_max_dest_size,
2461                                    p_cstr_info, p_manager)) {
2462             return OPJ_FALSE;
2463         }
2464     } else {
2465         /* Fixed layer allocation */
2466         opj_tcd_rateallocate_fixed(p_tcd);
2467     }
2468
2469     return OPJ_TRUE;
2470 }
2471
2472
2473 OPJ_BOOL opj_tcd_copy_tile_data(opj_tcd_t *p_tcd,
2474                                 OPJ_BYTE * p_src,
2475                                 OPJ_UINT32 p_src_length)
2476 {
2477     OPJ_UINT32 i, j, l_data_size = 0;
2478     opj_image_comp_t * l_img_comp = 00;
2479     opj_tcd_tilecomp_t * l_tilec = 00;
2480     OPJ_UINT32 l_size_comp, l_remaining;
2481     OPJ_UINT32 l_nb_elem;
2482
2483     l_data_size = opj_tcd_get_encoded_tile_size(p_tcd);
2484     if (l_data_size != p_src_length) {
2485         return OPJ_FALSE;
2486     }
2487
2488     l_tilec = p_tcd->tcd_image->tiles->comps;
2489     l_img_comp = p_tcd->image->comps;
2490     for (i = 0; i < p_tcd->image->numcomps; ++i) {
2491         l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
2492         l_remaining = l_img_comp->prec & 7;  /* (%8) */
2493         l_nb_elem = (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 -
2494                                  l_tilec->y0));
2495
2496         if (l_remaining) {
2497             ++l_size_comp;
2498         }
2499
2500         if (l_size_comp == 3) {
2501             l_size_comp = 4;
2502         }
2503
2504         switch (l_size_comp) {
2505         case 1: {
2506             OPJ_CHAR * l_src_ptr = (OPJ_CHAR *) p_src;
2507             OPJ_INT32 * l_dest_ptr = l_tilec->data;
2508
2509             if (l_img_comp->sgnd) {
2510                 for (j = 0; j < l_nb_elem; ++j) {
2511                     *(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
2512                 }
2513             } else {
2514                 for (j = 0; j < l_nb_elem; ++j) {
2515                     *(l_dest_ptr++) = (*(l_src_ptr++)) & 0xff;
2516                 }
2517             }
2518
2519             p_src = (OPJ_BYTE*) l_src_ptr;
2520         }
2521         break;
2522         case 2: {
2523             OPJ_INT32 * l_dest_ptr = l_tilec->data;
2524             OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_src;
2525
2526             if (l_img_comp->sgnd) {
2527                 for (j = 0; j < l_nb_elem; ++j) {
2528                     *(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
2529                 }
2530             } else {
2531                 for (j = 0; j < l_nb_elem; ++j) {
2532                     *(l_dest_ptr++) = (*(l_src_ptr++)) & 0xffff;
2533                 }
2534             }
2535
2536             p_src = (OPJ_BYTE*) l_src_ptr;
2537         }
2538         break;
2539         case 4: {
2540             OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_src;
2541             OPJ_INT32 * l_dest_ptr = l_tilec->data;
2542
2543             for (j = 0; j < l_nb_elem; ++j) {
2544                 *(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
2545             }
2546
2547             p_src = (OPJ_BYTE*) l_src_ptr;
2548         }
2549         break;
2550         }
2551
2552         ++l_img_comp;
2553         ++l_tilec;
2554     }
2555
2556     return OPJ_TRUE;
2557 }
2558
2559 OPJ_BOOL opj_tcd_is_band_empty(opj_tcd_band_t* band)
2560 {
2561     return (band->x1 - band->x0 == 0) || (band->y1 - band->y0 == 0);
2562 }
2563
2564 OPJ_BOOL opj_tcd_is_subband_area_of_interest(opj_tcd_t *tcd,
2565         OPJ_UINT32 compno,
2566         OPJ_UINT32 resno,
2567         OPJ_UINT32 bandno,
2568         OPJ_UINT32 band_x0,
2569         OPJ_UINT32 band_y0,
2570         OPJ_UINT32 band_x1,
2571         OPJ_UINT32 band_y1)
2572 {
2573     /* Note: those values for filter_margin are in part the result of */
2574     /* experimentation. The value 2 for QMFBID=1 (5x3 filter) can be linked */
2575     /* to the maximum left/right extension given in tables F.2 and F.3 of the */
2576     /* standard. The value 3 for QMFBID=0 (9x7 filter) is more suspicious, */
2577     /* since F.2 and F.3 would lead to 4 instead, so the current 3 might be */
2578     /* needed to be bumped to 4, in case inconsistencies are found while */
2579     /* decoding parts of irreversible coded images. */
2580     /* See opj_dwt_decode_partial_53 and opj_dwt_decode_partial_97 as well */
2581     OPJ_UINT32 filter_margin = (tcd->tcp->tccps[compno].qmfbid == 1) ? 2 : 3;
2582     opj_tcd_tilecomp_t *tilec = &(tcd->tcd_image->tiles->comps[compno]);
2583     opj_image_comp_t* image_comp = &(tcd->image->comps[compno]);
2584     /* Compute the intersection of the area of interest, expressed in tile coordinates */
2585     /* with the tile coordinates */
2586     OPJ_UINT32 tcx0 = opj_uint_max(
2587                           (OPJ_UINT32)tilec->x0,
2588                           opj_uint_ceildiv(tcd->win_x0, image_comp->dx));
2589     OPJ_UINT32 tcy0 = opj_uint_max(
2590                           (OPJ_UINT32)tilec->y0,
2591                           opj_uint_ceildiv(tcd->win_y0, image_comp->dy));
2592     OPJ_UINT32 tcx1 = opj_uint_min(
2593                           (OPJ_UINT32)tilec->x1,
2594                           opj_uint_ceildiv(tcd->win_x1, image_comp->dx));
2595     OPJ_UINT32 tcy1 = opj_uint_min(
2596                           (OPJ_UINT32)tilec->y1,
2597                           opj_uint_ceildiv(tcd->win_y1, image_comp->dy));
2598     /* Compute number of decomposition for this band. See table F-1 */
2599     OPJ_UINT32 nb = (resno == 0) ?
2600                     tilec->numresolutions - 1 :
2601                     tilec->numresolutions - resno;
2602     /* Map above tile-based coordinates to sub-band-based coordinates per */
2603     /* equation B-15 of the standard */
2604     OPJ_UINT32 x0b = bandno & 1;
2605     OPJ_UINT32 y0b = bandno >> 1;
2606     OPJ_UINT32 tbx0 = (nb == 0) ? tcx0 :
2607                       (tcx0 <= (1U << (nb - 1)) * x0b) ? 0 :
2608                       opj_uint_ceildivpow2(tcx0 - (1U << (nb - 1)) * x0b, nb);
2609     OPJ_UINT32 tby0 = (nb == 0) ? tcy0 :
2610                       (tcy0 <= (1U << (nb - 1)) * y0b) ? 0 :
2611                       opj_uint_ceildivpow2(tcy0 - (1U << (nb - 1)) * y0b, nb);
2612     OPJ_UINT32 tbx1 = (nb == 0) ? tcx1 :
2613                       (tcx1 <= (1U << (nb - 1)) * x0b) ? 0 :
2614                       opj_uint_ceildivpow2(tcx1 - (1U << (nb - 1)) * x0b, nb);
2615     OPJ_UINT32 tby1 = (nb == 0) ? tcy1 :
2616                       (tcy1 <= (1U << (nb - 1)) * y0b) ? 0 :
2617                       opj_uint_ceildivpow2(tcy1 - (1U << (nb - 1)) * y0b, nb);
2618     OPJ_BOOL intersects;
2619
2620     if (tbx0 < filter_margin) {
2621         tbx0 = 0;
2622     } else {
2623         tbx0 -= filter_margin;
2624     }
2625     if (tby0 < filter_margin) {
2626         tby0 = 0;
2627     } else {
2628         tby0 -= filter_margin;
2629     }
2630     tbx1 = opj_uint_adds(tbx1, filter_margin);
2631     tby1 = opj_uint_adds(tby1, filter_margin);
2632
2633     intersects = band_x0 < tbx1 && band_y0 < tby1 && band_x1 > tbx0 &&
2634                  band_y1 > tby0;
2635
2636 #ifdef DEBUG_VERBOSE
2637     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",
2638            compno, resno, nb, bandno, x0b, y0b,
2639            band_x0, band_y0, band_x1, band_y1,
2640            tbx0, tby0, tbx1, tby1, intersects);
2641 #endif
2642     return intersects;
2643 }
2644
2645 /** Returns whether a tile componenent is fully decoded, taking into account
2646  * p_tcd->win_* members.
2647  *
2648  * @param p_tcd    TCD handle.
2649  * @param compno Component number
2650  * @return OPJ_TRUE whether the tile componenent is fully decoded
2651  */
2652 static OPJ_BOOL opj_tcd_is_whole_tilecomp_decoding(opj_tcd_t *p_tcd,
2653         OPJ_UINT32 compno)
2654 {
2655     opj_tcd_tilecomp_t* tilec = &(p_tcd->tcd_image->tiles->comps[compno]);
2656     opj_image_comp_t* image_comp = &(p_tcd->image->comps[compno]);
2657     /* Compute the intersection of the area of interest, expressed in tile coordinates */
2658     /* with the tile coordinates */
2659     OPJ_UINT32 tcx0 = opj_uint_max(
2660                           (OPJ_UINT32)tilec->x0,
2661                           opj_uint_ceildiv(p_tcd->win_x0, image_comp->dx));
2662     OPJ_UINT32 tcy0 = opj_uint_max(
2663                           (OPJ_UINT32)tilec->y0,
2664                           opj_uint_ceildiv(p_tcd->win_y0, image_comp->dy));
2665     OPJ_UINT32 tcx1 = opj_uint_min(
2666                           (OPJ_UINT32)tilec->x1,
2667                           opj_uint_ceildiv(p_tcd->win_x1, image_comp->dx));
2668     OPJ_UINT32 tcy1 = opj_uint_min(
2669                           (OPJ_UINT32)tilec->y1,
2670                           opj_uint_ceildiv(p_tcd->win_y1, image_comp->dy));
2671
2672     OPJ_UINT32 shift = tilec->numresolutions - tilec->minimum_num_resolutions;
2673     /* Tolerate small margin within the reduced resolution factor to consider if */
2674     /* the whole tile path must be taken */
2675     return (tcx0 >= (OPJ_UINT32)tilec->x0 &&
2676             tcy0 >= (OPJ_UINT32)tilec->y0 &&
2677             tcx1 <= (OPJ_UINT32)tilec->x1 &&
2678             tcy1 <= (OPJ_UINT32)tilec->y1 &&
2679             (shift >= 32 ||
2680              (((tcx0 - (OPJ_UINT32)tilec->x0) >> shift) == 0 &&
2681               ((tcy0 - (OPJ_UINT32)tilec->y0) >> shift) == 0 &&
2682               (((OPJ_UINT32)tilec->x1 - tcx1) >> shift) == 0 &&
2683               (((OPJ_UINT32)tilec->y1 - tcy1) >> shift) == 0)));
2684 }