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