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