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