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