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