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