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