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