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