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