Fix null pointer dereference on partial tile decoding when they are empty. Fixes...
[openjpeg.git] / src / lib / openjp2 / dwt.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) 2007, Jonathan Ballard <dzonatas@dzonux.net>
15  * Copyright (c) 2007, Callum Lerwick <seg@haxxed.com>
16  * Copyright (c) 2017, IntoPIX SA <support@intopix.com>
17  * All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
29  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
32  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  */
40
41 #include <assert.h>
42
43 #define OPJ_SKIP_POISON
44 #include "opj_includes.h"
45
46 #ifdef __SSE__
47 #include <xmmintrin.h>
48 #endif
49 #ifdef __SSE2__
50 #include <emmintrin.h>
51 #endif
52 #ifdef __SSSE3__
53 #include <tmmintrin.h>
54 #endif
55 #ifdef __AVX2__
56 #include <immintrin.h>
57 #endif
58
59 #if defined(__GNUC__)
60 #pragma GCC poison malloc calloc realloc free
61 #endif
62
63 /** @defgroup DWT DWT - Implementation of a discrete wavelet transform */
64 /*@{*/
65
66 #define OPJ_WS(i) v->mem[(i)*2]
67 #define OPJ_WD(i) v->mem[(1+(i)*2)]
68
69 #ifdef __AVX2__
70 /** Number of int32 values in a AVX2 register */
71 #define VREG_INT_COUNT       8
72 #else
73 /** Number of int32 values in a SSE2 register */
74 #define VREG_INT_COUNT       4
75 #endif
76
77 /** Number of columns that we can process in parallel in the vertical pass */
78 #define PARALLEL_COLS_53     (2*VREG_INT_COUNT)
79
80 /** @name Local data structures */
81 /*@{*/
82
83 typedef struct dwt_local {
84     OPJ_INT32* mem;
85     OPJ_INT32 dn;   /* number of elements in high pass band */
86     OPJ_INT32 sn;   /* number of elements in low pass band */
87     OPJ_INT32 cas;  /* 0 = start on even coord, 1 = start on odd coord */
88 } opj_dwt_t;
89
90 typedef union {
91     OPJ_FLOAT32 f[4];
92 } opj_v4_t;
93
94 typedef struct v4dwt_local {
95     opj_v4_t*   wavelet ;
96     OPJ_INT32       dn ;  /* number of elements in high pass band */
97     OPJ_INT32       sn ;  /* number of elements in low pass band */
98     OPJ_INT32       cas ; /* 0 = start on even coord, 1 = start on odd coord */
99     OPJ_UINT32      win_l_x0; /* start coord in low pass band */
100     OPJ_UINT32      win_l_x1; /* end coord in low pass band */
101     OPJ_UINT32      win_h_x0; /* start coord in high pass band */
102     OPJ_UINT32      win_h_x1; /* end coord in high pass band */
103 } opj_v4dwt_t ;
104
105 static const OPJ_FLOAT32 opj_dwt_alpha =  1.586134342f; /*  12994 */
106 static const OPJ_FLOAT32 opj_dwt_beta  =  0.052980118f; /*    434 */
107 static const OPJ_FLOAT32 opj_dwt_gamma = -0.882911075f; /*  -7233 */
108 static const OPJ_FLOAT32 opj_dwt_delta = -0.443506852f; /*  -3633 */
109
110 static const OPJ_FLOAT32 opj_K      = 1.230174105f; /*  10078 */
111 static const OPJ_FLOAT32 opj_c13318 = 1.625732422f;
112
113 /*@}*/
114
115 /**
116 Virtual function type for wavelet transform in 1-D
117 */
118 typedef void (*DWT1DFN)(const opj_dwt_t* v);
119
120 /** @name Local static functions */
121 /*@{*/
122
123 /**
124 Forward lazy transform (horizontal)
125 */
126 static void opj_dwt_deinterleave_h(OPJ_INT32 *a, OPJ_INT32 *b, OPJ_INT32 dn,
127                                    OPJ_INT32 sn, OPJ_INT32 cas);
128 /**
129 Forward lazy transform (vertical)
130 */
131 static void opj_dwt_deinterleave_v(OPJ_INT32 *a, OPJ_INT32 *b, OPJ_INT32 dn,
132                                    OPJ_INT32 sn, OPJ_INT32 x, OPJ_INT32 cas);
133 /**
134 Forward 5-3 wavelet transform in 1-D
135 */
136 static void opj_dwt_encode_1(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
137                              OPJ_INT32 cas);
138 /**
139 Forward 9-7 wavelet transform in 1-D
140 */
141 static void opj_dwt_encode_1_real(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
142                                   OPJ_INT32 cas);
143 /**
144 Explicit calculation of the Quantization Stepsizes
145 */
146 static void opj_dwt_encode_stepsize(OPJ_INT32 stepsize, OPJ_INT32 numbps,
147                                     opj_stepsize_t *bandno_stepsize);
148 /**
149 Inverse wavelet transform in 2-D.
150 */
151 static OPJ_BOOL opj_dwt_decode_tile(opj_thread_pool_t* tp,
152                                     opj_tcd_tilecomp_t* tilec, OPJ_UINT32 i);
153
154 static OPJ_BOOL opj_dwt_decode_partial_tile(
155     opj_tcd_tilecomp_t* tilec,
156     OPJ_UINT32 numres);
157
158 static OPJ_BOOL opj_dwt_encode_procedure(opj_tcd_tilecomp_t * tilec,
159         void (*p_function)(OPJ_INT32 *, OPJ_INT32, OPJ_INT32, OPJ_INT32));
160
161 static OPJ_UINT32 opj_dwt_max_resolution(opj_tcd_resolution_t* OPJ_RESTRICT r,
162         OPJ_UINT32 i);
163
164 /* <summary>                             */
165 /* Inverse 9-7 wavelet transform in 1-D. */
166 /* </summary>                            */
167 static void opj_v4dwt_decode(opj_v4dwt_t* OPJ_RESTRICT dwt);
168
169 static void opj_v4dwt_interleave_h(opj_v4dwt_t* OPJ_RESTRICT dwt,
170                                    OPJ_FLOAT32* OPJ_RESTRICT a,
171                                    OPJ_UINT32 width,
172                                    OPJ_UINT32 remaining_height);
173
174 static void opj_v4dwt_interleave_v(opj_v4dwt_t* OPJ_RESTRICT dwt,
175                                    OPJ_FLOAT32* OPJ_RESTRICT a,
176                                    OPJ_UINT32 width,
177                                    OPJ_UINT32 nb_elts_read);
178
179 #ifdef __SSE__
180 static void opj_v4dwt_decode_step1_sse(opj_v4_t* w,
181                                        OPJ_UINT32 start,
182                                        OPJ_UINT32 end,
183                                        const __m128 c);
184
185 static void opj_v4dwt_decode_step2_sse(opj_v4_t* l, opj_v4_t* w,
186                                        OPJ_UINT32 start,
187                                        OPJ_UINT32 end,
188                                        OPJ_UINT32 m, __m128 c);
189
190 #else
191 static void opj_v4dwt_decode_step1(opj_v4_t* w,
192                                    OPJ_UINT32 start,
193                                    OPJ_UINT32 end,
194                                    const OPJ_FLOAT32 c);
195
196 static void opj_v4dwt_decode_step2(opj_v4_t* l, opj_v4_t* w,
197                                    OPJ_UINT32 start,
198                                    OPJ_UINT32 end,
199                                    OPJ_UINT32 m,
200                                    OPJ_FLOAT32 c);
201
202 #endif
203
204 /*@}*/
205
206 /*@}*/
207
208 #define OPJ_S(i) a[(i)*2]
209 #define OPJ_D(i) a[(1+(i)*2)]
210 #define OPJ_S_(i) ((i)<0?OPJ_S(0):((i)>=sn?OPJ_S(sn-1):OPJ_S(i)))
211 #define OPJ_D_(i) ((i)<0?OPJ_D(0):((i)>=dn?OPJ_D(dn-1):OPJ_D(i)))
212 /* new */
213 #define OPJ_SS_(i) ((i)<0?OPJ_S(0):((i)>=dn?OPJ_S(dn-1):OPJ_S(i)))
214 #define OPJ_DD_(i) ((i)<0?OPJ_D(0):((i)>=sn?OPJ_D(sn-1):OPJ_D(i)))
215
216 /* <summary>                                                              */
217 /* This table contains the norms of the 5-3 wavelets for different bands. */
218 /* </summary>                                                             */
219 static const OPJ_FLOAT64 opj_dwt_norms[4][10] = {
220     {1.000, 1.500, 2.750, 5.375, 10.68, 21.34, 42.67, 85.33, 170.7, 341.3},
221     {1.038, 1.592, 2.919, 5.703, 11.33, 22.64, 45.25, 90.48, 180.9},
222     {1.038, 1.592, 2.919, 5.703, 11.33, 22.64, 45.25, 90.48, 180.9},
223     {.7186, .9218, 1.586, 3.043, 6.019, 12.01, 24.00, 47.97, 95.93}
224 };
225
226 /* <summary>                                                              */
227 /* This table contains the norms of the 9-7 wavelets for different bands. */
228 /* </summary>                                                             */
229 static const OPJ_FLOAT64 opj_dwt_norms_real[4][10] = {
230     {1.000, 1.965, 4.177, 8.403, 16.90, 33.84, 67.69, 135.3, 270.6, 540.9},
231     {2.022, 3.989, 8.355, 17.04, 34.27, 68.63, 137.3, 274.6, 549.0},
232     {2.022, 3.989, 8.355, 17.04, 34.27, 68.63, 137.3, 274.6, 549.0},
233     {2.080, 3.865, 8.307, 17.18, 34.71, 69.59, 139.3, 278.6, 557.2}
234 };
235
236 /*
237 ==========================================================
238    local functions
239 ==========================================================
240 */
241
242 /* <summary>                             */
243 /* Forward lazy transform (horizontal).  */
244 /* </summary>                            */
245 static void opj_dwt_deinterleave_h(OPJ_INT32 *a, OPJ_INT32 *b, OPJ_INT32 dn,
246                                    OPJ_INT32 sn, OPJ_INT32 cas)
247 {
248     OPJ_INT32 i;
249     OPJ_INT32 * l_dest = b;
250     OPJ_INT32 * l_src = a + cas;
251
252     for (i = 0; i < sn; ++i) {
253         *l_dest++ = *l_src;
254         l_src += 2;
255     }
256
257     l_dest = b + sn;
258     l_src = a + 1 - cas;
259
260     for (i = 0; i < dn; ++i)  {
261         *l_dest++ = *l_src;
262         l_src += 2;
263     }
264 }
265
266 /* <summary>                             */
267 /* Forward lazy transform (vertical).    */
268 /* </summary>                            */
269 static void opj_dwt_deinterleave_v(OPJ_INT32 *a, OPJ_INT32 *b, OPJ_INT32 dn,
270                                    OPJ_INT32 sn, OPJ_INT32 x, OPJ_INT32 cas)
271 {
272     OPJ_INT32 i = sn;
273     OPJ_INT32 * l_dest = b;
274     OPJ_INT32 * l_src = a + cas;
275
276     while (i--) {
277         *l_dest = *l_src;
278         l_dest += x;
279         l_src += 2;
280     } /* b[i*x]=a[2*i+cas]; */
281
282     l_dest = b + (OPJ_SIZE_T)sn * (OPJ_SIZE_T)x;
283     l_src = a + 1 - cas;
284
285     i = dn;
286     while (i--) {
287         *l_dest = *l_src;
288         l_dest += x;
289         l_src += 2;
290     } /*b[(sn+i)*x]=a[(2*i+1-cas)];*/
291 }
292
293 #ifdef STANDARD_SLOW_VERSION
294 /* <summary>                             */
295 /* Inverse lazy transform (horizontal).  */
296 /* </summary>                            */
297 static void opj_dwt_interleave_h(const opj_dwt_t* h, OPJ_INT32 *a)
298 {
299     OPJ_INT32 *ai = a;
300     OPJ_INT32 *bi = h->mem + h->cas;
301     OPJ_INT32  i    = h->sn;
302     while (i--) {
303         *bi = *(ai++);
304         bi += 2;
305     }
306     ai  = a + h->sn;
307     bi  = h->mem + 1 - h->cas;
308     i   = h->dn ;
309     while (i--) {
310         *bi = *(ai++);
311         bi += 2;
312     }
313 }
314
315 /* <summary>                             */
316 /* Inverse lazy transform (vertical).    */
317 /* </summary>                            */
318 static void opj_dwt_interleave_v(const opj_dwt_t* v, OPJ_INT32 *a, OPJ_INT32 x)
319 {
320     OPJ_INT32 *ai = a;
321     OPJ_INT32 *bi = v->mem + v->cas;
322     OPJ_INT32  i = v->sn;
323     while (i--) {
324         *bi = *ai;
325         bi += 2;
326         ai += x;
327     }
328     ai = a + (v->sn * (OPJ_SIZE_T)x);
329     bi = v->mem + 1 - v->cas;
330     i = v->dn ;
331     while (i--) {
332         *bi = *ai;
333         bi += 2;
334         ai += x;
335     }
336 }
337
338 #endif /* STANDARD_SLOW_VERSION */
339
340 /* <summary>                            */
341 /* Forward 5-3 wavelet transform in 1-D. */
342 /* </summary>                           */
343 static void opj_dwt_encode_1(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
344                              OPJ_INT32 cas)
345 {
346     OPJ_INT32 i;
347
348     if (!cas) {
349         if ((dn > 0) || (sn > 1)) { /* NEW :  CASE ONE ELEMENT */
350             for (i = 0; i < dn; i++) {
351                 OPJ_D(i) -= (OPJ_S_(i) + OPJ_S_(i + 1)) >> 1;
352             }
353             for (i = 0; i < sn; i++) {
354                 OPJ_S(i) += (OPJ_D_(i - 1) + OPJ_D_(i) + 2) >> 2;
355             }
356         }
357     } else {
358         if (!sn && dn == 1) {       /* NEW :  CASE ONE ELEMENT */
359             OPJ_S(0) *= 2;
360         } else {
361             for (i = 0; i < dn; i++) {
362                 OPJ_S(i) -= (OPJ_DD_(i) + OPJ_DD_(i - 1)) >> 1;
363             }
364             for (i = 0; i < sn; i++) {
365                 OPJ_D(i) += (OPJ_SS_(i) + OPJ_SS_(i + 1) + 2) >> 2;
366             }
367         }
368     }
369 }
370
371 #ifdef STANDARD_SLOW_VERSION
372 /* <summary>                            */
373 /* Inverse 5-3 wavelet transform in 1-D. */
374 /* </summary>                           */
375 static void opj_dwt_decode_1_(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
376                               OPJ_INT32 cas)
377 {
378     OPJ_INT32 i;
379
380     if (!cas) {
381         if ((dn > 0) || (sn > 1)) { /* NEW :  CASE ONE ELEMENT */
382             for (i = 0; i < sn; i++) {
383                 OPJ_S(i) -= (OPJ_D_(i - 1) + OPJ_D_(i) + 2) >> 2;
384             }
385             for (i = 0; i < dn; i++) {
386                 OPJ_D(i) += (OPJ_S_(i) + OPJ_S_(i + 1)) >> 1;
387             }
388         }
389     } else {
390         if (!sn  && dn == 1) {        /* NEW :  CASE ONE ELEMENT */
391             OPJ_S(0) /= 2;
392         } else {
393             for (i = 0; i < sn; i++) {
394                 OPJ_D(i) -= (OPJ_SS_(i) + OPJ_SS_(i + 1) + 2) >> 2;
395             }
396             for (i = 0; i < dn; i++) {
397                 OPJ_S(i) += (OPJ_DD_(i) + OPJ_DD_(i - 1)) >> 1;
398             }
399         }
400     }
401 }
402
403 static void opj_dwt_decode_1(const opj_dwt_t *v)
404 {
405     opj_dwt_decode_1_(v->mem, v->dn, v->sn, v->cas);
406 }
407
408 #endif /* STANDARD_SLOW_VERSION */
409
410 #if !defined(STANDARD_SLOW_VERSION)
411 static void  opj_idwt53_h_cas0(OPJ_INT32* tmp,
412                                const OPJ_INT32 sn,
413                                const OPJ_INT32 len,
414                                OPJ_INT32* tiledp)
415 {
416     OPJ_INT32 i, j;
417     const OPJ_INT32* in_even = &tiledp[0];
418     const OPJ_INT32* in_odd = &tiledp[sn];
419
420 #ifdef TWO_PASS_VERSION
421     /* For documentation purpose: performs lifting in two iterations, */
422     /* but without explicit interleaving */
423
424     assert(len > 1);
425
426     /* Even */
427     tmp[0] = in_even[0] - ((in_odd[0] + 1) >> 1);
428     for (i = 2, j = 0; i <= len - 2; i += 2, j++) {
429         tmp[i] = in_even[j + 1] - ((in_odd[j] + in_odd[j + 1] + 2) >> 2);
430     }
431     if (len & 1) { /* if len is odd */
432         tmp[len - 1] = in_even[(len - 1) / 2] - ((in_odd[(len - 2) / 2] + 1) >> 1);
433     }
434
435     /* Odd */
436     for (i = 1, j = 0; i < len - 1; i += 2, j++) {
437         tmp[i] = in_odd[j] + ((tmp[i - 1] + tmp[i + 1]) >> 1);
438     }
439     if (!(len & 1)) { /* if len is even */
440         tmp[len - 1] = in_odd[(len - 1) / 2] + tmp[len - 2];
441     }
442 #else
443     OPJ_INT32 d1c, d1n, s1n, s0c, s0n;
444
445     assert(len > 1);
446
447     /* Improved version of the TWO_PASS_VERSION: */
448     /* Performs lifting in one single iteration. Saves memory */
449     /* accesses and explicit interleaving. */
450     s1n = in_even[0];
451     d1n = in_odd[0];
452     s0n = s1n - ((d1n + 1) >> 1);
453
454     for (i = 0, j = 1; i < (len - 3); i += 2, j++) {
455         d1c = d1n;
456         s0c = s0n;
457
458         s1n = in_even[j];
459         d1n = in_odd[j];
460
461         s0n = s1n - ((d1c + d1n + 2) >> 2);
462
463         tmp[i  ] = s0c;
464         tmp[i + 1] = d1c + ((s0c + s0n) >> 1);
465     }
466
467     tmp[i] = s0n;
468
469     if (len & 1) {
470         tmp[len - 1] = in_even[(len - 1) / 2] - ((d1n + 1) >> 1);
471         tmp[len - 2] = d1n + ((s0n + tmp[len - 1]) >> 1);
472     } else {
473         tmp[len - 1] = d1n + s0n;
474     }
475 #endif
476     memcpy(tiledp, tmp, (OPJ_UINT32)len * sizeof(OPJ_INT32));
477 }
478
479 static void  opj_idwt53_h_cas1(OPJ_INT32* tmp,
480                                const OPJ_INT32 sn,
481                                const OPJ_INT32 len,
482                                OPJ_INT32* tiledp)
483 {
484     OPJ_INT32 i, j;
485     const OPJ_INT32* in_even = &tiledp[sn];
486     const OPJ_INT32* in_odd = &tiledp[0];
487
488 #ifdef TWO_PASS_VERSION
489     /* For documentation purpose: performs lifting in two iterations, */
490     /* but without explicit interleaving */
491
492     assert(len > 2);
493
494     /* Odd */
495     for (i = 1, j = 0; i < len - 1; i += 2, j++) {
496         tmp[i] = in_odd[j] - ((in_even[j] + in_even[j + 1] + 2) >> 2);
497     }
498     if (!(len & 1)) {
499         tmp[len - 1] = in_odd[len / 2 - 1] - ((in_even[len / 2 - 1] + 1) >> 1);
500     }
501
502     /* Even */
503     tmp[0] = in_even[0] + tmp[1];
504     for (i = 2, j = 1; i < len - 1; i += 2, j++) {
505         tmp[i] = in_even[j] + ((tmp[i + 1] + tmp[i - 1]) >> 1);
506     }
507     if (len & 1) {
508         tmp[len - 1] = in_even[len / 2] + tmp[len - 2];
509     }
510 #else
511     OPJ_INT32 s1, s2, dc, dn;
512
513     assert(len > 2);
514
515     /* Improved version of the TWO_PASS_VERSION: */
516     /* Performs lifting in one single iteration. Saves memory */
517     /* accesses and explicit interleaving. */
518
519     s1 = in_even[1];
520     dc = in_odd[0] - ((in_even[0] + s1 + 2) >> 2);
521     tmp[0] = in_even[0] + dc;
522
523     for (i = 1, j = 1; i < (len - 2 - !(len & 1)); i += 2, j++) {
524
525         s2 = in_even[j + 1];
526
527         dn = in_odd[j] - ((s1 + s2 + 2) >> 2);
528         tmp[i  ] = dc;
529         tmp[i + 1] = s1 + ((dn + dc) >> 1);
530
531         dc = dn;
532         s1 = s2;
533     }
534
535     tmp[i] = dc;
536
537     if (!(len & 1)) {
538         dn = in_odd[len / 2 - 1] - ((s1 + 1) >> 1);
539         tmp[len - 2] = s1 + ((dn + dc) >> 1);
540         tmp[len - 1] = dn;
541     } else {
542         tmp[len - 1] = s1 + dc;
543     }
544 #endif
545     memcpy(tiledp, tmp, (OPJ_UINT32)len * sizeof(OPJ_INT32));
546 }
547
548
549 #endif /* !defined(STANDARD_SLOW_VERSION) */
550
551 /* <summary>                            */
552 /* Inverse 5-3 wavelet transform in 1-D for one row. */
553 /* </summary>                           */
554 /* Performs interleave, inverse wavelet transform and copy back to buffer */
555 static void opj_idwt53_h(const opj_dwt_t *dwt,
556                          OPJ_INT32* tiledp)
557 {
558 #ifdef STANDARD_SLOW_VERSION
559     /* For documentation purpose */
560     opj_dwt_interleave_h(dwt, tiledp);
561     opj_dwt_decode_1(dwt);
562     memcpy(tiledp, dwt->mem, (OPJ_UINT32)(dwt->sn + dwt->dn) * sizeof(OPJ_INT32));
563 #else
564     const OPJ_INT32 sn = dwt->sn;
565     const OPJ_INT32 len = sn + dwt->dn;
566     if (dwt->cas == 0) { /* Left-most sample is on even coordinate */
567         if (len > 1) {
568             opj_idwt53_h_cas0(dwt->mem, sn, len, tiledp);
569         } else {
570             /* Unmodified value */
571         }
572     } else { /* Left-most sample is on odd coordinate */
573         if (len == 1) {
574             tiledp[0] /= 2;
575         } else if (len == 2) {
576             OPJ_INT32* out = dwt->mem;
577             const OPJ_INT32* in_even = &tiledp[sn];
578             const OPJ_INT32* in_odd = &tiledp[0];
579             out[1] = in_odd[0] - ((in_even[0] + 1) >> 1);
580             out[0] = in_even[0] + out[1];
581             memcpy(tiledp, dwt->mem, (OPJ_UINT32)len * sizeof(OPJ_INT32));
582         } else if (len > 2) {
583             opj_idwt53_h_cas1(dwt->mem, sn, len, tiledp);
584         }
585     }
586 #endif
587 }
588
589 #if (defined(__SSE2__) || defined(__AVX2__)) && !defined(STANDARD_SLOW_VERSION)
590
591 /* Conveniency macros to improve the readabilty of the formulas */
592 #if __AVX2__
593 #define VREG        __m256i
594 #define LOAD_CST(x) _mm256_set1_epi32(x)
595 #define LOAD(x)     _mm256_load_si256((const VREG*)(x))
596 #define LOADU(x)    _mm256_loadu_si256((const VREG*)(x))
597 #define STORE(x,y)  _mm256_store_si256((VREG*)(x),(y))
598 #define STOREU(x,y) _mm256_storeu_si256((VREG*)(x),(y))
599 #define ADD(x,y)    _mm256_add_epi32((x),(y))
600 #define SUB(x,y)    _mm256_sub_epi32((x),(y))
601 #define SAR(x,y)    _mm256_srai_epi32((x),(y))
602 #else
603 #define VREG        __m128i
604 #define LOAD_CST(x) _mm_set1_epi32(x)
605 #define LOAD(x)     _mm_load_si128((const VREG*)(x))
606 #define LOADU(x)    _mm_loadu_si128((const VREG*)(x))
607 #define STORE(x,y)  _mm_store_si128((VREG*)(x),(y))
608 #define STOREU(x,y) _mm_storeu_si128((VREG*)(x),(y))
609 #define ADD(x,y)    _mm_add_epi32((x),(y))
610 #define SUB(x,y)    _mm_sub_epi32((x),(y))
611 #define SAR(x,y)    _mm_srai_epi32((x),(y))
612 #endif
613 #define ADD3(x,y,z) ADD(ADD(x,y),z)
614
615 static
616 void opj_idwt53_v_final_memcpy(OPJ_INT32* tiledp_col,
617                                const OPJ_INT32* tmp,
618                                OPJ_INT32 len,
619                                OPJ_SIZE_T stride)
620 {
621     OPJ_INT32 i;
622     for (i = 0; i < len; ++i) {
623         /* A memcpy(&tiledp_col[i * stride + 0],
624                     &tmp[PARALLEL_COLS_53 * i + 0],
625                     PARALLEL_COLS_53 * sizeof(OPJ_INT32))
626            would do but would be a tiny bit slower.
627            We can take here advantage of our knowledge of alignment */
628         STOREU(&tiledp_col[(OPJ_SIZE_T)i * stride + 0],
629                LOAD(&tmp[PARALLEL_COLS_53 * i + 0]));
630         STOREU(&tiledp_col[(OPJ_SIZE_T)i * stride + VREG_INT_COUNT],
631                LOAD(&tmp[PARALLEL_COLS_53 * i + VREG_INT_COUNT]));
632     }
633 }
634
635 /** Vertical inverse 5x3 wavelet transform for 8 columns in SSE2, or
636  * 16 in AVX2, when top-most pixel is on even coordinate */
637 static void opj_idwt53_v_cas0_mcols_SSE2_OR_AVX2(
638     OPJ_INT32* tmp,
639     const OPJ_INT32 sn,
640     const OPJ_INT32 len,
641     OPJ_INT32* tiledp_col,
642     const OPJ_SIZE_T stride)
643 {
644     const OPJ_INT32* in_even = &tiledp_col[0];
645     const OPJ_INT32* in_odd = &tiledp_col[(OPJ_SIZE_T)sn * stride];
646
647     OPJ_INT32 i;
648     OPJ_SIZE_T j;
649     VREG d1c_0, d1n_0, s1n_0, s0c_0, s0n_0;
650     VREG d1c_1, d1n_1, s1n_1, s0c_1, s0n_1;
651     const VREG two = LOAD_CST(2);
652
653     assert(len > 1);
654 #if __AVX2__
655     assert(PARALLEL_COLS_53 == 16);
656     assert(VREG_INT_COUNT == 8);
657 #else
658     assert(PARALLEL_COLS_53 == 8);
659     assert(VREG_INT_COUNT == 4);
660 #endif
661
662     /* Note: loads of input even/odd values must be done in a unaligned */
663     /* fashion. But stores in tmp can be done with aligned store, since */
664     /* the temporary buffer is properly aligned */
665     assert((OPJ_SIZE_T)tmp % (sizeof(OPJ_INT32) * VREG_INT_COUNT) == 0);
666
667     s1n_0 = LOADU(in_even + 0);
668     s1n_1 = LOADU(in_even + VREG_INT_COUNT);
669     d1n_0 = LOADU(in_odd);
670     d1n_1 = LOADU(in_odd + VREG_INT_COUNT);
671
672     /* s0n = s1n - ((d1n + 1) >> 1); <==> */
673     /* s0n = s1n - ((d1n + d1n + 2) >> 2); */
674     s0n_0 = SUB(s1n_0, SAR(ADD3(d1n_0, d1n_0, two), 2));
675     s0n_1 = SUB(s1n_1, SAR(ADD3(d1n_1, d1n_1, two), 2));
676
677     for (i = 0, j = 1; i < (len - 3); i += 2, j++) {
678         d1c_0 = d1n_0;
679         s0c_0 = s0n_0;
680         d1c_1 = d1n_1;
681         s0c_1 = s0n_1;
682
683         s1n_0 = LOADU(in_even + j * stride);
684         s1n_1 = LOADU(in_even + j * stride + VREG_INT_COUNT);
685         d1n_0 = LOADU(in_odd + j * stride);
686         d1n_1 = LOADU(in_odd + j * stride + VREG_INT_COUNT);
687
688         /*s0n = s1n - ((d1c + d1n + 2) >> 2);*/
689         s0n_0 = SUB(s1n_0, SAR(ADD3(d1c_0, d1n_0, two), 2));
690         s0n_1 = SUB(s1n_1, SAR(ADD3(d1c_1, d1n_1, two), 2));
691
692         STORE(tmp + PARALLEL_COLS_53 * (i + 0), s0c_0);
693         STORE(tmp + PARALLEL_COLS_53 * (i + 0) + VREG_INT_COUNT, s0c_1);
694
695         /* d1c + ((s0c + s0n) >> 1) */
696         STORE(tmp + PARALLEL_COLS_53 * (i + 1) + 0,
697               ADD(d1c_0, SAR(ADD(s0c_0, s0n_0), 1)));
698         STORE(tmp + PARALLEL_COLS_53 * (i + 1) + VREG_INT_COUNT,
699               ADD(d1c_1, SAR(ADD(s0c_1, s0n_1), 1)));
700     }
701
702     STORE(tmp + PARALLEL_COLS_53 * (i + 0) + 0, s0n_0);
703     STORE(tmp + PARALLEL_COLS_53 * (i + 0) + VREG_INT_COUNT, s0n_1);
704
705     if (len & 1) {
706         VREG tmp_len_minus_1;
707         s1n_0 = LOADU(in_even + (OPJ_SIZE_T)((len - 1) / 2) * stride);
708         /* tmp_len_minus_1 = s1n - ((d1n + 1) >> 1); */
709         tmp_len_minus_1 = SUB(s1n_0, SAR(ADD3(d1n_0, d1n_0, two), 2));
710         STORE(tmp + PARALLEL_COLS_53 * (len - 1), tmp_len_minus_1);
711         /* d1n + ((s0n + tmp_len_minus_1) >> 1) */
712         STORE(tmp + PARALLEL_COLS_53 * (len - 2),
713               ADD(d1n_0, SAR(ADD(s0n_0, tmp_len_minus_1), 1)));
714
715         s1n_1 = LOADU(in_even + (OPJ_SIZE_T)((len - 1) / 2) * stride + VREG_INT_COUNT);
716         /* tmp_len_minus_1 = s1n - ((d1n + 1) >> 1); */
717         tmp_len_minus_1 = SUB(s1n_1, SAR(ADD3(d1n_1, d1n_1, two), 2));
718         STORE(tmp + PARALLEL_COLS_53 * (len - 1) + VREG_INT_COUNT,
719               tmp_len_minus_1);
720         /* d1n + ((s0n + tmp_len_minus_1) >> 1) */
721         STORE(tmp + PARALLEL_COLS_53 * (len - 2) + VREG_INT_COUNT,
722               ADD(d1n_1, SAR(ADD(s0n_1, tmp_len_minus_1), 1)));
723
724
725     } else {
726         STORE(tmp + PARALLEL_COLS_53 * (len - 1) + 0,
727               ADD(d1n_0, s0n_0));
728         STORE(tmp + PARALLEL_COLS_53 * (len - 1) + VREG_INT_COUNT,
729               ADD(d1n_1, s0n_1));
730     }
731
732     opj_idwt53_v_final_memcpy(tiledp_col, tmp, len, stride);
733 }
734
735
736 /** Vertical inverse 5x3 wavelet transform for 8 columns in SSE2, or
737  * 16 in AVX2, when top-most pixel is on odd coordinate */
738 static void opj_idwt53_v_cas1_mcols_SSE2_OR_AVX2(
739     OPJ_INT32* tmp,
740     const OPJ_INT32 sn,
741     const OPJ_INT32 len,
742     OPJ_INT32* tiledp_col,
743     const OPJ_SIZE_T stride)
744 {
745     OPJ_INT32 i;
746     OPJ_SIZE_T j;
747
748     VREG s1_0, s2_0, dc_0, dn_0;
749     VREG s1_1, s2_1, dc_1, dn_1;
750     const VREG two = LOAD_CST(2);
751
752     const OPJ_INT32* in_even = &tiledp_col[(OPJ_SIZE_T)sn * stride];
753     const OPJ_INT32* in_odd = &tiledp_col[0];
754
755     assert(len > 2);
756 #if __AVX2__
757     assert(PARALLEL_COLS_53 == 16);
758     assert(VREG_INT_COUNT == 8);
759 #else
760     assert(PARALLEL_COLS_53 == 8);
761     assert(VREG_INT_COUNT == 4);
762 #endif
763
764     /* Note: loads of input even/odd values must be done in a unaligned */
765     /* fashion. But stores in tmp can be done with aligned store, since */
766     /* the temporary buffer is properly aligned */
767     assert((OPJ_SIZE_T)tmp % (sizeof(OPJ_INT32) * VREG_INT_COUNT) == 0);
768
769     s1_0 = LOADU(in_even + stride);
770     /* in_odd[0] - ((in_even[0] + s1 + 2) >> 2); */
771     dc_0 = SUB(LOADU(in_odd + 0),
772                SAR(ADD3(LOADU(in_even + 0), s1_0, two), 2));
773     STORE(tmp + PARALLEL_COLS_53 * 0, ADD(LOADU(in_even + 0), dc_0));
774
775     s1_1 = LOADU(in_even + stride + VREG_INT_COUNT);
776     /* in_odd[0] - ((in_even[0] + s1 + 2) >> 2); */
777     dc_1 = SUB(LOADU(in_odd + VREG_INT_COUNT),
778                SAR(ADD3(LOADU(in_even + VREG_INT_COUNT), s1_1, two), 2));
779     STORE(tmp + PARALLEL_COLS_53 * 0 + VREG_INT_COUNT,
780           ADD(LOADU(in_even + VREG_INT_COUNT), dc_1));
781
782     for (i = 1, j = 1; i < (len - 2 - !(len & 1)); i += 2, j++) {
783
784         s2_0 = LOADU(in_even + (j + 1) * stride);
785         s2_1 = LOADU(in_even + (j + 1) * stride + VREG_INT_COUNT);
786
787         /* dn = in_odd[j * stride] - ((s1 + s2 + 2) >> 2); */
788         dn_0 = SUB(LOADU(in_odd + j * stride),
789                    SAR(ADD3(s1_0, s2_0, two), 2));
790         dn_1 = SUB(LOADU(in_odd + j * stride + VREG_INT_COUNT),
791                    SAR(ADD3(s1_1, s2_1, two), 2));
792
793         STORE(tmp + PARALLEL_COLS_53 * i, dc_0);
794         STORE(tmp + PARALLEL_COLS_53 * i + VREG_INT_COUNT, dc_1);
795
796         /* tmp[i + 1] = s1 + ((dn + dc) >> 1); */
797         STORE(tmp + PARALLEL_COLS_53 * (i + 1) + 0,
798               ADD(s1_0, SAR(ADD(dn_0, dc_0), 1)));
799         STORE(tmp + PARALLEL_COLS_53 * (i + 1) + VREG_INT_COUNT,
800               ADD(s1_1, SAR(ADD(dn_1, dc_1), 1)));
801
802         dc_0 = dn_0;
803         s1_0 = s2_0;
804         dc_1 = dn_1;
805         s1_1 = s2_1;
806     }
807     STORE(tmp + PARALLEL_COLS_53 * i, dc_0);
808     STORE(tmp + PARALLEL_COLS_53 * i + VREG_INT_COUNT, dc_1);
809
810     if (!(len & 1)) {
811         /*dn = in_odd[(len / 2 - 1) * stride] - ((s1 + 1) >> 1); */
812         dn_0 = SUB(LOADU(in_odd + (OPJ_SIZE_T)(len / 2 - 1) * stride),
813                    SAR(ADD3(s1_0, s1_0, two), 2));
814         dn_1 = SUB(LOADU(in_odd + (OPJ_SIZE_T)(len / 2 - 1) * stride + VREG_INT_COUNT),
815                    SAR(ADD3(s1_1, s1_1, two), 2));
816
817         /* tmp[len - 2] = s1 + ((dn + dc) >> 1); */
818         STORE(tmp + PARALLEL_COLS_53 * (len - 2) + 0,
819               ADD(s1_0, SAR(ADD(dn_0, dc_0), 1)));
820         STORE(tmp + PARALLEL_COLS_53 * (len - 2) + VREG_INT_COUNT,
821               ADD(s1_1, SAR(ADD(dn_1, dc_1), 1)));
822
823         STORE(tmp + PARALLEL_COLS_53 * (len - 1) + 0, dn_0);
824         STORE(tmp + PARALLEL_COLS_53 * (len - 1) + VREG_INT_COUNT, dn_1);
825     } else {
826         STORE(tmp + PARALLEL_COLS_53 * (len - 1) + 0, ADD(s1_0, dc_0));
827         STORE(tmp + PARALLEL_COLS_53 * (len - 1) + VREG_INT_COUNT,
828               ADD(s1_1, dc_1));
829     }
830
831     opj_idwt53_v_final_memcpy(tiledp_col, tmp, len, stride);
832 }
833
834 #undef VREG
835 #undef LOAD_CST
836 #undef LOADU
837 #undef LOAD
838 #undef STORE
839 #undef STOREU
840 #undef ADD
841 #undef ADD3
842 #undef SUB
843 #undef SAR
844
845 #endif /* (defined(__SSE2__) || defined(__AVX2__)) && !defined(STANDARD_SLOW_VERSION) */
846
847 #if !defined(STANDARD_SLOW_VERSION)
848 /** Vertical inverse 5x3 wavelet transform for one column, when top-most
849  * pixel is on even coordinate */
850 static void opj_idwt3_v_cas0(OPJ_INT32* tmp,
851                              const OPJ_INT32 sn,
852                              const OPJ_INT32 len,
853                              OPJ_INT32* tiledp_col,
854                              const OPJ_SIZE_T stride)
855 {
856     OPJ_INT32 i, j;
857     OPJ_INT32 d1c, d1n, s1n, s0c, s0n;
858
859     assert(len > 1);
860
861     /* Performs lifting in one single iteration. Saves memory */
862     /* accesses and explicit interleaving. */
863
864     s1n = tiledp_col[0];
865     d1n = tiledp_col[(OPJ_SIZE_T)sn * stride];
866     s0n = s1n - ((d1n + 1) >> 1);
867
868     for (i = 0, j = 0; i < (len - 3); i += 2, j++) {
869         d1c = d1n;
870         s0c = s0n;
871
872         s1n = tiledp_col[(OPJ_SIZE_T)(j + 1) * stride];
873         d1n = tiledp_col[(OPJ_SIZE_T)(sn + j + 1) * stride];
874
875         s0n = s1n - ((d1c + d1n + 2) >> 2);
876
877         tmp[i  ] = s0c;
878         tmp[i + 1] = d1c + ((s0c + s0n) >> 1);
879     }
880
881     tmp[i] = s0n;
882
883     if (len & 1) {
884         tmp[len - 1] =
885             tiledp_col[(OPJ_SIZE_T)((len - 1) / 2) * stride] -
886             ((d1n + 1) >> 1);
887         tmp[len - 2] = d1n + ((s0n + tmp[len - 1]) >> 1);
888     } else {
889         tmp[len - 1] = d1n + s0n;
890     }
891
892     for (i = 0; i < len; ++i) {
893         tiledp_col[(OPJ_SIZE_T)i * stride] = tmp[i];
894     }
895 }
896
897
898 /** Vertical inverse 5x3 wavelet transform for one column, when top-most
899  * pixel is on odd coordinate */
900 static void opj_idwt3_v_cas1(OPJ_INT32* tmp,
901                              const OPJ_INT32 sn,
902                              const OPJ_INT32 len,
903                              OPJ_INT32* tiledp_col,
904                              const OPJ_SIZE_T stride)
905 {
906     OPJ_INT32 i, j;
907     OPJ_INT32 s1, s2, dc, dn;
908     const OPJ_INT32* in_even = &tiledp_col[(OPJ_SIZE_T)sn * stride];
909     const OPJ_INT32* in_odd = &tiledp_col[0];
910
911     assert(len > 2);
912
913     /* Performs lifting in one single iteration. Saves memory */
914     /* accesses and explicit interleaving. */
915
916     s1 = in_even[stride];
917     dc = in_odd[0] - ((in_even[0] + s1 + 2) >> 2);
918     tmp[0] = in_even[0] + dc;
919     for (i = 1, j = 1; i < (len - 2 - !(len & 1)); i += 2, j++) {
920
921         s2 = in_even[(OPJ_SIZE_T)(j + 1) * stride];
922
923         dn = in_odd[(OPJ_SIZE_T)j * stride] - ((s1 + s2 + 2) >> 2);
924         tmp[i  ] = dc;
925         tmp[i + 1] = s1 + ((dn + dc) >> 1);
926
927         dc = dn;
928         s1 = s2;
929     }
930     tmp[i] = dc;
931     if (!(len & 1)) {
932         dn = in_odd[(OPJ_SIZE_T)(len / 2 - 1) * stride] - ((s1 + 1) >> 1);
933         tmp[len - 2] = s1 + ((dn + dc) >> 1);
934         tmp[len - 1] = dn;
935     } else {
936         tmp[len - 1] = s1 + dc;
937     }
938
939     for (i = 0; i < len; ++i) {
940         tiledp_col[(OPJ_SIZE_T)i * stride] = tmp[i];
941     }
942 }
943 #endif /* !defined(STANDARD_SLOW_VERSION) */
944
945 /* <summary>                            */
946 /* Inverse vertical 5-3 wavelet transform in 1-D for several columns. */
947 /* </summary>                           */
948 /* Performs interleave, inverse wavelet transform and copy back to buffer */
949 static void opj_idwt53_v(const opj_dwt_t *dwt,
950                          OPJ_INT32* tiledp_col,
951                          OPJ_SIZE_T stride,
952                          OPJ_INT32 nb_cols)
953 {
954 #ifdef STANDARD_SLOW_VERSION
955     /* For documentation purpose */
956     OPJ_INT32 k, c;
957     for (c = 0; c < nb_cols; c ++) {
958         opj_dwt_interleave_v(dwt, tiledp_col + c, stride);
959         opj_dwt_decode_1(dwt);
960         for (k = 0; k < dwt->sn + dwt->dn; ++k) {
961             tiledp_col[c + k * stride] = dwt->mem[k];
962         }
963     }
964 #else
965     const OPJ_INT32 sn = dwt->sn;
966     const OPJ_INT32 len = sn + dwt->dn;
967     if (dwt->cas == 0) {
968         /* If len == 1, unmodified value */
969
970 #if (defined(__SSE2__) || defined(__AVX2__))
971         if (len > 1 && nb_cols == PARALLEL_COLS_53) {
972             /* Same as below general case, except that thanks to SSE2/AVX2 */
973             /* we can efficently process 8/16 columns in parallel */
974             opj_idwt53_v_cas0_mcols_SSE2_OR_AVX2(dwt->mem, sn, len, tiledp_col, stride);
975             return;
976         }
977 #endif
978         if (len > 1) {
979             OPJ_INT32 c;
980             for (c = 0; c < nb_cols; c++, tiledp_col++) {
981                 opj_idwt3_v_cas0(dwt->mem, sn, len, tiledp_col, stride);
982             }
983             return;
984         }
985     } else {
986         if (len == 1) {
987             OPJ_INT32 c;
988             for (c = 0; c < nb_cols; c++, tiledp_col++) {
989                 tiledp_col[0] /= 2;
990             }
991             return;
992         }
993
994         if (len == 2) {
995             OPJ_INT32 c;
996             OPJ_INT32* out = dwt->mem;
997             for (c = 0; c < nb_cols; c++, tiledp_col++) {
998                 OPJ_INT32 i;
999                 const OPJ_INT32* in_even = &tiledp_col[(OPJ_SIZE_T)sn * stride];
1000                 const OPJ_INT32* in_odd = &tiledp_col[0];
1001
1002                 out[1] = in_odd[0] - ((in_even[0] + 1) >> 1);
1003                 out[0] = in_even[0] + out[1];
1004
1005                 for (i = 0; i < len; ++i) {
1006                     tiledp_col[(OPJ_SIZE_T)i * stride] = out[i];
1007                 }
1008             }
1009
1010             return;
1011         }
1012
1013 #if (defined(__SSE2__) || defined(__AVX2__))
1014         if (len > 2 && nb_cols == PARALLEL_COLS_53) {
1015             /* Same as below general case, except that thanks to SSE2/AVX2 */
1016             /* we can efficently process 8/16 columns in parallel */
1017             opj_idwt53_v_cas1_mcols_SSE2_OR_AVX2(dwt->mem, sn, len, tiledp_col, stride);
1018             return;
1019         }
1020 #endif
1021         if (len > 2) {
1022             OPJ_INT32 c;
1023             for (c = 0; c < nb_cols; c++, tiledp_col++) {
1024                 opj_idwt3_v_cas1(dwt->mem, sn, len, tiledp_col, stride);
1025             }
1026             return;
1027         }
1028     }
1029 #endif
1030 }
1031
1032
1033 /* <summary>                             */
1034 /* Forward 9-7 wavelet transform in 1-D. */
1035 /* </summary>                            */
1036 static void opj_dwt_encode_1_real(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
1037                                   OPJ_INT32 cas)
1038 {
1039     OPJ_INT32 i;
1040     if (!cas) {
1041         if ((dn > 0) || (sn > 1)) { /* NEW :  CASE ONE ELEMENT */
1042             for (i = 0; i < dn; i++) {
1043                 OPJ_D(i) -= opj_int_fix_mul(OPJ_S_(i) + OPJ_S_(i + 1), 12993);
1044             }
1045             for (i = 0; i < sn; i++) {
1046                 OPJ_S(i) -= opj_int_fix_mul(OPJ_D_(i - 1) + OPJ_D_(i), 434);
1047             }
1048             for (i = 0; i < dn; i++) {
1049                 OPJ_D(i) += opj_int_fix_mul(OPJ_S_(i) + OPJ_S_(i + 1), 7233);
1050             }
1051             for (i = 0; i < sn; i++) {
1052                 OPJ_S(i) += opj_int_fix_mul(OPJ_D_(i - 1) + OPJ_D_(i), 3633);
1053             }
1054             for (i = 0; i < dn; i++) {
1055                 OPJ_D(i) = opj_int_fix_mul(OPJ_D(i), 5038);    /*5038 */
1056             }
1057             for (i = 0; i < sn; i++) {
1058                 OPJ_S(i) = opj_int_fix_mul(OPJ_S(i), 6659);    /*6660 */
1059             }
1060         }
1061     } else {
1062         if ((sn > 0) || (dn > 1)) { /* NEW :  CASE ONE ELEMENT */
1063             for (i = 0; i < dn; i++) {
1064                 OPJ_S(i) -= opj_int_fix_mul(OPJ_DD_(i) + OPJ_DD_(i - 1), 12993);
1065             }
1066             for (i = 0; i < sn; i++) {
1067                 OPJ_D(i) -= opj_int_fix_mul(OPJ_SS_(i) + OPJ_SS_(i + 1), 434);
1068             }
1069             for (i = 0; i < dn; i++) {
1070                 OPJ_S(i) += opj_int_fix_mul(OPJ_DD_(i) + OPJ_DD_(i - 1), 7233);
1071             }
1072             for (i = 0; i < sn; i++) {
1073                 OPJ_D(i) += opj_int_fix_mul(OPJ_SS_(i) + OPJ_SS_(i + 1), 3633);
1074             }
1075             for (i = 0; i < dn; i++) {
1076                 OPJ_S(i) = opj_int_fix_mul(OPJ_S(i), 5038);    /*5038 */
1077             }
1078             for (i = 0; i < sn; i++) {
1079                 OPJ_D(i) = opj_int_fix_mul(OPJ_D(i), 6659);    /*6660 */
1080             }
1081         }
1082     }
1083 }
1084
1085 static void opj_dwt_encode_stepsize(OPJ_INT32 stepsize, OPJ_INT32 numbps,
1086                                     opj_stepsize_t *bandno_stepsize)
1087 {
1088     OPJ_INT32 p, n;
1089     p = opj_int_floorlog2(stepsize) - 13;
1090     n = 11 - opj_int_floorlog2(stepsize);
1091     bandno_stepsize->mant = (n < 0 ? stepsize >> -n : stepsize << n) & 0x7ff;
1092     bandno_stepsize->expn = numbps - p;
1093 }
1094
1095 /*
1096 ==========================================================
1097    DWT interface
1098 ==========================================================
1099 */
1100
1101
1102 /* <summary>                            */
1103 /* Forward 5-3 wavelet transform in 2-D. */
1104 /* </summary>                           */
1105 static INLINE OPJ_BOOL opj_dwt_encode_procedure(opj_tcd_tilecomp_t * tilec,
1106         void (*p_function)(OPJ_INT32 *, OPJ_INT32, OPJ_INT32, OPJ_INT32))
1107 {
1108     OPJ_INT32 i, j, k;
1109     OPJ_INT32 *a = 00;
1110     OPJ_INT32 *aj = 00;
1111     OPJ_INT32 *bj = 00;
1112     OPJ_INT32 w, l;
1113
1114     OPJ_INT32 rw;           /* width of the resolution level computed   */
1115     OPJ_INT32 rh;           /* height of the resolution level computed  */
1116     OPJ_SIZE_T l_data_size;
1117
1118     opj_tcd_resolution_t * l_cur_res = 0;
1119     opj_tcd_resolution_t * l_last_res = 0;
1120
1121     w = tilec->x1 - tilec->x0;
1122     l = (OPJ_INT32)tilec->numresolutions - 1;
1123     a = tilec->data;
1124
1125     l_cur_res = tilec->resolutions + l;
1126     l_last_res = l_cur_res - 1;
1127
1128     l_data_size = opj_dwt_max_resolution(tilec->resolutions, tilec->numresolutions);
1129     /* overflow check */
1130     if (l_data_size > (SIZE_MAX / sizeof(OPJ_INT32))) {
1131         /* FIXME event manager error callback */
1132         return OPJ_FALSE;
1133     }
1134     l_data_size *= sizeof(OPJ_INT32);
1135     bj = (OPJ_INT32*)opj_malloc(l_data_size);
1136     /* l_data_size is equal to 0 when numresolutions == 1 but bj is not used */
1137     /* in that case, so do not error out */
1138     if (l_data_size != 0 && ! bj) {
1139         return OPJ_FALSE;
1140     }
1141     i = l;
1142
1143     while (i--) {
1144         OPJ_INT32 rw1;      /* width of the resolution level once lower than computed one                                       */
1145         OPJ_INT32 rh1;      /* height of the resolution level once lower than computed one                                      */
1146         OPJ_INT32 cas_col;  /* 0 = non inversion on horizontal filtering 1 = inversion between low-pass and high-pass filtering */
1147         OPJ_INT32 cas_row;  /* 0 = non inversion on vertical filtering 1 = inversion between low-pass and high-pass filtering   */
1148         OPJ_INT32 dn, sn;
1149
1150         rw  = l_cur_res->x1 - l_cur_res->x0;
1151         rh  = l_cur_res->y1 - l_cur_res->y0;
1152         rw1 = l_last_res->x1 - l_last_res->x0;
1153         rh1 = l_last_res->y1 - l_last_res->y0;
1154
1155         cas_row = l_cur_res->x0 & 1;
1156         cas_col = l_cur_res->y0 & 1;
1157
1158         sn = rh1;
1159         dn = rh - rh1;
1160         for (j = 0; j < rw; ++j) {
1161             aj = a + j;
1162             for (k = 0; k < rh; ++k) {
1163                 bj[k] = aj[k * w];
1164             }
1165
1166             (*p_function)(bj, dn, sn, cas_col);
1167
1168             opj_dwt_deinterleave_v(bj, aj, dn, sn, w, cas_col);
1169         }
1170
1171         sn = rw1;
1172         dn = rw - rw1;
1173
1174         for (j = 0; j < rh; j++) {
1175             aj = a + j * w;
1176             for (k = 0; k < rw; k++) {
1177                 bj[k] = aj[k];
1178             }
1179             (*p_function)(bj, dn, sn, cas_row);
1180             opj_dwt_deinterleave_h(bj, aj, dn, sn, cas_row);
1181         }
1182
1183         l_cur_res = l_last_res;
1184
1185         --l_last_res;
1186     }
1187
1188     opj_free(bj);
1189     return OPJ_TRUE;
1190 }
1191
1192 /* Forward 5-3 wavelet transform in 2-D. */
1193 /* </summary>                           */
1194 OPJ_BOOL opj_dwt_encode(opj_tcd_tilecomp_t * tilec)
1195 {
1196     return opj_dwt_encode_procedure(tilec, opj_dwt_encode_1);
1197 }
1198
1199 /* <summary>                            */
1200 /* Inverse 5-3 wavelet transform in 2-D. */
1201 /* </summary>                           */
1202 OPJ_BOOL opj_dwt_decode(opj_tcd_t *p_tcd, opj_tcd_tilecomp_t* tilec,
1203                         OPJ_UINT32 numres)
1204 {
1205     if (p_tcd->whole_tile_decoding) {
1206         return opj_dwt_decode_tile(p_tcd->thread_pool, tilec, numres);
1207     } else {
1208         return opj_dwt_decode_partial_tile(tilec, numres);
1209     }
1210 }
1211
1212
1213 /* <summary>                          */
1214 /* Get gain of 5-3 wavelet transform. */
1215 /* </summary>                         */
1216 OPJ_UINT32 opj_dwt_getgain(OPJ_UINT32 orient)
1217 {
1218     if (orient == 0) {
1219         return 0;
1220     }
1221     if (orient == 1 || orient == 2) {
1222         return 1;
1223     }
1224     return 2;
1225 }
1226
1227 /* <summary>                */
1228 /* Get norm of 5-3 wavelet. */
1229 /* </summary>               */
1230 OPJ_FLOAT64 opj_dwt_getnorm(OPJ_UINT32 level, OPJ_UINT32 orient)
1231 {
1232     return opj_dwt_norms[orient][level];
1233 }
1234
1235 /* <summary>                             */
1236 /* Forward 9-7 wavelet transform in 2-D. */
1237 /* </summary>                            */
1238 OPJ_BOOL opj_dwt_encode_real(opj_tcd_tilecomp_t * tilec)
1239 {
1240     return opj_dwt_encode_procedure(tilec, opj_dwt_encode_1_real);
1241 }
1242
1243 /* <summary>                          */
1244 /* Get gain of 9-7 wavelet transform. */
1245 /* </summary>                         */
1246 OPJ_UINT32 opj_dwt_getgain_real(OPJ_UINT32 orient)
1247 {
1248     (void)orient;
1249     return 0;
1250 }
1251
1252 /* <summary>                */
1253 /* Get norm of 9-7 wavelet. */
1254 /* </summary>               */
1255 OPJ_FLOAT64 opj_dwt_getnorm_real(OPJ_UINT32 level, OPJ_UINT32 orient)
1256 {
1257     return opj_dwt_norms_real[orient][level];
1258 }
1259
1260 void opj_dwt_calc_explicit_stepsizes(opj_tccp_t * tccp, OPJ_UINT32 prec)
1261 {
1262     OPJ_UINT32 numbands, bandno;
1263     numbands = 3 * tccp->numresolutions - 2;
1264     for (bandno = 0; bandno < numbands; bandno++) {
1265         OPJ_FLOAT64 stepsize;
1266         OPJ_UINT32 resno, level, orient, gain;
1267
1268         resno = (bandno == 0) ? 0 : ((bandno - 1) / 3 + 1);
1269         orient = (bandno == 0) ? 0 : ((bandno - 1) % 3 + 1);
1270         level = tccp->numresolutions - 1 - resno;
1271         gain = (tccp->qmfbid == 0) ? 0 : ((orient == 0) ? 0 : (((orient == 1) ||
1272                                           (orient == 2)) ? 1 : 2));
1273         if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
1274             stepsize = 1.0;
1275         } else {
1276             OPJ_FLOAT64 norm = opj_dwt_norms_real[orient][level];
1277             stepsize = (1 << (gain)) / norm;
1278         }
1279         opj_dwt_encode_stepsize((OPJ_INT32) floor(stepsize * 8192.0),
1280                                 (OPJ_INT32)(prec + gain), &tccp->stepsizes[bandno]);
1281     }
1282 }
1283
1284 /* <summary>                             */
1285 /* Determine maximum computed resolution level for inverse wavelet transform */
1286 /* </summary>                            */
1287 static OPJ_UINT32 opj_dwt_max_resolution(opj_tcd_resolution_t* OPJ_RESTRICT r,
1288         OPJ_UINT32 i)
1289 {
1290     OPJ_UINT32 mr   = 0;
1291     OPJ_UINT32 w;
1292     while (--i) {
1293         ++r;
1294         if (mr < (w = (OPJ_UINT32)(r->x1 - r->x0))) {
1295             mr = w ;
1296         }
1297         if (mr < (w = (OPJ_UINT32)(r->y1 - r->y0))) {
1298             mr = w ;
1299         }
1300     }
1301     return mr ;
1302 }
1303
1304 typedef struct {
1305     opj_dwt_t h;
1306     OPJ_UINT32 rw;
1307     OPJ_UINT32 w;
1308     OPJ_INT32 * OPJ_RESTRICT tiledp;
1309     OPJ_UINT32 min_j;
1310     OPJ_UINT32 max_j;
1311 } opj_dwd_decode_h_job_t;
1312
1313 static void opj_dwt_decode_h_func(void* user_data, opj_tls_t* tls)
1314 {
1315     OPJ_UINT32 j;
1316     opj_dwd_decode_h_job_t* job;
1317     (void)tls;
1318
1319     job = (opj_dwd_decode_h_job_t*)user_data;
1320     for (j = job->min_j; j < job->max_j; j++) {
1321         opj_idwt53_h(&job->h, &job->tiledp[j * job->w]);
1322     }
1323
1324     opj_aligned_free(job->h.mem);
1325     opj_free(job);
1326 }
1327
1328 typedef struct {
1329     opj_dwt_t v;
1330     OPJ_UINT32 rh;
1331     OPJ_UINT32 w;
1332     OPJ_INT32 * OPJ_RESTRICT tiledp;
1333     OPJ_UINT32 min_j;
1334     OPJ_UINT32 max_j;
1335 } opj_dwd_decode_v_job_t;
1336
1337 static void opj_dwt_decode_v_func(void* user_data, opj_tls_t* tls)
1338 {
1339     OPJ_UINT32 j;
1340     opj_dwd_decode_v_job_t* job;
1341     (void)tls;
1342
1343     job = (opj_dwd_decode_v_job_t*)user_data;
1344     for (j = job->min_j; j + PARALLEL_COLS_53 <= job->max_j;
1345             j += PARALLEL_COLS_53) {
1346         opj_idwt53_v(&job->v, &job->tiledp[j], (OPJ_SIZE_T)job->w,
1347                      PARALLEL_COLS_53);
1348     }
1349     if (j < job->max_j)
1350         opj_idwt53_v(&job->v, &job->tiledp[j], (OPJ_SIZE_T)job->w,
1351                      (OPJ_INT32)(job->max_j - j));
1352
1353     opj_aligned_free(job->v.mem);
1354     opj_free(job);
1355 }
1356
1357
1358 /* <summary>                            */
1359 /* Inverse wavelet transform in 2-D.    */
1360 /* </summary>                           */
1361 static OPJ_BOOL opj_dwt_decode_tile(opj_thread_pool_t* tp,
1362                                     opj_tcd_tilecomp_t* tilec, OPJ_UINT32 numres)
1363 {
1364     opj_dwt_t h;
1365     opj_dwt_t v;
1366
1367     opj_tcd_resolution_t* tr = tilec->resolutions;
1368
1369     OPJ_UINT32 rw = (OPJ_UINT32)(tr->x1 -
1370                                  tr->x0);  /* width of the resolution level computed */
1371     OPJ_UINT32 rh = (OPJ_UINT32)(tr->y1 -
1372                                  tr->y0);  /* height of the resolution level computed */
1373
1374     OPJ_UINT32 w = (OPJ_UINT32)(tilec->resolutions[tilec->minimum_num_resolutions -
1375                                                                1].x1 -
1376                                 tilec->resolutions[tilec->minimum_num_resolutions - 1].x0);
1377     OPJ_SIZE_T h_mem_size;
1378     int num_threads;
1379
1380     if (numres == 1U) {
1381         return OPJ_TRUE;
1382     }
1383     num_threads = opj_thread_pool_get_thread_count(tp);
1384     h_mem_size = opj_dwt_max_resolution(tr, numres);
1385     /* overflow check */
1386     if (h_mem_size > (SIZE_MAX / PARALLEL_COLS_53 / sizeof(OPJ_INT32))) {
1387         /* FIXME event manager error callback */
1388         return OPJ_FALSE;
1389     }
1390     /* We need PARALLEL_COLS_53 times the height of the array, */
1391     /* since for the vertical pass */
1392     /* we process PARALLEL_COLS_53 columns at a time */
1393     h_mem_size *= PARALLEL_COLS_53 * sizeof(OPJ_INT32);
1394     h.mem = (OPJ_INT32*)opj_aligned_32_malloc(h_mem_size);
1395     if (! h.mem) {
1396         /* FIXME event manager error callback */
1397         return OPJ_FALSE;
1398     }
1399
1400     v.mem = h.mem;
1401
1402     while (--numres) {
1403         OPJ_INT32 * OPJ_RESTRICT tiledp = tilec->data;
1404         OPJ_UINT32 j;
1405
1406         ++tr;
1407         h.sn = (OPJ_INT32)rw;
1408         v.sn = (OPJ_INT32)rh;
1409
1410         rw = (OPJ_UINT32)(tr->x1 - tr->x0);
1411         rh = (OPJ_UINT32)(tr->y1 - tr->y0);
1412
1413         h.dn = (OPJ_INT32)(rw - (OPJ_UINT32)h.sn);
1414         h.cas = tr->x0 % 2;
1415
1416         if (num_threads <= 1 || rh <= 1) {
1417             for (j = 0; j < rh; ++j) {
1418                 opj_idwt53_h(&h, &tiledp[(OPJ_SIZE_T)j * w]);
1419             }
1420         } else {
1421             OPJ_UINT32 num_jobs = (OPJ_UINT32)num_threads;
1422             OPJ_UINT32 step_j;
1423
1424             if (rh < num_jobs) {
1425                 num_jobs = rh;
1426             }
1427             step_j = (rh / num_jobs);
1428
1429             for (j = 0; j < num_jobs; j++) {
1430                 opj_dwd_decode_h_job_t* job;
1431
1432                 job = (opj_dwd_decode_h_job_t*) opj_malloc(sizeof(opj_dwd_decode_h_job_t));
1433                 if (!job) {
1434                     /* It would be nice to fallback to single thread case, but */
1435                     /* unfortunately some jobs may be launched and have modified */
1436                     /* tiledp, so it is not practical to recover from that error */
1437                     /* FIXME event manager error callback */
1438                     opj_thread_pool_wait_completion(tp, 0);
1439                     opj_aligned_free(h.mem);
1440                     return OPJ_FALSE;
1441                 }
1442                 job->h = h;
1443                 job->rw = rw;
1444                 job->w = w;
1445                 job->tiledp = tiledp;
1446                 job->min_j = j * step_j;
1447                 job->max_j = (j + 1U) * step_j; /* this can overflow */
1448                 if (j == (num_jobs - 1U)) {  /* this will take care of the overflow */
1449                     job->max_j = rh;
1450                 }
1451                 job->h.mem = (OPJ_INT32*)opj_aligned_32_malloc(h_mem_size);
1452                 if (!job->h.mem) {
1453                     /* FIXME event manager error callback */
1454                     opj_thread_pool_wait_completion(tp, 0);
1455                     opj_free(job);
1456                     opj_aligned_free(h.mem);
1457                     return OPJ_FALSE;
1458                 }
1459                 opj_thread_pool_submit_job(tp, opj_dwt_decode_h_func, job);
1460             }
1461             opj_thread_pool_wait_completion(tp, 0);
1462         }
1463
1464         v.dn = (OPJ_INT32)(rh - (OPJ_UINT32)v.sn);
1465         v.cas = tr->y0 % 2;
1466
1467         if (num_threads <= 1 || rw <= 1) {
1468             for (j = 0; j + PARALLEL_COLS_53 <= rw;
1469                     j += PARALLEL_COLS_53) {
1470                 opj_idwt53_v(&v, &tiledp[j], (OPJ_SIZE_T)w, PARALLEL_COLS_53);
1471             }
1472             if (j < rw) {
1473                 opj_idwt53_v(&v, &tiledp[j], (OPJ_SIZE_T)w, (OPJ_INT32)(rw - j));
1474             }
1475         } else {
1476             OPJ_UINT32 num_jobs = (OPJ_UINT32)num_threads;
1477             OPJ_UINT32 step_j;
1478
1479             if (rw < num_jobs) {
1480                 num_jobs = rw;
1481             }
1482             step_j = (rw / num_jobs);
1483
1484             for (j = 0; j < num_jobs; j++) {
1485                 opj_dwd_decode_v_job_t* job;
1486
1487                 job = (opj_dwd_decode_v_job_t*) opj_malloc(sizeof(opj_dwd_decode_v_job_t));
1488                 if (!job) {
1489                     /* It would be nice to fallback to single thread case, but */
1490                     /* unfortunately some jobs may be launched and have modified */
1491                     /* tiledp, so it is not practical to recover from that error */
1492                     /* FIXME event manager error callback */
1493                     opj_thread_pool_wait_completion(tp, 0);
1494                     opj_aligned_free(v.mem);
1495                     return OPJ_FALSE;
1496                 }
1497                 job->v = v;
1498                 job->rh = rh;
1499                 job->w = w;
1500                 job->tiledp = tiledp;
1501                 job->min_j = j * step_j;
1502                 job->max_j = (j + 1U) * step_j; /* this can overflow */
1503                 if (j == (num_jobs - 1U)) {  /* this will take care of the overflow */
1504                     job->max_j = rw;
1505                 }
1506                 job->v.mem = (OPJ_INT32*)opj_aligned_32_malloc(h_mem_size);
1507                 if (!job->v.mem) {
1508                     /* FIXME event manager error callback */
1509                     opj_thread_pool_wait_completion(tp, 0);
1510                     opj_free(job);
1511                     opj_aligned_free(v.mem);
1512                     return OPJ_FALSE;
1513                 }
1514                 opj_thread_pool_submit_job(tp, opj_dwt_decode_v_func, job);
1515             }
1516             opj_thread_pool_wait_completion(tp, 0);
1517         }
1518     }
1519     opj_aligned_free(h.mem);
1520     return OPJ_TRUE;
1521 }
1522
1523 static void opj_dwt_interleave_partial_h(OPJ_INT32 *dest,
1524         OPJ_INT32 cas,
1525         opj_sparse_array_int32_t* sa,
1526         OPJ_UINT32 sa_line,
1527         OPJ_UINT32 sn,
1528         OPJ_UINT32 win_l_x0,
1529         OPJ_UINT32 win_l_x1,
1530         OPJ_UINT32 win_h_x0,
1531         OPJ_UINT32 win_h_x1)
1532 {
1533     OPJ_BOOL ret;
1534     ret = opj_sparse_array_int32_read(sa,
1535                                       win_l_x0, sa_line,
1536                                       win_l_x1, sa_line + 1,
1537                                       dest + cas + 2 * win_l_x0,
1538                                       2, 0, OPJ_TRUE);
1539     assert(ret);
1540     ret = opj_sparse_array_int32_read(sa,
1541                                       sn + win_h_x0, sa_line,
1542                                       sn + win_h_x1, sa_line + 1,
1543                                       dest + 1 - cas + 2 * win_h_x0,
1544                                       2, 0, OPJ_TRUE);
1545     assert(ret);
1546     OPJ_UNUSED(ret);
1547 }
1548
1549
1550 static void opj_dwt_interleave_partial_v(OPJ_INT32 *dest,
1551         OPJ_INT32 cas,
1552         opj_sparse_array_int32_t* sa,
1553         OPJ_UINT32 sa_col,
1554         OPJ_UINT32 nb_cols,
1555         OPJ_UINT32 sn,
1556         OPJ_UINT32 win_l_y0,
1557         OPJ_UINT32 win_l_y1,
1558         OPJ_UINT32 win_h_y0,
1559         OPJ_UINT32 win_h_y1)
1560 {
1561     OPJ_BOOL ret;
1562     ret  = opj_sparse_array_int32_read(sa,
1563                                        sa_col, win_l_y0,
1564                                        sa_col + nb_cols, win_l_y1,
1565                                        dest + cas * 4 + 2 * 4 * win_l_y0,
1566                                        1, 2 * 4, OPJ_TRUE);
1567     assert(ret);
1568     ret = opj_sparse_array_int32_read(sa,
1569                                       sa_col, sn + win_h_y0,
1570                                       sa_col + nb_cols, sn + win_h_y1,
1571                                       dest + (1 - cas) * 4 + 2 * 4 * win_h_y0,
1572                                       1, 2 * 4, OPJ_TRUE);
1573     assert(ret);
1574     OPJ_UNUSED(ret);
1575 }
1576
1577 static void opj_dwt_decode_partial_1(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
1578                                      OPJ_INT32 cas,
1579                                      OPJ_INT32 win_l_x0,
1580                                      OPJ_INT32 win_l_x1,
1581                                      OPJ_INT32 win_h_x0,
1582                                      OPJ_INT32 win_h_x1)
1583 {
1584     OPJ_INT32 i;
1585
1586     if (!cas) {
1587         if ((dn > 0) || (sn > 1)) { /* NEW :  CASE ONE ELEMENT */
1588
1589             /* Naive version is :
1590             for (i = win_l_x0; i < i_max; i++) {
1591                 OPJ_S(i) -= (OPJ_D_(i - 1) + OPJ_D_(i) + 2) >> 2;
1592             }
1593             for (i = win_h_x0; i < win_h_x1; i++) {
1594                 OPJ_D(i) += (OPJ_S_(i) + OPJ_S_(i + 1)) >> 1;
1595             }
1596             but the compiler doesn't manage to unroll it to avoid bound
1597             checking in OPJ_S_ and OPJ_D_ macros
1598             */
1599
1600             i = win_l_x0;
1601             if (i < win_l_x1) {
1602                 OPJ_INT32 i_max;
1603
1604                 /* Left-most case */
1605                 OPJ_S(i) -= (OPJ_D_(i - 1) + OPJ_D_(i) + 2) >> 2;
1606                 i ++;
1607
1608                 i_max = win_l_x1;
1609                 if (i_max > dn) {
1610                     i_max = dn;
1611                 }
1612                 for (; i < i_max; i++) {
1613                     /* No bound checking */
1614                     OPJ_S(i) -= (OPJ_D(i - 1) + OPJ_D(i) + 2) >> 2;
1615                 }
1616                 for (; i < win_l_x1; i++) {
1617                     /* Right-most case */
1618                     OPJ_S(i) -= (OPJ_D_(i - 1) + OPJ_D_(i) + 2) >> 2;
1619                 }
1620             }
1621
1622             i = win_h_x0;
1623             if (i < win_h_x1) {
1624                 OPJ_INT32 i_max = win_h_x1;
1625                 if (i_max >= sn) {
1626                     i_max = sn - 1;
1627                 }
1628                 for (; i < i_max; i++) {
1629                     /* No bound checking */
1630                     OPJ_D(i) += (OPJ_S(i) + OPJ_S(i + 1)) >> 1;
1631                 }
1632                 for (; i < win_h_x1; i++) {
1633                     /* Right-most case */
1634                     OPJ_D(i) += (OPJ_S_(i) + OPJ_S_(i + 1)) >> 1;
1635                 }
1636             }
1637         }
1638     } else {
1639         if (!sn  && dn == 1) {        /* NEW :  CASE ONE ELEMENT */
1640             OPJ_S(0) /= 2;
1641         } else {
1642             for (i = win_l_x0; i < win_l_x1; i++) {
1643                 OPJ_D(i) -= (OPJ_SS_(i) + OPJ_SS_(i + 1) + 2) >> 2;
1644             }
1645             for (i = win_h_x0; i < win_h_x1; i++) {
1646                 OPJ_S(i) += (OPJ_DD_(i) + OPJ_DD_(i - 1)) >> 1;
1647             }
1648         }
1649     }
1650 }
1651
1652 #define OPJ_S_off(i,off) a[(OPJ_UINT32)(i)*2*4+off]
1653 #define OPJ_D_off(i,off) a[(1+(OPJ_UINT32)(i)*2)*4+off]
1654 #define OPJ_S__off(i,off) ((i)<0?OPJ_S_off(0,off):((i)>=sn?OPJ_S_off(sn-1,off):OPJ_S_off(i,off)))
1655 #define OPJ_D__off(i,off) ((i)<0?OPJ_D_off(0,off):((i)>=dn?OPJ_D_off(dn-1,off):OPJ_D_off(i,off)))
1656 #define OPJ_SS__off(i,off) ((i)<0?OPJ_S_off(0,off):((i)>=dn?OPJ_S_off(dn-1,off):OPJ_S_off(i,off)))
1657 #define OPJ_DD__off(i,off) ((i)<0?OPJ_D_off(0,off):((i)>=sn?OPJ_D_off(sn-1,off):OPJ_D_off(i,off)))
1658
1659 static void opj_dwt_decode_partial_1_parallel(OPJ_INT32 *a,
1660         OPJ_UINT32 nb_cols,
1661         OPJ_INT32 dn, OPJ_INT32 sn,
1662         OPJ_INT32 cas,
1663         OPJ_INT32 win_l_x0,
1664         OPJ_INT32 win_l_x1,
1665         OPJ_INT32 win_h_x0,
1666         OPJ_INT32 win_h_x1)
1667 {
1668     OPJ_INT32 i;
1669     OPJ_UINT32 off;
1670
1671     (void)nb_cols;
1672
1673     if (!cas) {
1674         if ((dn > 0) || (sn > 1)) { /* NEW :  CASE ONE ELEMENT */
1675
1676             /* Naive version is :
1677             for (i = win_l_x0; i < i_max; i++) {
1678                 OPJ_S(i) -= (OPJ_D_(i - 1) + OPJ_D_(i) + 2) >> 2;
1679             }
1680             for (i = win_h_x0; i < win_h_x1; i++) {
1681                 OPJ_D(i) += (OPJ_S_(i) + OPJ_S_(i + 1)) >> 1;
1682             }
1683             but the compiler doesn't manage to unroll it to avoid bound
1684             checking in OPJ_S_ and OPJ_D_ macros
1685             */
1686
1687             i = win_l_x0;
1688             if (i < win_l_x1) {
1689                 OPJ_INT32 i_max;
1690
1691                 /* Left-most case */
1692                 for (off = 0; off < 4; off++) {
1693                     OPJ_S_off(i, off) -= (OPJ_D__off(i - 1, off) + OPJ_D__off(i, off) + 2) >> 2;
1694                 }
1695                 i ++;
1696
1697                 i_max = win_l_x1;
1698                 if (i_max > dn) {
1699                     i_max = dn;
1700                 }
1701
1702 #ifdef __SSE2__
1703                 if (i + 1 < i_max) {
1704                     const __m128i two = _mm_set1_epi32(2);
1705                     __m128i Dm1 = _mm_load_si128((__m128i * const)(a + 4 + (i - 1) * 8));
1706                     for (; i + 1 < i_max; i += 2) {
1707                         /* No bound checking */
1708                         __m128i S = _mm_load_si128((__m128i * const)(a + i * 8));
1709                         __m128i D = _mm_load_si128((__m128i * const)(a + 4 + i * 8));
1710                         __m128i S1 = _mm_load_si128((__m128i * const)(a + (i + 1) * 8));
1711                         __m128i D1 = _mm_load_si128((__m128i * const)(a + 4 + (i + 1) * 8));
1712                         S = _mm_sub_epi32(S,
1713                                           _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(Dm1, D), two), 2));
1714                         S1 = _mm_sub_epi32(S1,
1715                                            _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(D, D1), two), 2));
1716                         _mm_store_si128((__m128i*)(a + i * 8), S);
1717                         _mm_store_si128((__m128i*)(a + (i + 1) * 8), S1);
1718                         Dm1 = D1;
1719                     }
1720                 }
1721 #endif
1722
1723                 for (; i < i_max; i++) {
1724                     /* No bound checking */
1725                     for (off = 0; off < 4; off++) {
1726                         OPJ_S_off(i, off) -= (OPJ_D_off(i - 1, off) + OPJ_D_off(i, off) + 2) >> 2;
1727                     }
1728                 }
1729                 for (; i < win_l_x1; i++) {
1730                     /* Right-most case */
1731                     for (off = 0; off < 4; off++) {
1732                         OPJ_S_off(i, off) -= (OPJ_D__off(i - 1, off) + OPJ_D__off(i, off) + 2) >> 2;
1733                     }
1734                 }
1735             }
1736
1737             i = win_h_x0;
1738             if (i < win_h_x1) {
1739                 OPJ_INT32 i_max = win_h_x1;
1740                 if (i_max >= sn) {
1741                     i_max = sn - 1;
1742                 }
1743
1744 #ifdef __SSE2__
1745                 if (i + 1 < i_max) {
1746                     __m128i S =  _mm_load_si128((__m128i * const)(a + i * 8));
1747                     for (; i + 1 < i_max; i += 2) {
1748                         /* No bound checking */
1749                         __m128i D = _mm_load_si128((__m128i * const)(a + 4 + i * 8));
1750                         __m128i S1 = _mm_load_si128((__m128i * const)(a + (i + 1) * 8));
1751                         __m128i D1 = _mm_load_si128((__m128i * const)(a + 4 + (i + 1) * 8));
1752                         __m128i S2 = _mm_load_si128((__m128i * const)(a + (i + 2) * 8));
1753                         D = _mm_add_epi32(D, _mm_srai_epi32(_mm_add_epi32(S, S1), 1));
1754                         D1 = _mm_add_epi32(D1, _mm_srai_epi32(_mm_add_epi32(S1, S2), 1));
1755                         _mm_store_si128((__m128i*)(a + 4 + i * 8), D);
1756                         _mm_store_si128((__m128i*)(a + 4 + (i + 1) * 8), D1);
1757                         S = S2;
1758                     }
1759                 }
1760 #endif
1761
1762                 for (; i < i_max; i++) {
1763                     /* No bound checking */
1764                     for (off = 0; off < 4; off++) {
1765                         OPJ_D_off(i, off) += (OPJ_S_off(i, off) + OPJ_S_off(i + 1, off)) >> 1;
1766                     }
1767                 }
1768                 for (; i < win_h_x1; i++) {
1769                     /* Right-most case */
1770                     for (off = 0; off < 4; off++) {
1771                         OPJ_D_off(i, off) += (OPJ_S__off(i, off) + OPJ_S__off(i + 1, off)) >> 1;
1772                     }
1773                 }
1774             }
1775         }
1776     } else {
1777         if (!sn  && dn == 1) {        /* NEW :  CASE ONE ELEMENT */
1778             for (off = 0; off < 4; off++) {
1779                 OPJ_S_off(0, off) /= 2;
1780             }
1781         } else {
1782             for (i = win_l_x0; i < win_l_x1; i++) {
1783                 for (off = 0; off < 4; off++) {
1784                     OPJ_D_off(i, off) -= (OPJ_SS__off(i, off) + OPJ_SS__off(i + 1, off) + 2) >> 2;
1785                 }
1786             }
1787             for (i = win_h_x0; i < win_h_x1; i++) {
1788                 for (off = 0; off < 4; off++) {
1789                     OPJ_S_off(i, off) += (OPJ_DD__off(i, off) + OPJ_DD__off(i - 1, off)) >> 1;
1790                 }
1791             }
1792         }
1793     }
1794 }
1795
1796 static void opj_dwt_get_band_coordinates(opj_tcd_tilecomp_t* tilec,
1797         OPJ_UINT32 resno,
1798         OPJ_UINT32 bandno,
1799         OPJ_UINT32 tcx0,
1800         OPJ_UINT32 tcy0,
1801         OPJ_UINT32 tcx1,
1802         OPJ_UINT32 tcy1,
1803         OPJ_UINT32* tbx0,
1804         OPJ_UINT32* tby0,
1805         OPJ_UINT32* tbx1,
1806         OPJ_UINT32* tby1)
1807 {
1808     /* Compute number of decomposition for this band. See table F-1 */
1809     OPJ_UINT32 nb = (resno == 0) ?
1810                     tilec->numresolutions - 1 :
1811                     tilec->numresolutions - resno;
1812     /* Map above tile-based coordinates to sub-band-based coordinates per */
1813     /* equation B-15 of the standard */
1814     OPJ_UINT32 x0b = bandno & 1;
1815     OPJ_UINT32 y0b = bandno >> 1;
1816     if (tbx0) {
1817         *tbx0 = (nb == 0) ? tcx0 :
1818                 (tcx0 <= (1U << (nb - 1)) * x0b) ? 0 :
1819                 opj_uint_ceildivpow2(tcx0 - (1U << (nb - 1)) * x0b, nb);
1820     }
1821     if (tby0) {
1822         *tby0 = (nb == 0) ? tcy0 :
1823                 (tcy0 <= (1U << (nb - 1)) * y0b) ? 0 :
1824                 opj_uint_ceildivpow2(tcy0 - (1U << (nb - 1)) * y0b, nb);
1825     }
1826     if (tbx1) {
1827         *tbx1 = (nb == 0) ? tcx1 :
1828                 (tcx1 <= (1U << (nb - 1)) * x0b) ? 0 :
1829                 opj_uint_ceildivpow2(tcx1 - (1U << (nb - 1)) * x0b, nb);
1830     }
1831     if (tby1) {
1832         *tby1 = (nb == 0) ? tcy1 :
1833                 (tcy1 <= (1U << (nb - 1)) * y0b) ? 0 :
1834                 opj_uint_ceildivpow2(tcy1 - (1U << (nb - 1)) * y0b, nb);
1835     }
1836 }
1837
1838 static void opj_dwt_segment_grow(OPJ_UINT32 filter_width,
1839                                  OPJ_UINT32 max_size,
1840                                  OPJ_UINT32* start,
1841                                  OPJ_UINT32* end)
1842 {
1843     *start = opj_uint_subs(*start, filter_width);
1844     *end = opj_uint_adds(*end, filter_width);
1845     *end = opj_uint_min(*end, max_size);
1846 }
1847
1848
1849 static opj_sparse_array_int32_t* opj_dwt_init_sparse_array(
1850     opj_tcd_tilecomp_t* tilec,
1851     OPJ_UINT32 numres)
1852 {
1853     opj_tcd_resolution_t* tr_max = &(tilec->resolutions[numres - 1]);
1854     OPJ_UINT32 w = (OPJ_UINT32)(tr_max->x1 - tr_max->x0);
1855     OPJ_UINT32 h = (OPJ_UINT32)(tr_max->y1 - tr_max->y0);
1856     OPJ_UINT32 resno, bandno, precno, cblkno;
1857     opj_sparse_array_int32_t* sa = opj_sparse_array_int32_create(
1858                                        w, h, opj_uint_min(w, 64), opj_uint_min(h, 64));
1859     if (sa == NULL) {
1860         return NULL;
1861     }
1862
1863     for (resno = 0; resno < numres; ++resno) {
1864         opj_tcd_resolution_t* res = &tilec->resolutions[resno];
1865
1866         for (bandno = 0; bandno < res->numbands; ++bandno) {
1867             opj_tcd_band_t* band = &res->bands[bandno];
1868
1869             for (precno = 0; precno < res->pw * res->ph; ++precno) {
1870                 opj_tcd_precinct_t* precinct = &band->precincts[precno];
1871                 for (cblkno = 0; cblkno < precinct->cw * precinct->ch; ++cblkno) {
1872                     opj_tcd_cblk_dec_t* cblk = &precinct->cblks.dec[cblkno];
1873                     if (cblk->decoded_data != NULL) {
1874                         OPJ_UINT32 x = (OPJ_UINT32)(cblk->x0 - band->x0);
1875                         OPJ_UINT32 y = (OPJ_UINT32)(cblk->y0 - band->y0);
1876                         OPJ_UINT32 cblk_w = (OPJ_UINT32)(cblk->x1 - cblk->x0);
1877                         OPJ_UINT32 cblk_h = (OPJ_UINT32)(cblk->y1 - cblk->y0);
1878
1879                         if (band->bandno & 1) {
1880                             opj_tcd_resolution_t* pres = &tilec->resolutions[resno - 1];
1881                             x += (OPJ_UINT32)(pres->x1 - pres->x0);
1882                         }
1883                         if (band->bandno & 2) {
1884                             opj_tcd_resolution_t* pres = &tilec->resolutions[resno - 1];
1885                             y += (OPJ_UINT32)(pres->y1 - pres->y0);
1886                         }
1887
1888                         if (!opj_sparse_array_int32_write(sa, x, y,
1889                                                           x + cblk_w, y + cblk_h,
1890                                                           cblk->decoded_data,
1891                                                           1, cblk_w, OPJ_TRUE)) {
1892                             opj_sparse_array_int32_free(sa);
1893                             return NULL;
1894                         }
1895                     }
1896                 }
1897             }
1898         }
1899     }
1900
1901     return sa;
1902 }
1903
1904
1905 static OPJ_BOOL opj_dwt_decode_partial_tile(
1906     opj_tcd_tilecomp_t* tilec,
1907     OPJ_UINT32 numres)
1908 {
1909     opj_sparse_array_int32_t* sa;
1910     opj_dwt_t h;
1911     opj_dwt_t v;
1912     OPJ_UINT32 resno;
1913     /* This value matches the maximum left/right extension given in tables */
1914     /* F.2 and F.3 of the standard. */
1915     const OPJ_UINT32 filter_width = 2U;
1916
1917     opj_tcd_resolution_t* tr = tilec->resolutions;
1918     opj_tcd_resolution_t* tr_max = &(tilec->resolutions[numres - 1]);
1919
1920     OPJ_UINT32 rw = (OPJ_UINT32)(tr->x1 -
1921                                  tr->x0);  /* width of the resolution level computed */
1922     OPJ_UINT32 rh = (OPJ_UINT32)(tr->y1 -
1923                                  tr->y0);  /* height of the resolution level computed */
1924
1925     OPJ_SIZE_T h_mem_size;
1926
1927     /* Compute the intersection of the area of interest, expressed in tile coordinates */
1928     /* with the tile coordinates */
1929     OPJ_UINT32 win_tcx0 = tilec->win_x0;
1930     OPJ_UINT32 win_tcy0 = tilec->win_y0;
1931     OPJ_UINT32 win_tcx1 = tilec->win_x1;
1932     OPJ_UINT32 win_tcy1 = tilec->win_y1;
1933
1934     if (tr_max->x0 == tr_max->x1 || tr_max->y0 == tr_max->y1) {
1935         return OPJ_TRUE;
1936     }
1937
1938     sa = opj_dwt_init_sparse_array(tilec, numres);
1939     if (sa == NULL) {
1940         return OPJ_FALSE;
1941     }
1942
1943     if (numres == 1U) {
1944         OPJ_BOOL ret = opj_sparse_array_int32_read(sa,
1945                        tr_max->win_x0 - (OPJ_UINT32)tr_max->x0,
1946                        tr_max->win_y0 - (OPJ_UINT32)tr_max->y0,
1947                        tr_max->win_x1 - (OPJ_UINT32)tr_max->x0,
1948                        tr_max->win_y1 - (OPJ_UINT32)tr_max->y0,
1949                        tilec->data_win,
1950                        1, tr_max->win_x1 - tr_max->win_x0,
1951                        OPJ_TRUE);
1952         assert(ret);
1953         OPJ_UNUSED(ret);
1954         opj_sparse_array_int32_free(sa);
1955         return OPJ_TRUE;
1956     }
1957     h_mem_size = opj_dwt_max_resolution(tr, numres);
1958     /* overflow check */
1959     /* in vertical pass, we process 4 columns at a time */
1960     if (h_mem_size > (SIZE_MAX / (4 * sizeof(OPJ_INT32)))) {
1961         /* FIXME event manager error callback */
1962         opj_sparse_array_int32_free(sa);
1963         return OPJ_FALSE;
1964     }
1965
1966     h_mem_size *= 4 * sizeof(OPJ_INT32);
1967     h.mem = (OPJ_INT32*)opj_aligned_32_malloc(h_mem_size);
1968     if (! h.mem) {
1969         /* FIXME event manager error callback */
1970         opj_sparse_array_int32_free(sa);
1971         return OPJ_FALSE;
1972     }
1973
1974     v.mem = h.mem;
1975
1976     for (resno = 1; resno < numres; resno ++) {
1977         OPJ_UINT32 i, j;
1978         /* Window of interest subband-based coordinates */
1979         OPJ_UINT32 win_ll_x0, win_ll_y0, win_ll_x1, win_ll_y1;
1980         OPJ_UINT32 win_hl_x0, win_hl_x1;
1981         OPJ_UINT32 win_lh_y0, win_lh_y1;
1982         /* Window of interest tile-resolution-based coordinates */
1983         OPJ_UINT32 win_tr_x0, win_tr_x1, win_tr_y0, win_tr_y1;
1984         /* Tile-resolution subband-based coordinates */
1985         OPJ_UINT32 tr_ll_x0, tr_ll_y0, tr_hl_x0, tr_lh_y0;
1986
1987         ++tr;
1988
1989         h.sn = (OPJ_INT32)rw;
1990         v.sn = (OPJ_INT32)rh;
1991
1992         rw = (OPJ_UINT32)(tr->x1 - tr->x0);
1993         rh = (OPJ_UINT32)(tr->y1 - tr->y0);
1994
1995         h.dn = (OPJ_INT32)(rw - (OPJ_UINT32)h.sn);
1996         h.cas = tr->x0 % 2;
1997
1998         v.dn = (OPJ_INT32)(rh - (OPJ_UINT32)v.sn);
1999         v.cas = tr->y0 % 2;
2000
2001         /* Get the subband coordinates for the window of interest */
2002         /* LL band */
2003         opj_dwt_get_band_coordinates(tilec, resno, 0,
2004                                      win_tcx0, win_tcy0, win_tcx1, win_tcy1,
2005                                      &win_ll_x0, &win_ll_y0,
2006                                      &win_ll_x1, &win_ll_y1);
2007
2008         /* HL band */
2009         opj_dwt_get_band_coordinates(tilec, resno, 1,
2010                                      win_tcx0, win_tcy0, win_tcx1, win_tcy1,
2011                                      &win_hl_x0, NULL, &win_hl_x1, NULL);
2012
2013         /* LH band */
2014         opj_dwt_get_band_coordinates(tilec, resno, 2,
2015                                      win_tcx0, win_tcy0, win_tcx1, win_tcy1,
2016                                      NULL, &win_lh_y0, NULL, &win_lh_y1);
2017
2018         /* Beware: band index for non-LL0 resolution are 0=HL, 1=LH and 2=HH */
2019         tr_ll_x0 = (OPJ_UINT32)tr->bands[1].x0;
2020         tr_ll_y0 = (OPJ_UINT32)tr->bands[0].y0;
2021         tr_hl_x0 = (OPJ_UINT32)tr->bands[0].x0;
2022         tr_lh_y0 = (OPJ_UINT32)tr->bands[1].y0;
2023
2024         /* Substract the origin of the bands for this tile, to the subwindow */
2025         /* of interest band coordinates, so as to get them relative to the */
2026         /* tile */
2027         win_ll_x0 = opj_uint_subs(win_ll_x0, tr_ll_x0);
2028         win_ll_y0 = opj_uint_subs(win_ll_y0, tr_ll_y0);
2029         win_ll_x1 = opj_uint_subs(win_ll_x1, tr_ll_x0);
2030         win_ll_y1 = opj_uint_subs(win_ll_y1, tr_ll_y0);
2031         win_hl_x0 = opj_uint_subs(win_hl_x0, tr_hl_x0);
2032         win_hl_x1 = opj_uint_subs(win_hl_x1, tr_hl_x0);
2033         win_lh_y0 = opj_uint_subs(win_lh_y0, tr_lh_y0);
2034         win_lh_y1 = opj_uint_subs(win_lh_y1, tr_lh_y0);
2035
2036         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)h.sn, &win_ll_x0, &win_ll_x1);
2037         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)h.dn, &win_hl_x0, &win_hl_x1);
2038
2039         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)v.sn, &win_ll_y0, &win_ll_y1);
2040         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)v.dn, &win_lh_y0, &win_lh_y1);
2041
2042         /* Compute the tile-resolution-based coordinates for the window of interest */
2043         if (h.cas == 0) {
2044             win_tr_x0 = opj_uint_min(2 * win_ll_x0, 2 * win_hl_x0 + 1);
2045             win_tr_x1 = opj_uint_min(opj_uint_max(2 * win_ll_x1, 2 * win_hl_x1 + 1), rw);
2046         } else {
2047             win_tr_x0 = opj_uint_min(2 * win_hl_x0, 2 * win_ll_x0 + 1);
2048             win_tr_x1 = opj_uint_min(opj_uint_max(2 * win_hl_x1, 2 * win_ll_x1 + 1), rw);
2049         }
2050
2051         if (v.cas == 0) {
2052             win_tr_y0 = opj_uint_min(2 * win_ll_y0, 2 * win_lh_y0 + 1);
2053             win_tr_y1 = opj_uint_min(opj_uint_max(2 * win_ll_y1, 2 * win_lh_y1 + 1), rh);
2054         } else {
2055             win_tr_y0 = opj_uint_min(2 * win_lh_y0, 2 * win_ll_y0 + 1);
2056             win_tr_y1 = opj_uint_min(opj_uint_max(2 * win_lh_y1, 2 * win_ll_y1 + 1), rh);
2057         }
2058
2059         for (j = 0; j < rh; ++j) {
2060             if ((j >= win_ll_y0 && j < win_ll_y1) ||
2061                     (j >= win_lh_y0 + (OPJ_UINT32)v.sn && j < win_lh_y1 + (OPJ_UINT32)v.sn)) {
2062
2063                 /* Avoids dwt.c:1584:44 (in opj_dwt_decode_partial_1): runtime error: */
2064                 /* signed integer overflow: -1094795586 + -1094795586 cannot be represented in type 'int' */
2065                 /* on opj_decompress -i  ../../openjpeg/MAPA.jp2 -o out.tif -d 0,0,256,256 */
2066                 /* This is less extreme than memsetting the whole buffer to 0 */
2067                 /* although we could potentially do better with better handling of edge conditions */
2068                 if (win_tr_x1 >= 1 && win_tr_x1 < rw) {
2069                     h.mem[win_tr_x1 - 1] = 0;
2070                 }
2071                 if (win_tr_x1 < rw) {
2072                     h.mem[win_tr_x1] = 0;
2073                 }
2074
2075                 opj_dwt_interleave_partial_h(h.mem,
2076                                              h.cas,
2077                                              sa,
2078                                              j,
2079                                              (OPJ_UINT32)h.sn,
2080                                              win_ll_x0,
2081                                              win_ll_x1,
2082                                              win_hl_x0,
2083                                              win_hl_x1);
2084                 opj_dwt_decode_partial_1(h.mem, h.dn, h.sn, h.cas,
2085                                          (OPJ_INT32)win_ll_x0,
2086                                          (OPJ_INT32)win_ll_x1,
2087                                          (OPJ_INT32)win_hl_x0,
2088                                          (OPJ_INT32)win_hl_x1);
2089                 if (!opj_sparse_array_int32_write(sa,
2090                                                   win_tr_x0, j,
2091                                                   win_tr_x1, j + 1,
2092                                                   h.mem + win_tr_x0,
2093                                                   1, 0, OPJ_TRUE)) {
2094                     /* FIXME event manager error callback */
2095                     opj_sparse_array_int32_free(sa);
2096                     opj_aligned_free(h.mem);
2097                     return OPJ_FALSE;
2098                 }
2099             }
2100         }
2101
2102         for (i = win_tr_x0; i < win_tr_x1;) {
2103             OPJ_UINT32 nb_cols = opj_uint_min(4U, win_tr_x1 - i);
2104             opj_dwt_interleave_partial_v(v.mem,
2105                                          v.cas,
2106                                          sa,
2107                                          i,
2108                                          nb_cols,
2109                                          (OPJ_UINT32)v.sn,
2110                                          win_ll_y0,
2111                                          win_ll_y1,
2112                                          win_lh_y0,
2113                                          win_lh_y1);
2114             opj_dwt_decode_partial_1_parallel(v.mem, nb_cols, v.dn, v.sn, v.cas,
2115                                               (OPJ_INT32)win_ll_y0,
2116                                               (OPJ_INT32)win_ll_y1,
2117                                               (OPJ_INT32)win_lh_y0,
2118                                               (OPJ_INT32)win_lh_y1);
2119             if (!opj_sparse_array_int32_write(sa,
2120                                               i, win_tr_y0,
2121                                               i + nb_cols, win_tr_y1,
2122                                               v.mem + 4 * win_tr_y0,
2123                                               1, 4, OPJ_TRUE)) {
2124                 /* FIXME event manager error callback */
2125                 opj_sparse_array_int32_free(sa);
2126                 opj_aligned_free(h.mem);
2127                 return OPJ_FALSE;
2128             }
2129
2130             i += nb_cols;
2131         }
2132     }
2133     opj_aligned_free(h.mem);
2134
2135     {
2136         OPJ_BOOL ret = opj_sparse_array_int32_read(sa,
2137                        tr_max->win_x0 - (OPJ_UINT32)tr_max->x0,
2138                        tr_max->win_y0 - (OPJ_UINT32)tr_max->y0,
2139                        tr_max->win_x1 - (OPJ_UINT32)tr_max->x0,
2140                        tr_max->win_y1 - (OPJ_UINT32)tr_max->y0,
2141                        tilec->data_win,
2142                        1, tr_max->win_x1 - tr_max->win_x0,
2143                        OPJ_TRUE);
2144         assert(ret);
2145         OPJ_UNUSED(ret);
2146     }
2147     opj_sparse_array_int32_free(sa);
2148     return OPJ_TRUE;
2149 }
2150
2151 static void opj_v4dwt_interleave_h(opj_v4dwt_t* OPJ_RESTRICT dwt,
2152                                    OPJ_FLOAT32* OPJ_RESTRICT a,
2153                                    OPJ_UINT32 width,
2154                                    OPJ_UINT32 remaining_height)
2155 {
2156     OPJ_FLOAT32* OPJ_RESTRICT bi = (OPJ_FLOAT32*)(dwt->wavelet + dwt->cas);
2157     OPJ_UINT32 i, k;
2158     OPJ_UINT32 x0 = dwt->win_l_x0;
2159     OPJ_UINT32 x1 = dwt->win_l_x1;
2160
2161     for (k = 0; k < 2; ++k) {
2162         if (remaining_height >= 4 && ((OPJ_SIZE_T) a & 0x0f) == 0 &&
2163                 ((OPJ_SIZE_T) bi & 0x0f) == 0 && (width & 0x0f) == 0) {
2164             /* Fast code path */
2165             for (i = x0; i < x1; ++i) {
2166                 OPJ_UINT32 j = i;
2167                 bi[i * 8    ] = a[j];
2168                 j += width;
2169                 bi[i * 8 + 1] = a[j];
2170                 j += width;
2171                 bi[i * 8 + 2] = a[j];
2172                 j += width;
2173                 bi[i * 8 + 3] = a[j];
2174             }
2175         } else {
2176             /* Slow code path */
2177             for (i = x0; i < x1; ++i) {
2178                 OPJ_UINT32 j = i;
2179                 bi[i * 8    ] = a[j];
2180                 j += width;
2181                 if (remaining_height == 1) {
2182                     continue;
2183                 }
2184                 bi[i * 8 + 1] = a[j];
2185                 j += width;
2186                 if (remaining_height == 2) {
2187                     continue;
2188                 }
2189                 bi[i * 8 + 2] = a[j];
2190                 j += width;
2191                 if (remaining_height == 3) {
2192                     continue;
2193                 }
2194                 bi[i * 8 + 3] = a[j]; /* This one*/
2195             }
2196         }
2197
2198         bi = (OPJ_FLOAT32*)(dwt->wavelet + 1 - dwt->cas);
2199         a += dwt->sn;
2200         x0 = dwt->win_h_x0;
2201         x1 = dwt->win_h_x1;
2202     }
2203 }
2204
2205 static void opj_v4dwt_interleave_partial_h(opj_v4dwt_t* dwt,
2206         opj_sparse_array_int32_t* sa,
2207         OPJ_UINT32 sa_line,
2208         OPJ_UINT32 remaining_height)
2209 {
2210     OPJ_UINT32 i;
2211     for (i = 0; i < remaining_height; i++) {
2212         OPJ_BOOL ret;
2213         ret = opj_sparse_array_int32_read(sa,
2214                                           dwt->win_l_x0, sa_line + i,
2215                                           dwt->win_l_x1, sa_line + i + 1,
2216                                           /* Nasty cast from float* to int32* */
2217                                           (OPJ_INT32*)(dwt->wavelet + dwt->cas + 2 * dwt->win_l_x0) + i,
2218                                           8, 0, OPJ_TRUE);
2219         assert(ret);
2220         ret = opj_sparse_array_int32_read(sa,
2221                                           (OPJ_UINT32)dwt->sn + dwt->win_h_x0, sa_line + i,
2222                                           (OPJ_UINT32)dwt->sn + dwt->win_h_x1, sa_line + i + 1,
2223                                           /* Nasty cast from float* to int32* */
2224                                           (OPJ_INT32*)(dwt->wavelet + 1 - dwt->cas + 2 * dwt->win_h_x0) + i,
2225                                           8, 0, OPJ_TRUE);
2226         assert(ret);
2227         OPJ_UNUSED(ret);
2228     }
2229 }
2230
2231 static void opj_v4dwt_interleave_v(opj_v4dwt_t* OPJ_RESTRICT dwt,
2232                                    OPJ_FLOAT32* OPJ_RESTRICT a,
2233                                    OPJ_UINT32 width,
2234                                    OPJ_UINT32 nb_elts_read)
2235 {
2236     opj_v4_t* OPJ_RESTRICT bi = dwt->wavelet + dwt->cas;
2237     OPJ_UINT32 i;
2238
2239     for (i = dwt->win_l_x0; i < dwt->win_l_x1; ++i) {
2240         memcpy(&bi[i * 2], &a[i * (OPJ_SIZE_T)width],
2241                (OPJ_SIZE_T)nb_elts_read * sizeof(OPJ_FLOAT32));
2242     }
2243
2244     a += (OPJ_UINT32)dwt->sn * (OPJ_SIZE_T)width;
2245     bi = dwt->wavelet + 1 - dwt->cas;
2246
2247     for (i = dwt->win_h_x0; i < dwt->win_h_x1; ++i) {
2248         memcpy(&bi[i * 2], &a[i * (OPJ_SIZE_T)width],
2249                (OPJ_SIZE_T)nb_elts_read * sizeof(OPJ_FLOAT32));
2250     }
2251 }
2252
2253 static void opj_v4dwt_interleave_partial_v(opj_v4dwt_t* OPJ_RESTRICT dwt,
2254         opj_sparse_array_int32_t* sa,
2255         OPJ_UINT32 sa_col,
2256         OPJ_UINT32 nb_elts_read)
2257 {
2258     OPJ_BOOL ret;
2259     ret = opj_sparse_array_int32_read(sa,
2260                                       sa_col, dwt->win_l_x0,
2261                                       sa_col + nb_elts_read, dwt->win_l_x1,
2262                                       (OPJ_INT32*)(dwt->wavelet + dwt->cas + 2 * dwt->win_l_x0),
2263                                       1, 8, OPJ_TRUE);
2264     assert(ret);
2265     ret = opj_sparse_array_int32_read(sa,
2266                                       sa_col, (OPJ_UINT32)dwt->sn + dwt->win_h_x0,
2267                                       sa_col + nb_elts_read, (OPJ_UINT32)dwt->sn + dwt->win_h_x1,
2268                                       (OPJ_INT32*)(dwt->wavelet + 1 - dwt->cas + 2 * dwt->win_h_x0),
2269                                       1, 8, OPJ_TRUE);
2270     assert(ret);
2271     OPJ_UNUSED(ret);
2272 }
2273
2274 #ifdef __SSE__
2275
2276 static void opj_v4dwt_decode_step1_sse(opj_v4_t* w,
2277                                        OPJ_UINT32 start,
2278                                        OPJ_UINT32 end,
2279                                        const __m128 c)
2280 {
2281     __m128* OPJ_RESTRICT vw = (__m128*) w;
2282     OPJ_UINT32 i;
2283     /* 4x unrolled loop */
2284     vw += 2 * start;
2285     for (i = start; i + 3 < end; i += 4, vw += 8) {
2286         __m128 xmm0 = _mm_mul_ps(vw[0], c);
2287         __m128 xmm2 = _mm_mul_ps(vw[2], c);
2288         __m128 xmm4 = _mm_mul_ps(vw[4], c);
2289         __m128 xmm6 = _mm_mul_ps(vw[6], c);
2290         vw[0] = xmm0;
2291         vw[2] = xmm2;
2292         vw[4] = xmm4;
2293         vw[6] = xmm6;
2294     }
2295     for (; i < end; ++i, vw += 2) {
2296         vw[0] = _mm_mul_ps(vw[0], c);
2297     }
2298 }
2299
2300 static void opj_v4dwt_decode_step2_sse(opj_v4_t* l, opj_v4_t* w,
2301                                        OPJ_UINT32 start,
2302                                        OPJ_UINT32 end,
2303                                        OPJ_UINT32 m,
2304                                        __m128 c)
2305 {
2306     __m128* OPJ_RESTRICT vl = (__m128*) l;
2307     __m128* OPJ_RESTRICT vw = (__m128*) w;
2308     OPJ_UINT32 i;
2309     OPJ_UINT32 imax = opj_uint_min(end, m);
2310     __m128 tmp1, tmp2, tmp3;
2311     if (start == 0) {
2312         tmp1 = vl[0];
2313     } else {
2314         vw += start * 2;
2315         tmp1 = vw[-3];
2316     }
2317
2318     i = start;
2319
2320     /* 4x loop unrolling */
2321     for (; i + 3 < imax; i += 4) {
2322         __m128 tmp4, tmp5, tmp6, tmp7, tmp8, tmp9;
2323         tmp2 = vw[-1];
2324         tmp3 = vw[ 0];
2325         tmp4 = vw[ 1];
2326         tmp5 = vw[ 2];
2327         tmp6 = vw[ 3];
2328         tmp7 = vw[ 4];
2329         tmp8 = vw[ 5];
2330         tmp9 = vw[ 6];
2331         vw[-1] = _mm_add_ps(tmp2, _mm_mul_ps(_mm_add_ps(tmp1, tmp3), c));
2332         vw[ 1] = _mm_add_ps(tmp4, _mm_mul_ps(_mm_add_ps(tmp3, tmp5), c));
2333         vw[ 3] = _mm_add_ps(tmp6, _mm_mul_ps(_mm_add_ps(tmp5, tmp7), c));
2334         vw[ 5] = _mm_add_ps(tmp8, _mm_mul_ps(_mm_add_ps(tmp7, tmp9), c));
2335         tmp1 = tmp9;
2336         vw += 8;
2337     }
2338
2339     for (; i < imax; ++i) {
2340         tmp2 = vw[-1];
2341         tmp3 = vw[ 0];
2342         vw[-1] = _mm_add_ps(tmp2, _mm_mul_ps(_mm_add_ps(tmp1, tmp3), c));
2343         tmp1 = tmp3;
2344         vw += 2;
2345     }
2346     if (m < end) {
2347         assert(m + 1 == end);
2348         c = _mm_add_ps(c, c);
2349         c = _mm_mul_ps(c, vw[-2]);
2350         vw[-1] = _mm_add_ps(vw[-1], c);
2351     }
2352 }
2353
2354 #else
2355
2356 static void opj_v4dwt_decode_step1(opj_v4_t* w,
2357                                    OPJ_UINT32 start,
2358                                    OPJ_UINT32 end,
2359                                    const OPJ_FLOAT32 c)
2360 {
2361     OPJ_FLOAT32* OPJ_RESTRICT fw = (OPJ_FLOAT32*) w;
2362     OPJ_UINT32 i;
2363     for (i = start; i < end; ++i) {
2364         OPJ_FLOAT32 tmp1 = fw[i * 8    ];
2365         OPJ_FLOAT32 tmp2 = fw[i * 8 + 1];
2366         OPJ_FLOAT32 tmp3 = fw[i * 8 + 2];
2367         OPJ_FLOAT32 tmp4 = fw[i * 8 + 3];
2368         fw[i * 8    ] = tmp1 * c;
2369         fw[i * 8 + 1] = tmp2 * c;
2370         fw[i * 8 + 2] = tmp3 * c;
2371         fw[i * 8 + 3] = tmp4 * c;
2372     }
2373 }
2374
2375 static void opj_v4dwt_decode_step2(opj_v4_t* l, opj_v4_t* w,
2376                                    OPJ_UINT32 start,
2377                                    OPJ_UINT32 end,
2378                                    OPJ_UINT32 m,
2379                                    OPJ_FLOAT32 c)
2380 {
2381     OPJ_FLOAT32* fl = (OPJ_FLOAT32*) l;
2382     OPJ_FLOAT32* fw = (OPJ_FLOAT32*) w;
2383     OPJ_UINT32 i;
2384     OPJ_UINT32 imax = opj_uint_min(end, m);
2385     if (start > 0) {
2386         fw += 8 * start;
2387         fl = fw - 8;
2388     }
2389     for (i = start; i < imax; ++i) {
2390         OPJ_FLOAT32 tmp1_1 = fl[0];
2391         OPJ_FLOAT32 tmp1_2 = fl[1];
2392         OPJ_FLOAT32 tmp1_3 = fl[2];
2393         OPJ_FLOAT32 tmp1_4 = fl[3];
2394         OPJ_FLOAT32 tmp2_1 = fw[-4];
2395         OPJ_FLOAT32 tmp2_2 = fw[-3];
2396         OPJ_FLOAT32 tmp2_3 = fw[-2];
2397         OPJ_FLOAT32 tmp2_4 = fw[-1];
2398         OPJ_FLOAT32 tmp3_1 = fw[0];
2399         OPJ_FLOAT32 tmp3_2 = fw[1];
2400         OPJ_FLOAT32 tmp3_3 = fw[2];
2401         OPJ_FLOAT32 tmp3_4 = fw[3];
2402         fw[-4] = tmp2_1 + ((tmp1_1 + tmp3_1) * c);
2403         fw[-3] = tmp2_2 + ((tmp1_2 + tmp3_2) * c);
2404         fw[-2] = tmp2_3 + ((tmp1_3 + tmp3_3) * c);
2405         fw[-1] = tmp2_4 + ((tmp1_4 + tmp3_4) * c);
2406         fl = fw;
2407         fw += 8;
2408     }
2409     if (m < end) {
2410         assert(m + 1 == end);
2411         c += c;
2412         fw[-4] = fw[-4] + fl[0] * c;
2413         fw[-3] = fw[-3] + fl[1] * c;
2414         fw[-2] = fw[-2] + fl[2] * c;
2415         fw[-1] = fw[-1] + fl[3] * c;
2416     }
2417 }
2418
2419 #endif
2420
2421 /* <summary>                             */
2422 /* Inverse 9-7 wavelet transform in 1-D. */
2423 /* </summary>                            */
2424 static void opj_v4dwt_decode(opj_v4dwt_t* OPJ_RESTRICT dwt)
2425 {
2426     OPJ_INT32 a, b;
2427     if (dwt->cas == 0) {
2428         if (!((dwt->dn > 0) || (dwt->sn > 1))) {
2429             return;
2430         }
2431         a = 0;
2432         b = 1;
2433     } else {
2434         if (!((dwt->sn > 0) || (dwt->dn > 1))) {
2435             return;
2436         }
2437         a = 1;
2438         b = 0;
2439     }
2440 #ifdef __SSE__
2441     opj_v4dwt_decode_step1_sse(dwt->wavelet + a, dwt->win_l_x0, dwt->win_l_x1,
2442                                _mm_set1_ps(opj_K));
2443     opj_v4dwt_decode_step1_sse(dwt->wavelet + b, dwt->win_h_x0, dwt->win_h_x1,
2444                                _mm_set1_ps(opj_c13318));
2445     opj_v4dwt_decode_step2_sse(dwt->wavelet + b, dwt->wavelet + a + 1,
2446                                dwt->win_l_x0, dwt->win_l_x1,
2447                                (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
2448                                _mm_set1_ps(opj_dwt_delta));
2449     opj_v4dwt_decode_step2_sse(dwt->wavelet + a, dwt->wavelet + b + 1,
2450                                dwt->win_h_x0, dwt->win_h_x1,
2451                                (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
2452                                _mm_set1_ps(opj_dwt_gamma));
2453     opj_v4dwt_decode_step2_sse(dwt->wavelet + b, dwt->wavelet + a + 1,
2454                                dwt->win_l_x0, dwt->win_l_x1,
2455                                (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
2456                                _mm_set1_ps(opj_dwt_beta));
2457     opj_v4dwt_decode_step2_sse(dwt->wavelet + a, dwt->wavelet + b + 1,
2458                                dwt->win_h_x0, dwt->win_h_x1,
2459                                (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
2460                                _mm_set1_ps(opj_dwt_alpha));
2461 #else
2462     opj_v4dwt_decode_step1(dwt->wavelet + a, dwt->win_l_x0, dwt->win_l_x1,
2463                            opj_K);
2464     opj_v4dwt_decode_step1(dwt->wavelet + b, dwt->win_h_x0, dwt->win_h_x1,
2465                            opj_c13318);
2466     opj_v4dwt_decode_step2(dwt->wavelet + b, dwt->wavelet + a + 1,
2467                            dwt->win_l_x0, dwt->win_l_x1,
2468                            (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
2469                            opj_dwt_delta);
2470     opj_v4dwt_decode_step2(dwt->wavelet + a, dwt->wavelet + b + 1,
2471                            dwt->win_h_x0, dwt->win_h_x1,
2472                            (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
2473                            opj_dwt_gamma);
2474     opj_v4dwt_decode_step2(dwt->wavelet + b, dwt->wavelet + a + 1,
2475                            dwt->win_l_x0, dwt->win_l_x1,
2476                            (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
2477                            opj_dwt_beta);
2478     opj_v4dwt_decode_step2(dwt->wavelet + a, dwt->wavelet + b + 1,
2479                            dwt->win_h_x0, dwt->win_h_x1,
2480                            (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
2481                            opj_dwt_alpha);
2482 #endif
2483 }
2484
2485
2486 /* <summary>                             */
2487 /* Inverse 9-7 wavelet transform in 2-D. */
2488 /* </summary>                            */
2489 static
2490 OPJ_BOOL opj_dwt_decode_tile_97(opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
2491                                 OPJ_UINT32 numres)
2492 {
2493     opj_v4dwt_t h;
2494     opj_v4dwt_t v;
2495
2496     opj_tcd_resolution_t* res = tilec->resolutions;
2497
2498     OPJ_UINT32 rw = (OPJ_UINT32)(res->x1 -
2499                                  res->x0);    /* width of the resolution level computed */
2500     OPJ_UINT32 rh = (OPJ_UINT32)(res->y1 -
2501                                  res->y0);    /* height of the resolution level computed */
2502
2503     OPJ_UINT32 w = (OPJ_UINT32)(tilec->resolutions[tilec->minimum_num_resolutions -
2504                                                                1].x1 -
2505                                 tilec->resolutions[tilec->minimum_num_resolutions - 1].x0);
2506
2507     OPJ_SIZE_T l_data_size;
2508
2509     l_data_size = opj_dwt_max_resolution(res, numres);
2510     /* overflow check */
2511     if (l_data_size > (SIZE_MAX - 5U)) {
2512         /* FIXME event manager error callback */
2513         return OPJ_FALSE;
2514     }
2515     l_data_size += 5U;
2516     /* overflow check */
2517     if (l_data_size > (SIZE_MAX / sizeof(opj_v4_t))) {
2518         /* FIXME event manager error callback */
2519         return OPJ_FALSE;
2520     }
2521     h.wavelet = (opj_v4_t*) opj_aligned_malloc(l_data_size * sizeof(opj_v4_t));
2522     if (!h.wavelet) {
2523         /* FIXME event manager error callback */
2524         return OPJ_FALSE;
2525     }
2526     v.wavelet = h.wavelet;
2527
2528     while (--numres) {
2529         OPJ_FLOAT32 * OPJ_RESTRICT aj = (OPJ_FLOAT32*) tilec->data;
2530         OPJ_UINT32 j;
2531
2532         h.sn = (OPJ_INT32)rw;
2533         v.sn = (OPJ_INT32)rh;
2534
2535         ++res;
2536
2537         rw = (OPJ_UINT32)(res->x1 -
2538                           res->x0);   /* width of the resolution level computed */
2539         rh = (OPJ_UINT32)(res->y1 -
2540                           res->y0);   /* height of the resolution level computed */
2541
2542         h.dn = (OPJ_INT32)(rw - (OPJ_UINT32)h.sn);
2543         h.cas = res->x0 % 2;
2544
2545         h.win_l_x0 = 0;
2546         h.win_l_x1 = (OPJ_UINT32)h.sn;
2547         h.win_h_x0 = 0;
2548         h.win_h_x1 = (OPJ_UINT32)h.dn;
2549         for (j = 0; j + 3 < rh; j += 4) {
2550             OPJ_UINT32 k;
2551             opj_v4dwt_interleave_h(&h, aj, w, rh - j);
2552             opj_v4dwt_decode(&h);
2553
2554             for (k = 0; k < rw; k++) {
2555                 aj[k      ] = h.wavelet[k].f[0];
2556                 aj[k + (OPJ_SIZE_T)w  ] = h.wavelet[k].f[1];
2557                 aj[k + (OPJ_SIZE_T)w * 2] = h.wavelet[k].f[2];
2558                 aj[k + (OPJ_SIZE_T)w * 3] = h.wavelet[k].f[3];
2559             }
2560
2561             aj += w * 4;
2562         }
2563
2564         if (j < rh) {
2565             OPJ_UINT32 k;
2566             opj_v4dwt_interleave_h(&h, aj, w, rh - j);
2567             opj_v4dwt_decode(&h);
2568             for (k = 0; k < rw; k++) {
2569                 switch (rh - j) {
2570                 case 3:
2571                     aj[k + (OPJ_SIZE_T)w * 2] = h.wavelet[k].f[2];
2572                 /* FALLTHRU */
2573                 case 2:
2574                     aj[k + (OPJ_SIZE_T)w  ] = h.wavelet[k].f[1];
2575                 /* FALLTHRU */
2576                 case 1:
2577                     aj[k] = h.wavelet[k].f[0];
2578                 }
2579             }
2580         }
2581
2582         v.dn = (OPJ_INT32)(rh - (OPJ_UINT32)v.sn);
2583         v.cas = res->y0 % 2;
2584         v.win_l_x0 = 0;
2585         v.win_l_x1 = (OPJ_UINT32)v.sn;
2586         v.win_h_x0 = 0;
2587         v.win_h_x1 = (OPJ_UINT32)v.dn;
2588
2589         aj = (OPJ_FLOAT32*) tilec->data;
2590         for (j = rw; j > 3; j -= 4) {
2591             OPJ_UINT32 k;
2592
2593             opj_v4dwt_interleave_v(&v, aj, w, 4);
2594             opj_v4dwt_decode(&v);
2595
2596             for (k = 0; k < rh; ++k) {
2597                 memcpy(&aj[k * (OPJ_SIZE_T)w], &v.wavelet[k], 4 * sizeof(OPJ_FLOAT32));
2598             }
2599             aj += 4;
2600         }
2601
2602         if (rw & 0x03) {
2603             OPJ_UINT32 k;
2604
2605             j = rw & 0x03;
2606
2607             opj_v4dwt_interleave_v(&v, aj, w, j);
2608             opj_v4dwt_decode(&v);
2609
2610             for (k = 0; k < rh; ++k) {
2611                 memcpy(&aj[k * (OPJ_SIZE_T)w], &v.wavelet[k],
2612                        (OPJ_SIZE_T)j * sizeof(OPJ_FLOAT32));
2613             }
2614         }
2615     }
2616
2617     opj_aligned_free(h.wavelet);
2618     return OPJ_TRUE;
2619 }
2620
2621 static
2622 OPJ_BOOL opj_dwt_decode_partial_97(opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
2623                                    OPJ_UINT32 numres)
2624 {
2625     opj_sparse_array_int32_t* sa;
2626     opj_v4dwt_t h;
2627     opj_v4dwt_t v;
2628     OPJ_UINT32 resno;
2629     /* This value matches the maximum left/right extension given in tables */
2630     /* F.2 and F.3 of the standard. Note: in opj_tcd_is_subband_area_of_interest() */
2631     /* we currently use 3. */
2632     const OPJ_UINT32 filter_width = 4U;
2633
2634     opj_tcd_resolution_t* tr = tilec->resolutions;
2635     opj_tcd_resolution_t* tr_max = &(tilec->resolutions[numres - 1]);
2636
2637     OPJ_UINT32 rw = (OPJ_UINT32)(tr->x1 -
2638                                  tr->x0);    /* width of the resolution level computed */
2639     OPJ_UINT32 rh = (OPJ_UINT32)(tr->y1 -
2640                                  tr->y0);    /* height of the resolution level computed */
2641
2642     OPJ_SIZE_T l_data_size;
2643
2644     /* Compute the intersection of the area of interest, expressed in tile coordinates */
2645     /* with the tile coordinates */
2646     OPJ_UINT32 win_tcx0 = tilec->win_x0;
2647     OPJ_UINT32 win_tcy0 = tilec->win_y0;
2648     OPJ_UINT32 win_tcx1 = tilec->win_x1;
2649     OPJ_UINT32 win_tcy1 = tilec->win_y1;
2650
2651     if (tr_max->x0 == tr_max->x1 || tr_max->y0 == tr_max->y1) {
2652         return OPJ_TRUE;
2653     }
2654
2655     sa = opj_dwt_init_sparse_array(tilec, numres);
2656     if (sa == NULL) {
2657         return OPJ_FALSE;
2658     }
2659
2660     if (numres == 1U) {
2661         OPJ_BOOL ret = opj_sparse_array_int32_read(sa,
2662                        tr_max->win_x0 - (OPJ_UINT32)tr_max->x0,
2663                        tr_max->win_y0 - (OPJ_UINT32)tr_max->y0,
2664                        tr_max->win_x1 - (OPJ_UINT32)tr_max->x0,
2665                        tr_max->win_y1 - (OPJ_UINT32)tr_max->y0,
2666                        tilec->data_win,
2667                        1, tr_max->win_x1 - tr_max->win_x0,
2668                        OPJ_TRUE);
2669         assert(ret);
2670         OPJ_UNUSED(ret);
2671         opj_sparse_array_int32_free(sa);
2672         return OPJ_TRUE;
2673     }
2674
2675     l_data_size = opj_dwt_max_resolution(tr, numres);
2676     /* overflow check */
2677     if (l_data_size > (SIZE_MAX - 5U)) {
2678         /* FIXME event manager error callback */
2679         return OPJ_FALSE;
2680     }
2681     l_data_size += 5U;
2682     /* overflow check */
2683     if (l_data_size > (SIZE_MAX / sizeof(opj_v4_t))) {
2684         /* FIXME event manager error callback */
2685         return OPJ_FALSE;
2686     }
2687     h.wavelet = (opj_v4_t*) opj_aligned_malloc(l_data_size * sizeof(opj_v4_t));
2688     if (!h.wavelet) {
2689         /* FIXME event manager error callback */
2690         return OPJ_FALSE;
2691     }
2692     v.wavelet = h.wavelet;
2693
2694     for (resno = 1; resno < numres; resno ++) {
2695         OPJ_UINT32 j;
2696         /* Window of interest subband-based coordinates */
2697         OPJ_UINT32 win_ll_x0, win_ll_y0, win_ll_x1, win_ll_y1;
2698         OPJ_UINT32 win_hl_x0, win_hl_x1;
2699         OPJ_UINT32 win_lh_y0, win_lh_y1;
2700         /* Window of interest tile-resolution-based coordinates */
2701         OPJ_UINT32 win_tr_x0, win_tr_x1, win_tr_y0, win_tr_y1;
2702         /* Tile-resolution subband-based coordinates */
2703         OPJ_UINT32 tr_ll_x0, tr_ll_y0, tr_hl_x0, tr_lh_y0;
2704
2705         ++tr;
2706
2707         h.sn = (OPJ_INT32)rw;
2708         v.sn = (OPJ_INT32)rh;
2709
2710         rw = (OPJ_UINT32)(tr->x1 - tr->x0);
2711         rh = (OPJ_UINT32)(tr->y1 - tr->y0);
2712
2713         h.dn = (OPJ_INT32)(rw - (OPJ_UINT32)h.sn);
2714         h.cas = tr->x0 % 2;
2715
2716         v.dn = (OPJ_INT32)(rh - (OPJ_UINT32)v.sn);
2717         v.cas = tr->y0 % 2;
2718
2719         /* Get the subband coordinates for the window of interest */
2720         /* LL band */
2721         opj_dwt_get_band_coordinates(tilec, resno, 0,
2722                                      win_tcx0, win_tcy0, win_tcx1, win_tcy1,
2723                                      &win_ll_x0, &win_ll_y0,
2724                                      &win_ll_x1, &win_ll_y1);
2725
2726         /* HL band */
2727         opj_dwt_get_band_coordinates(tilec, resno, 1,
2728                                      win_tcx0, win_tcy0, win_tcx1, win_tcy1,
2729                                      &win_hl_x0, NULL, &win_hl_x1, NULL);
2730
2731         /* LH band */
2732         opj_dwt_get_band_coordinates(tilec, resno, 2,
2733                                      win_tcx0, win_tcy0, win_tcx1, win_tcy1,
2734                                      NULL, &win_lh_y0, NULL, &win_lh_y1);
2735
2736         /* Beware: band index for non-LL0 resolution are 0=HL, 1=LH and 2=HH */
2737         tr_ll_x0 = (OPJ_UINT32)tr->bands[1].x0;
2738         tr_ll_y0 = (OPJ_UINT32)tr->bands[0].y0;
2739         tr_hl_x0 = (OPJ_UINT32)tr->bands[0].x0;
2740         tr_lh_y0 = (OPJ_UINT32)tr->bands[1].y0;
2741
2742         /* Substract the origin of the bands for this tile, to the subwindow */
2743         /* of interest band coordinates, so as to get them relative to the */
2744         /* tile */
2745         win_ll_x0 = opj_uint_subs(win_ll_x0, tr_ll_x0);
2746         win_ll_y0 = opj_uint_subs(win_ll_y0, tr_ll_y0);
2747         win_ll_x1 = opj_uint_subs(win_ll_x1, tr_ll_x0);
2748         win_ll_y1 = opj_uint_subs(win_ll_y1, tr_ll_y0);
2749         win_hl_x0 = opj_uint_subs(win_hl_x0, tr_hl_x0);
2750         win_hl_x1 = opj_uint_subs(win_hl_x1, tr_hl_x0);
2751         win_lh_y0 = opj_uint_subs(win_lh_y0, tr_lh_y0);
2752         win_lh_y1 = opj_uint_subs(win_lh_y1, tr_lh_y0);
2753
2754         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)h.sn, &win_ll_x0, &win_ll_x1);
2755         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)h.dn, &win_hl_x0, &win_hl_x1);
2756
2757         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)v.sn, &win_ll_y0, &win_ll_y1);
2758         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)v.dn, &win_lh_y0, &win_lh_y1);
2759
2760         /* Compute the tile-resolution-based coordinates for the window of interest */
2761         if (h.cas == 0) {
2762             win_tr_x0 = opj_uint_min(2 * win_ll_x0, 2 * win_hl_x0 + 1);
2763             win_tr_x1 = opj_uint_min(opj_uint_max(2 * win_ll_x1, 2 * win_hl_x1 + 1), rw);
2764         } else {
2765             win_tr_x0 = opj_uint_min(2 * win_hl_x0, 2 * win_ll_x0 + 1);
2766             win_tr_x1 = opj_uint_min(opj_uint_max(2 * win_hl_x1, 2 * win_ll_x1 + 1), rw);
2767         }
2768
2769         if (v.cas == 0) {
2770             win_tr_y0 = opj_uint_min(2 * win_ll_y0, 2 * win_lh_y0 + 1);
2771             win_tr_y1 = opj_uint_min(opj_uint_max(2 * win_ll_y1, 2 * win_lh_y1 + 1), rh);
2772         } else {
2773             win_tr_y0 = opj_uint_min(2 * win_lh_y0, 2 * win_ll_y0 + 1);
2774             win_tr_y1 = opj_uint_min(opj_uint_max(2 * win_lh_y1, 2 * win_ll_y1 + 1), rh);
2775         }
2776
2777         h.win_l_x0 = win_ll_x0;
2778         h.win_l_x1 = win_ll_x1;
2779         h.win_h_x0 = win_hl_x0;
2780         h.win_h_x1 = win_hl_x1;
2781         for (j = 0; j + 3 < rh; j += 4) {
2782             if ((j + 3 >= win_ll_y0 && j < win_ll_y1) ||
2783                     (j + 3 >= win_lh_y0 + (OPJ_UINT32)v.sn &&
2784                      j < win_lh_y1 + (OPJ_UINT32)v.sn)) {
2785                 opj_v4dwt_interleave_partial_h(&h, sa, j, opj_uint_min(4U, rh - j));
2786                 opj_v4dwt_decode(&h);
2787                 if (!opj_sparse_array_int32_write(sa,
2788                                                   win_tr_x0, j,
2789                                                   win_tr_x1, j + 4,
2790                                                   (OPJ_INT32*)&h.wavelet[win_tr_x0].f[0],
2791                                                   4, 1, OPJ_TRUE)) {
2792                     /* FIXME event manager error callback */
2793                     opj_sparse_array_int32_free(sa);
2794                     opj_aligned_free(h.wavelet);
2795                     return OPJ_FALSE;
2796                 }
2797             }
2798         }
2799
2800         if (j < rh &&
2801                 ((j + 3 >= win_ll_y0 && j < win_ll_y1) ||
2802                  (j + 3 >= win_lh_y0 + (OPJ_UINT32)v.sn &&
2803                   j < win_lh_y1 + (OPJ_UINT32)v.sn))) {
2804             opj_v4dwt_interleave_partial_h(&h, sa, j, rh - j);
2805             opj_v4dwt_decode(&h);
2806             if (!opj_sparse_array_int32_write(sa,
2807                                               win_tr_x0, j,
2808                                               win_tr_x1, rh,
2809                                               (OPJ_INT32*)&h.wavelet[win_tr_x0].f[0],
2810                                               4, 1, OPJ_TRUE)) {
2811                 /* FIXME event manager error callback */
2812                 opj_sparse_array_int32_free(sa);
2813                 opj_aligned_free(h.wavelet);
2814                 return OPJ_FALSE;
2815             }
2816         }
2817
2818         v.win_l_x0 = win_ll_y0;
2819         v.win_l_x1 = win_ll_y1;
2820         v.win_h_x0 = win_lh_y0;
2821         v.win_h_x1 = win_lh_y1;
2822         for (j = win_tr_x0; j < win_tr_x1; j += 4) {
2823             OPJ_UINT32 nb_elts = opj_uint_min(4U, win_tr_x1 - j);
2824
2825             opj_v4dwt_interleave_partial_v(&v, sa, j, nb_elts);
2826             opj_v4dwt_decode(&v);
2827
2828             if (!opj_sparse_array_int32_write(sa,
2829                                               j, win_tr_y0,
2830                                               j + nb_elts, win_tr_y1,
2831                                               (OPJ_INT32*)&h.wavelet[win_tr_y0].f[0],
2832                                               1, 4, OPJ_TRUE)) {
2833                 /* FIXME event manager error callback */
2834                 opj_sparse_array_int32_free(sa);
2835                 opj_aligned_free(h.wavelet);
2836                 return OPJ_FALSE;
2837             }
2838         }
2839     }
2840
2841     {
2842         OPJ_BOOL ret = opj_sparse_array_int32_read(sa,
2843                        tr_max->win_x0 - (OPJ_UINT32)tr_max->x0,
2844                        tr_max->win_y0 - (OPJ_UINT32)tr_max->y0,
2845                        tr_max->win_x1 - (OPJ_UINT32)tr_max->x0,
2846                        tr_max->win_y1 - (OPJ_UINT32)tr_max->y0,
2847                        tilec->data_win,
2848                        1, tr_max->win_x1 - tr_max->win_x0,
2849                        OPJ_TRUE);
2850         assert(ret);
2851         OPJ_UNUSED(ret);
2852     }
2853     opj_sparse_array_int32_free(sa);
2854
2855     opj_aligned_free(h.wavelet);
2856     return OPJ_TRUE;
2857 }
2858
2859
2860 OPJ_BOOL opj_dwt_decode_real(opj_tcd_t *p_tcd,
2861                              opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
2862                              OPJ_UINT32 numres)
2863 {
2864     if (p_tcd->whole_tile_decoding) {
2865         return opj_dwt_decode_tile_97(tilec, numres);
2866     } else {
2867         return opj_dwt_decode_partial_97(tilec, numres);
2868     }
2869 }