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