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