Encoder: use floating-point operations for irreversible transformation
[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; /*  12994 */
107 static const OPJ_FLOAT32 opj_dwt_beta  =  -0.052980118f; /*    434 */
108 static const OPJ_FLOAT32 opj_dwt_gamma = 0.882911075f; /*  -7233 */
109 static const OPJ_FLOAT32 opj_dwt_delta = 0.443506852f; /*  -3633 */
110
111 static const OPJ_FLOAT32 opj_K      = 1.230174105f; /*  10078 */
112 static const OPJ_FLOAT32 opj_c13318 = 1.625732422f;
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
1044 /* <summary>                             */
1045 /* Forward 9-7 wavelet transform in 1-D. */
1046 /* </summary>                            */
1047 static void opj_dwt_encode_1_real(void *aIn, OPJ_INT32 dn, OPJ_INT32 sn,
1048                                   OPJ_INT32 cas)
1049 {
1050     OPJ_INT32 i;
1051     OPJ_FLOAT32* a = (OPJ_FLOAT32*)aIn;
1052
1053     if (!cas) {
1054         if ((dn > 0) || (sn > 1)) { /* NEW :  CASE ONE ELEMENT */
1055             for (i = 0; i < dn; i++) {
1056                 OPJ_D(i) += opj_dwt_alpha * (OPJ_S_(i) + OPJ_S_(i + 1));
1057             }
1058             for (i = 0; i < sn; i++) {
1059                 OPJ_S(i) += opj_dwt_beta * (OPJ_D_(i - 1) + OPJ_D_(i));
1060             }
1061             for (i = 0; i < dn; i++) {
1062                 OPJ_D(i) += opj_dwt_gamma * (OPJ_S_(i) + OPJ_S_(i + 1));
1063             }
1064             for (i = 0; i < sn; i++) {
1065                 OPJ_S(i) += opj_dwt_delta * (OPJ_D_(i - 1) + OPJ_D_(i));
1066             }
1067             for (i = 0; i < dn; i++) {
1068                 OPJ_D(i) = opj_K / 2 * OPJ_D(i);
1069             }
1070             for (i = 0; i < sn; i++) {
1071                 OPJ_S(i) = opj_c13318 / 2 * OPJ_S(i);
1072             }
1073         }
1074     } else {
1075         if ((sn > 0) || (dn > 1)) { /* NEW :  CASE ONE ELEMENT */
1076             for (i = 0; i < dn; i++) {
1077                 OPJ_S(i) += opj_dwt_alpha * (OPJ_DD_(i) + OPJ_DD_(i - 1));
1078             }
1079             for (i = 0; i < sn; i++) {
1080                 OPJ_D(i) += opj_dwt_beta * (OPJ_SS_(i) + OPJ_SS_(i + 1));
1081             }
1082             for (i = 0; i < dn; i++) {
1083                 OPJ_S(i) += opj_dwt_gamma * (OPJ_DD_(i) + OPJ_DD_(i - 1));
1084             }
1085             for (i = 0; i < sn; i++) {
1086                 OPJ_D(i) += opj_dwt_delta * (OPJ_SS_(i) + OPJ_SS_(i + 1));
1087             }
1088             for (i = 0; i < dn; i++) {
1089                 OPJ_S(i) = opj_K / 2 * OPJ_S(i);
1090             }
1091             for (i = 0; i < sn; i++) {
1092                 OPJ_D(i) = opj_c13318 / 2 * OPJ_D(i);
1093             }
1094         }
1095     }
1096 }
1097
1098 static void opj_dwt_encode_stepsize(OPJ_INT32 stepsize, OPJ_INT32 numbps,
1099                                     opj_stepsize_t *bandno_stepsize)
1100 {
1101     OPJ_INT32 p, n;
1102     p = opj_int_floorlog2(stepsize) - 13;
1103     n = 11 - opj_int_floorlog2(stepsize);
1104     bandno_stepsize->mant = (n < 0 ? stepsize >> -n : stepsize << n) & 0x7ff;
1105     bandno_stepsize->expn = numbps - p;
1106 }
1107
1108 /*
1109 ==========================================================
1110    DWT interface
1111 ==========================================================
1112 */
1113
1114
1115 typedef struct {
1116     opj_dwt_t h;
1117     OPJ_UINT32 rw;
1118     OPJ_UINT32 w;
1119     OPJ_INT32 * OPJ_RESTRICT tiledp;
1120     OPJ_UINT32 min_j;
1121     OPJ_UINT32 max_j;
1122     opj_encode_one_row_fnptr_type p_function;
1123 } opj_dwt_encode_h_job_t;
1124
1125 static void opj_dwt_encode_h_func(void* user_data, opj_tls_t* tls)
1126 {
1127     OPJ_UINT32 j;
1128     opj_dwt_encode_h_job_t* job;
1129     (void)tls;
1130
1131     job = (opj_dwt_encode_h_job_t*)user_data;
1132     for (j = job->min_j; j < job->max_j; j++) {
1133         OPJ_INT32* OPJ_RESTRICT aj = job->tiledp + j * job->w;
1134         OPJ_UINT32 k;
1135         for (k = 0; k < job->rw; k++) {
1136             job->h.mem[k] = aj[k];
1137         }
1138         (*job->p_function)(job->h.mem, job->h.dn, job->h.sn, job->h.cas);
1139         opj_dwt_deinterleave_h(job->h.mem, aj, job->h.dn, job->h.sn, job->h.cas);
1140     }
1141
1142     opj_aligned_free(job->h.mem);
1143     opj_free(job);
1144 }
1145
1146 typedef struct {
1147     opj_dwt_t v;
1148     OPJ_UINT32 rh;
1149     OPJ_UINT32 w;
1150     OPJ_INT32 * OPJ_RESTRICT tiledp;
1151     OPJ_UINT32 min_j;
1152     OPJ_UINT32 max_j;
1153     opj_encode_one_row_fnptr_type p_function;
1154 } opj_dwt_encode_v_job_t;
1155
1156 static void opj_dwt_encode_v_func(void* user_data, opj_tls_t* tls)
1157 {
1158     OPJ_UINT32 j;
1159     opj_dwt_encode_v_job_t* job;
1160     (void)tls;
1161
1162     job = (opj_dwt_encode_v_job_t*)user_data;
1163     for (j = job->min_j; j < job->max_j; j++) {
1164         OPJ_INT32* OPJ_RESTRICT aj = job->tiledp + j;
1165         OPJ_UINT32 k;
1166         for (k = 0; k < job->rh; ++k) {
1167             job->v.mem[k] = aj[k * job->w];
1168         }
1169
1170         (*job->p_function)(job->v.mem, job->v.dn, job->v.sn, job->v.cas);
1171
1172         opj_dwt_deinterleave_v(job->v.mem, aj, job->v.dn, job->v.sn, job->w,
1173                                job->v.cas);
1174     }
1175
1176     opj_aligned_free(job->v.mem);
1177     opj_free(job);
1178 }
1179
1180 /* <summary>                            */
1181 /* Forward 5-3 wavelet transform in 2-D. */
1182 /* </summary>                           */
1183 static INLINE OPJ_BOOL opj_dwt_encode_procedure(opj_thread_pool_t* tp,
1184         opj_tcd_tilecomp_t * tilec,
1185         opj_encode_one_row_fnptr_type p_function)
1186 {
1187     OPJ_INT32 i;
1188     OPJ_INT32 *bj = 00;
1189     OPJ_UINT32 w;
1190     OPJ_INT32 l;
1191
1192     OPJ_SIZE_T l_data_size;
1193
1194     opj_tcd_resolution_t * l_cur_res = 0;
1195     opj_tcd_resolution_t * l_last_res = 0;
1196     const int num_threads = opj_thread_pool_get_thread_count(tp);
1197     OPJ_INT32 * OPJ_RESTRICT tiledp = tilec->data;
1198
1199     w = (OPJ_UINT32)(tilec->x1 - tilec->x0);
1200     l = (OPJ_INT32)tilec->numresolutions - 1;
1201
1202     l_cur_res = tilec->resolutions + l;
1203     l_last_res = l_cur_res - 1;
1204
1205     l_data_size = opj_dwt_max_resolution(tilec->resolutions, tilec->numresolutions);
1206     /* overflow check */
1207     if (l_data_size > (SIZE_MAX / sizeof(OPJ_INT32))) {
1208         /* FIXME event manager error callback */
1209         return OPJ_FALSE;
1210     }
1211     l_data_size *= sizeof(OPJ_INT32);
1212     bj = (OPJ_INT32*)opj_aligned_32_malloc(l_data_size);
1213     /* l_data_size is equal to 0 when numresolutions == 1 but bj is not used */
1214     /* in that case, so do not error out */
1215     if (l_data_size != 0 && ! bj) {
1216         return OPJ_FALSE;
1217     }
1218     i = l;
1219
1220     while (i--) {
1221         OPJ_UINT32 j;
1222         OPJ_UINT32 rw;           /* width of the resolution level computed   */
1223         OPJ_UINT32 rh;           /* height of the resolution level computed  */
1224         OPJ_UINT32
1225         rw1;      /* width of the resolution level once lower than computed one                                       */
1226         OPJ_UINT32
1227         rh1;      /* height of the resolution level once lower than computed one                                      */
1228         OPJ_INT32 cas_col;  /* 0 = non inversion on horizontal filtering 1 = inversion between low-pass and high-pass filtering */
1229         OPJ_INT32 cas_row;  /* 0 = non inversion on vertical filtering 1 = inversion between low-pass and high-pass filtering   */
1230         OPJ_INT32 dn, sn;
1231
1232         rw  = (OPJ_UINT32)(l_cur_res->x1 - l_cur_res->x0);
1233         rh  = (OPJ_UINT32)(l_cur_res->y1 - l_cur_res->y0);
1234         rw1 = (OPJ_UINT32)(l_last_res->x1 - l_last_res->x0);
1235         rh1 = (OPJ_UINT32)(l_last_res->y1 - l_last_res->y0);
1236
1237         cas_row = l_cur_res->x0 & 1;
1238         cas_col = l_cur_res->y0 & 1;
1239
1240         sn = (OPJ_INT32)rh1;
1241         dn = (OPJ_INT32)(rh - rh1);
1242
1243         /* Perform vertical pass */
1244         if (num_threads <= 1 || rw <= 1) {
1245             for (j = 0; j < rw; ++j) {
1246                 OPJ_INT32* OPJ_RESTRICT aj = tiledp + j;
1247                 OPJ_UINT32 k;
1248                 for (k = 0; k < rh; ++k) {
1249                     bj[k] = aj[k * w];
1250                 }
1251
1252                 (*p_function)(bj, dn, sn, cas_col);
1253
1254                 opj_dwt_deinterleave_v(bj, aj, dn, sn, w, cas_col);
1255             }
1256         }  else {
1257             OPJ_UINT32 num_jobs = (OPJ_UINT32)num_threads;
1258             OPJ_UINT32 step_j;
1259
1260             if (rw < num_jobs) {
1261                 num_jobs = rw;
1262             }
1263             step_j = (rw / num_jobs);
1264
1265             for (j = 0; j < num_jobs; j++) {
1266                 opj_dwt_encode_v_job_t* job;
1267
1268                 job = (opj_dwt_encode_v_job_t*) opj_malloc(sizeof(opj_dwt_encode_v_job_t));
1269                 if (!job) {
1270                     opj_thread_pool_wait_completion(tp, 0);
1271                     opj_aligned_free(bj);
1272                     return OPJ_FALSE;
1273                 }
1274                 job->v.mem = (OPJ_INT32*)opj_aligned_32_malloc(l_data_size);
1275                 if (!job->v.mem) {
1276                     opj_thread_pool_wait_completion(tp, 0);
1277                     opj_free(job);
1278                     opj_aligned_free(bj);
1279                     return OPJ_FALSE;
1280                 }
1281                 job->v.dn = dn;
1282                 job->v.sn = sn;
1283                 job->v.cas = cas_col;
1284                 job->rh = rh;
1285                 job->w = w;
1286                 job->tiledp = tiledp;
1287                 job->min_j = j * step_j;
1288                 job->max_j = (j + 1U) * step_j; /* this can overflow */
1289                 if (j == (num_jobs - 1U)) {  /* this will take care of the overflow */
1290                     job->max_j = rw;
1291                 }
1292                 job->p_function = p_function;
1293                 opj_thread_pool_submit_job(tp, opj_dwt_encode_v_func, job);
1294             }
1295             opj_thread_pool_wait_completion(tp, 0);
1296         }
1297
1298         sn = (OPJ_INT32)rw1;
1299         dn = (OPJ_INT32)(rw - rw1);
1300
1301         /* Perform horizontal pass */
1302         if (num_threads <= 1 || rh <= 1) {
1303             for (j = 0; j < rh; j++) {
1304                 OPJ_INT32* OPJ_RESTRICT aj = tiledp + j * w;
1305                 OPJ_UINT32 k;
1306                 for (k = 0; k < rw; k++) {
1307                     bj[k] = aj[k];
1308                 }
1309                 (*p_function)(bj, dn, sn, cas_row);
1310                 opj_dwt_deinterleave_h(bj, aj, dn, sn, cas_row);
1311             }
1312         }  else {
1313             OPJ_UINT32 num_jobs = (OPJ_UINT32)num_threads;
1314             OPJ_UINT32 step_j;
1315
1316             if (rh < num_jobs) {
1317                 num_jobs = rh;
1318             }
1319             step_j = (rh / num_jobs);
1320
1321             for (j = 0; j < num_jobs; j++) {
1322                 opj_dwt_encode_h_job_t* job;
1323
1324                 job = (opj_dwt_encode_h_job_t*) opj_malloc(sizeof(opj_dwt_encode_h_job_t));
1325                 if (!job) {
1326                     opj_thread_pool_wait_completion(tp, 0);
1327                     opj_aligned_free(bj);
1328                     return OPJ_FALSE;
1329                 }
1330                 job->h.mem = (OPJ_INT32*)opj_aligned_32_malloc(l_data_size);
1331                 if (!job->h.mem) {
1332                     opj_thread_pool_wait_completion(tp, 0);
1333                     opj_free(job);
1334                     opj_aligned_free(bj);
1335                     return OPJ_FALSE;
1336                 }
1337                 job->h.dn = dn;
1338                 job->h.sn = sn;
1339                 job->h.cas = cas_row;
1340                 job->rw = rw;
1341                 job->w = w;
1342                 job->tiledp = tiledp;
1343                 job->min_j = j * step_j;
1344                 job->max_j = (j + 1U) * step_j; /* this can overflow */
1345                 if (j == (num_jobs - 1U)) {  /* this will take care of the overflow */
1346                     job->max_j = rh;
1347                 }
1348                 job->p_function = p_function;
1349                 opj_thread_pool_submit_job(tp, opj_dwt_encode_h_func, job);
1350             }
1351             opj_thread_pool_wait_completion(tp, 0);
1352         }
1353
1354         l_cur_res = l_last_res;
1355
1356         --l_last_res;
1357     }
1358
1359     opj_aligned_free(bj);
1360     return OPJ_TRUE;
1361 }
1362
1363 /* Forward 5-3 wavelet transform in 2-D. */
1364 /* </summary>                           */
1365 OPJ_BOOL opj_dwt_encode(opj_tcd_t *p_tcd,
1366                         opj_tcd_tilecomp_t * tilec)
1367 {
1368     return opj_dwt_encode_procedure(p_tcd->thread_pool, tilec, opj_dwt_encode_1);
1369 }
1370
1371 /* <summary>                            */
1372 /* Inverse 5-3 wavelet transform in 2-D. */
1373 /* </summary>                           */
1374 OPJ_BOOL opj_dwt_decode(opj_tcd_t *p_tcd, opj_tcd_tilecomp_t* tilec,
1375                         OPJ_UINT32 numres)
1376 {
1377     if (p_tcd->whole_tile_decoding) {
1378         return opj_dwt_decode_tile(p_tcd->thread_pool, tilec, numres);
1379     } else {
1380         return opj_dwt_decode_partial_tile(tilec, numres);
1381     }
1382 }
1383
1384
1385 /* <summary>                          */
1386 /* Get gain of 5-3 wavelet transform. */
1387 /* </summary>                         */
1388 OPJ_UINT32 opj_dwt_getgain(OPJ_UINT32 orient)
1389 {
1390     if (orient == 0) {
1391         return 0;
1392     }
1393     if (orient == 1 || orient == 2) {
1394         return 1;
1395     }
1396     return 2;
1397 }
1398
1399 /* <summary>                */
1400 /* Get norm of 5-3 wavelet. */
1401 /* </summary>               */
1402 OPJ_FLOAT64 opj_dwt_getnorm(OPJ_UINT32 level, OPJ_UINT32 orient)
1403 {
1404     /* FIXME ! This is just a band-aid to avoid a buffer overflow */
1405     /* but the array should really be extended up to 33 resolution levels */
1406     /* See https://github.com/uclouvain/openjpeg/issues/493 */
1407     if (orient == 0 && level >= 10) {
1408         level = 9;
1409     } else if (orient > 0 && level >= 9) {
1410         level = 8;
1411     }
1412     return opj_dwt_norms[orient][level];
1413 }
1414
1415 /* <summary>                             */
1416 /* Forward 9-7 wavelet transform in 2-D. */
1417 /* </summary>                            */
1418 OPJ_BOOL opj_dwt_encode_real(opj_tcd_t *p_tcd,
1419                              opj_tcd_tilecomp_t * tilec)
1420 {
1421     return opj_dwt_encode_procedure(p_tcd->thread_pool, tilec,
1422                                     opj_dwt_encode_1_real);
1423 }
1424
1425 /* <summary>                          */
1426 /* Get gain of 9-7 wavelet transform. */
1427 /* </summary>                         */
1428 OPJ_UINT32 opj_dwt_getgain_real(OPJ_UINT32 orient)
1429 {
1430     (void)orient;
1431     return 0;
1432 }
1433
1434 /* <summary>                */
1435 /* Get norm of 9-7 wavelet. */
1436 /* </summary>               */
1437 OPJ_FLOAT64 opj_dwt_getnorm_real(OPJ_UINT32 level, OPJ_UINT32 orient)
1438 {
1439     /* FIXME ! This is just a band-aid to avoid a buffer overflow */
1440     /* but the array should really be extended up to 33 resolution levels */
1441     /* See https://github.com/uclouvain/openjpeg/issues/493 */
1442     if (orient == 0 && level >= 10) {
1443         level = 9;
1444     } else if (orient > 0 && level >= 9) {
1445         level = 8;
1446     }
1447     return opj_dwt_norms_real[orient][level];
1448 }
1449
1450 void opj_dwt_calc_explicit_stepsizes(opj_tccp_t * tccp, OPJ_UINT32 prec)
1451 {
1452     OPJ_UINT32 numbands, bandno;
1453     numbands = 3 * tccp->numresolutions - 2;
1454     for (bandno = 0; bandno < numbands; bandno++) {
1455         OPJ_FLOAT64 stepsize;
1456         OPJ_UINT32 resno, level, orient, gain;
1457
1458         resno = (bandno == 0) ? 0 : ((bandno - 1) / 3 + 1);
1459         orient = (bandno == 0) ? 0 : ((bandno - 1) % 3 + 1);
1460         level = tccp->numresolutions - 1 - resno;
1461         gain = (tccp->qmfbid == 0) ? 0 : ((orient == 0) ? 0 : (((orient == 1) ||
1462                                           (orient == 2)) ? 1 : 2));
1463         if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
1464             stepsize = 1.0;
1465         } else {
1466             OPJ_FLOAT64 norm = opj_dwt_norms_real[orient][level];
1467             stepsize = (1 << (gain)) / norm;
1468         }
1469         opj_dwt_encode_stepsize((OPJ_INT32) floor(stepsize * 8192.0),
1470                                 (OPJ_INT32)(prec + gain), &tccp->stepsizes[bandno]);
1471     }
1472 }
1473
1474 /* <summary>                             */
1475 /* Determine maximum computed resolution level for inverse wavelet transform */
1476 /* </summary>                            */
1477 static OPJ_UINT32 opj_dwt_max_resolution(opj_tcd_resolution_t* OPJ_RESTRICT r,
1478         OPJ_UINT32 i)
1479 {
1480     OPJ_UINT32 mr   = 0;
1481     OPJ_UINT32 w;
1482     while (--i) {
1483         ++r;
1484         if (mr < (w = (OPJ_UINT32)(r->x1 - r->x0))) {
1485             mr = w ;
1486         }
1487         if (mr < (w = (OPJ_UINT32)(r->y1 - r->y0))) {
1488             mr = w ;
1489         }
1490     }
1491     return mr ;
1492 }
1493
1494 typedef struct {
1495     opj_dwt_t h;
1496     OPJ_UINT32 rw;
1497     OPJ_UINT32 w;
1498     OPJ_INT32 * OPJ_RESTRICT tiledp;
1499     OPJ_UINT32 min_j;
1500     OPJ_UINT32 max_j;
1501 } opj_dwt_decode_h_job_t;
1502
1503 static void opj_dwt_decode_h_func(void* user_data, opj_tls_t* tls)
1504 {
1505     OPJ_UINT32 j;
1506     opj_dwt_decode_h_job_t* job;
1507     (void)tls;
1508
1509     job = (opj_dwt_decode_h_job_t*)user_data;
1510     for (j = job->min_j; j < job->max_j; j++) {
1511         opj_idwt53_h(&job->h, &job->tiledp[j * job->w]);
1512     }
1513
1514     opj_aligned_free(job->h.mem);
1515     opj_free(job);
1516 }
1517
1518 typedef struct {
1519     opj_dwt_t v;
1520     OPJ_UINT32 rh;
1521     OPJ_UINT32 w;
1522     OPJ_INT32 * OPJ_RESTRICT tiledp;
1523     OPJ_UINT32 min_j;
1524     OPJ_UINT32 max_j;
1525 } opj_dwt_decode_v_job_t;
1526
1527 static void opj_dwt_decode_v_func(void* user_data, opj_tls_t* tls)
1528 {
1529     OPJ_UINT32 j;
1530     opj_dwt_decode_v_job_t* job;
1531     (void)tls;
1532
1533     job = (opj_dwt_decode_v_job_t*)user_data;
1534     for (j = job->min_j; j + PARALLEL_COLS_53 <= job->max_j;
1535             j += PARALLEL_COLS_53) {
1536         opj_idwt53_v(&job->v, &job->tiledp[j], (OPJ_SIZE_T)job->w,
1537                      PARALLEL_COLS_53);
1538     }
1539     if (j < job->max_j)
1540         opj_idwt53_v(&job->v, &job->tiledp[j], (OPJ_SIZE_T)job->w,
1541                      (OPJ_INT32)(job->max_j - j));
1542
1543     opj_aligned_free(job->v.mem);
1544     opj_free(job);
1545 }
1546
1547
1548 /* <summary>                            */
1549 /* Inverse wavelet transform in 2-D.    */
1550 /* </summary>                           */
1551 static OPJ_BOOL opj_dwt_decode_tile(opj_thread_pool_t* tp,
1552                                     opj_tcd_tilecomp_t* tilec, OPJ_UINT32 numres)
1553 {
1554     opj_dwt_t h;
1555     opj_dwt_t v;
1556
1557     opj_tcd_resolution_t* tr = tilec->resolutions;
1558
1559     OPJ_UINT32 rw = (OPJ_UINT32)(tr->x1 -
1560                                  tr->x0);  /* width of the resolution level computed */
1561     OPJ_UINT32 rh = (OPJ_UINT32)(tr->y1 -
1562                                  tr->y0);  /* height of the resolution level computed */
1563
1564     OPJ_UINT32 w = (OPJ_UINT32)(tilec->resolutions[tilec->minimum_num_resolutions -
1565                                                                1].x1 -
1566                                 tilec->resolutions[tilec->minimum_num_resolutions - 1].x0);
1567     OPJ_SIZE_T h_mem_size;
1568     int num_threads;
1569
1570     if (numres == 1U) {
1571         return OPJ_TRUE;
1572     }
1573     num_threads = opj_thread_pool_get_thread_count(tp);
1574     h_mem_size = opj_dwt_max_resolution(tr, numres);
1575     /* overflow check */
1576     if (h_mem_size > (SIZE_MAX / PARALLEL_COLS_53 / sizeof(OPJ_INT32))) {
1577         /* FIXME event manager error callback */
1578         return OPJ_FALSE;
1579     }
1580     /* We need PARALLEL_COLS_53 times the height of the array, */
1581     /* since for the vertical pass */
1582     /* we process PARALLEL_COLS_53 columns at a time */
1583     h_mem_size *= PARALLEL_COLS_53 * sizeof(OPJ_INT32);
1584     h.mem = (OPJ_INT32*)opj_aligned_32_malloc(h_mem_size);
1585     if (! h.mem) {
1586         /* FIXME event manager error callback */
1587         return OPJ_FALSE;
1588     }
1589
1590     v.mem = h.mem;
1591
1592     while (--numres) {
1593         OPJ_INT32 * OPJ_RESTRICT tiledp = tilec->data;
1594         OPJ_UINT32 j;
1595
1596         ++tr;
1597         h.sn = (OPJ_INT32)rw;
1598         v.sn = (OPJ_INT32)rh;
1599
1600         rw = (OPJ_UINT32)(tr->x1 - tr->x0);
1601         rh = (OPJ_UINT32)(tr->y1 - tr->y0);
1602
1603         h.dn = (OPJ_INT32)(rw - (OPJ_UINT32)h.sn);
1604         h.cas = tr->x0 % 2;
1605
1606         if (num_threads <= 1 || rh <= 1) {
1607             for (j = 0; j < rh; ++j) {
1608                 opj_idwt53_h(&h, &tiledp[(OPJ_SIZE_T)j * w]);
1609             }
1610         } else {
1611             OPJ_UINT32 num_jobs = (OPJ_UINT32)num_threads;
1612             OPJ_UINT32 step_j;
1613
1614             if (rh < num_jobs) {
1615                 num_jobs = rh;
1616             }
1617             step_j = (rh / num_jobs);
1618
1619             for (j = 0; j < num_jobs; j++) {
1620                 opj_dwt_decode_h_job_t* job;
1621
1622                 job = (opj_dwt_decode_h_job_t*) opj_malloc(sizeof(opj_dwt_decode_h_job_t));
1623                 if (!job) {
1624                     /* It would be nice to fallback to single thread case, but */
1625                     /* unfortunately some jobs may be launched and have modified */
1626                     /* tiledp, so it is not practical to recover from that error */
1627                     /* FIXME event manager error callback */
1628                     opj_thread_pool_wait_completion(tp, 0);
1629                     opj_aligned_free(h.mem);
1630                     return OPJ_FALSE;
1631                 }
1632                 job->h = h;
1633                 job->rw = rw;
1634                 job->w = w;
1635                 job->tiledp = tiledp;
1636                 job->min_j = j * step_j;
1637                 job->max_j = (j + 1U) * step_j; /* this can overflow */
1638                 if (j == (num_jobs - 1U)) {  /* this will take care of the overflow */
1639                     job->max_j = rh;
1640                 }
1641                 job->h.mem = (OPJ_INT32*)opj_aligned_32_malloc(h_mem_size);
1642                 if (!job->h.mem) {
1643                     /* FIXME event manager error callback */
1644                     opj_thread_pool_wait_completion(tp, 0);
1645                     opj_free(job);
1646                     opj_aligned_free(h.mem);
1647                     return OPJ_FALSE;
1648                 }
1649                 opj_thread_pool_submit_job(tp, opj_dwt_decode_h_func, job);
1650             }
1651             opj_thread_pool_wait_completion(tp, 0);
1652         }
1653
1654         v.dn = (OPJ_INT32)(rh - (OPJ_UINT32)v.sn);
1655         v.cas = tr->y0 % 2;
1656
1657         if (num_threads <= 1 || rw <= 1) {
1658             for (j = 0; j + PARALLEL_COLS_53 <= rw;
1659                     j += PARALLEL_COLS_53) {
1660                 opj_idwt53_v(&v, &tiledp[j], (OPJ_SIZE_T)w, PARALLEL_COLS_53);
1661             }
1662             if (j < rw) {
1663                 opj_idwt53_v(&v, &tiledp[j], (OPJ_SIZE_T)w, (OPJ_INT32)(rw - j));
1664             }
1665         } else {
1666             OPJ_UINT32 num_jobs = (OPJ_UINT32)num_threads;
1667             OPJ_UINT32 step_j;
1668
1669             if (rw < num_jobs) {
1670                 num_jobs = rw;
1671             }
1672             step_j = (rw / num_jobs);
1673
1674             for (j = 0; j < num_jobs; j++) {
1675                 opj_dwt_decode_v_job_t* job;
1676
1677                 job = (opj_dwt_decode_v_job_t*) opj_malloc(sizeof(opj_dwt_decode_v_job_t));
1678                 if (!job) {
1679                     /* It would be nice to fallback to single thread case, but */
1680                     /* unfortunately some jobs may be launched and have modified */
1681                     /* tiledp, so it is not practical to recover from that error */
1682                     /* FIXME event manager error callback */
1683                     opj_thread_pool_wait_completion(tp, 0);
1684                     opj_aligned_free(v.mem);
1685                     return OPJ_FALSE;
1686                 }
1687                 job->v = v;
1688                 job->rh = rh;
1689                 job->w = w;
1690                 job->tiledp = tiledp;
1691                 job->min_j = j * step_j;
1692                 job->max_j = (j + 1U) * step_j; /* this can overflow */
1693                 if (j == (num_jobs - 1U)) {  /* this will take care of the overflow */
1694                     job->max_j = rw;
1695                 }
1696                 job->v.mem = (OPJ_INT32*)opj_aligned_32_malloc(h_mem_size);
1697                 if (!job->v.mem) {
1698                     /* FIXME event manager error callback */
1699                     opj_thread_pool_wait_completion(tp, 0);
1700                     opj_free(job);
1701                     opj_aligned_free(v.mem);
1702                     return OPJ_FALSE;
1703                 }
1704                 opj_thread_pool_submit_job(tp, opj_dwt_decode_v_func, job);
1705             }
1706             opj_thread_pool_wait_completion(tp, 0);
1707         }
1708     }
1709     opj_aligned_free(h.mem);
1710     return OPJ_TRUE;
1711 }
1712
1713 static void opj_dwt_interleave_partial_h(OPJ_INT32 *dest,
1714         OPJ_INT32 cas,
1715         opj_sparse_array_int32_t* sa,
1716         OPJ_UINT32 sa_line,
1717         OPJ_UINT32 sn,
1718         OPJ_UINT32 win_l_x0,
1719         OPJ_UINT32 win_l_x1,
1720         OPJ_UINT32 win_h_x0,
1721         OPJ_UINT32 win_h_x1)
1722 {
1723     OPJ_BOOL ret;
1724     ret = opj_sparse_array_int32_read(sa,
1725                                       win_l_x0, sa_line,
1726                                       win_l_x1, sa_line + 1,
1727                                       dest + cas + 2 * win_l_x0,
1728                                       2, 0, OPJ_TRUE);
1729     assert(ret);
1730     ret = opj_sparse_array_int32_read(sa,
1731                                       sn + win_h_x0, sa_line,
1732                                       sn + win_h_x1, sa_line + 1,
1733                                       dest + 1 - cas + 2 * win_h_x0,
1734                                       2, 0, OPJ_TRUE);
1735     assert(ret);
1736     OPJ_UNUSED(ret);
1737 }
1738
1739
1740 static void opj_dwt_interleave_partial_v(OPJ_INT32 *dest,
1741         OPJ_INT32 cas,
1742         opj_sparse_array_int32_t* sa,
1743         OPJ_UINT32 sa_col,
1744         OPJ_UINT32 nb_cols,
1745         OPJ_UINT32 sn,
1746         OPJ_UINT32 win_l_y0,
1747         OPJ_UINT32 win_l_y1,
1748         OPJ_UINT32 win_h_y0,
1749         OPJ_UINT32 win_h_y1)
1750 {
1751     OPJ_BOOL ret;
1752     ret  = opj_sparse_array_int32_read(sa,
1753                                        sa_col, win_l_y0,
1754                                        sa_col + nb_cols, win_l_y1,
1755                                        dest + cas * 4 + 2 * 4 * win_l_y0,
1756                                        1, 2 * 4, OPJ_TRUE);
1757     assert(ret);
1758     ret = opj_sparse_array_int32_read(sa,
1759                                       sa_col, sn + win_h_y0,
1760                                       sa_col + nb_cols, sn + win_h_y1,
1761                                       dest + (1 - cas) * 4 + 2 * 4 * win_h_y0,
1762                                       1, 2 * 4, OPJ_TRUE);
1763     assert(ret);
1764     OPJ_UNUSED(ret);
1765 }
1766
1767 static void opj_dwt_decode_partial_1(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
1768                                      OPJ_INT32 cas,
1769                                      OPJ_INT32 win_l_x0,
1770                                      OPJ_INT32 win_l_x1,
1771                                      OPJ_INT32 win_h_x0,
1772                                      OPJ_INT32 win_h_x1)
1773 {
1774     OPJ_INT32 i;
1775
1776     if (!cas) {
1777         if ((dn > 0) || (sn > 1)) { /* NEW :  CASE ONE ELEMENT */
1778
1779             /* Naive version is :
1780             for (i = win_l_x0; i < i_max; i++) {
1781                 OPJ_S(i) -= (OPJ_D_(i - 1) + OPJ_D_(i) + 2) >> 2;
1782             }
1783             for (i = win_h_x0; i < win_h_x1; i++) {
1784                 OPJ_D(i) += (OPJ_S_(i) + OPJ_S_(i + 1)) >> 1;
1785             }
1786             but the compiler doesn't manage to unroll it to avoid bound
1787             checking in OPJ_S_ and OPJ_D_ macros
1788             */
1789
1790             i = win_l_x0;
1791             if (i < win_l_x1) {
1792                 OPJ_INT32 i_max;
1793
1794                 /* Left-most case */
1795                 OPJ_S(i) -= (OPJ_D_(i - 1) + OPJ_D_(i) + 2) >> 2;
1796                 i ++;
1797
1798                 i_max = win_l_x1;
1799                 if (i_max > dn) {
1800                     i_max = dn;
1801                 }
1802                 for (; i < i_max; i++) {
1803                     /* No bound checking */
1804                     OPJ_S(i) -= (OPJ_D(i - 1) + OPJ_D(i) + 2) >> 2;
1805                 }
1806                 for (; i < win_l_x1; i++) {
1807                     /* Right-most case */
1808                     OPJ_S(i) -= (OPJ_D_(i - 1) + OPJ_D_(i) + 2) >> 2;
1809                 }
1810             }
1811
1812             i = win_h_x0;
1813             if (i < win_h_x1) {
1814                 OPJ_INT32 i_max = win_h_x1;
1815                 if (i_max >= sn) {
1816                     i_max = sn - 1;
1817                 }
1818                 for (; i < i_max; i++) {
1819                     /* No bound checking */
1820                     OPJ_D(i) += (OPJ_S(i) + OPJ_S(i + 1)) >> 1;
1821                 }
1822                 for (; i < win_h_x1; i++) {
1823                     /* Right-most case */
1824                     OPJ_D(i) += (OPJ_S_(i) + OPJ_S_(i + 1)) >> 1;
1825                 }
1826             }
1827         }
1828     } else {
1829         if (!sn  && dn == 1) {        /* NEW :  CASE ONE ELEMENT */
1830             OPJ_S(0) /= 2;
1831         } else {
1832             for (i = win_l_x0; i < win_l_x1; i++) {
1833                 OPJ_D(i) -= (OPJ_SS_(i) + OPJ_SS_(i + 1) + 2) >> 2;
1834             }
1835             for (i = win_h_x0; i < win_h_x1; i++) {
1836                 OPJ_S(i) += (OPJ_DD_(i) + OPJ_DD_(i - 1)) >> 1;
1837             }
1838         }
1839     }
1840 }
1841
1842 #define OPJ_S_off(i,off) a[(OPJ_UINT32)(i)*2*4+off]
1843 #define OPJ_D_off(i,off) a[(1+(OPJ_UINT32)(i)*2)*4+off]
1844 #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)))
1845 #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)))
1846 #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)))
1847 #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)))
1848
1849 static void opj_dwt_decode_partial_1_parallel(OPJ_INT32 *a,
1850         OPJ_UINT32 nb_cols,
1851         OPJ_INT32 dn, OPJ_INT32 sn,
1852         OPJ_INT32 cas,
1853         OPJ_INT32 win_l_x0,
1854         OPJ_INT32 win_l_x1,
1855         OPJ_INT32 win_h_x0,
1856         OPJ_INT32 win_h_x1)
1857 {
1858     OPJ_INT32 i;
1859     OPJ_UINT32 off;
1860
1861     (void)nb_cols;
1862
1863     if (!cas) {
1864         if ((dn > 0) || (sn > 1)) { /* NEW :  CASE ONE ELEMENT */
1865
1866             /* Naive version is :
1867             for (i = win_l_x0; i < i_max; i++) {
1868                 OPJ_S(i) -= (OPJ_D_(i - 1) + OPJ_D_(i) + 2) >> 2;
1869             }
1870             for (i = win_h_x0; i < win_h_x1; i++) {
1871                 OPJ_D(i) += (OPJ_S_(i) + OPJ_S_(i + 1)) >> 1;
1872             }
1873             but the compiler doesn't manage to unroll it to avoid bound
1874             checking in OPJ_S_ and OPJ_D_ macros
1875             */
1876
1877             i = win_l_x0;
1878             if (i < win_l_x1) {
1879                 OPJ_INT32 i_max;
1880
1881                 /* Left-most case */
1882                 for (off = 0; off < 4; off++) {
1883                     OPJ_S_off(i, off) -= (OPJ_D__off(i - 1, off) + OPJ_D__off(i, off) + 2) >> 2;
1884                 }
1885                 i ++;
1886
1887                 i_max = win_l_x1;
1888                 if (i_max > dn) {
1889                     i_max = dn;
1890                 }
1891
1892 #ifdef __SSE2__
1893                 if (i + 1 < i_max) {
1894                     const __m128i two = _mm_set1_epi32(2);
1895                     __m128i Dm1 = _mm_load_si128((__m128i * const)(a + 4 + (i - 1) * 8));
1896                     for (; i + 1 < i_max; i += 2) {
1897                         /* No bound checking */
1898                         __m128i S = _mm_load_si128((__m128i * const)(a + i * 8));
1899                         __m128i D = _mm_load_si128((__m128i * const)(a + 4 + i * 8));
1900                         __m128i S1 = _mm_load_si128((__m128i * const)(a + (i + 1) * 8));
1901                         __m128i D1 = _mm_load_si128((__m128i * const)(a + 4 + (i + 1) * 8));
1902                         S = _mm_sub_epi32(S,
1903                                           _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(Dm1, D), two), 2));
1904                         S1 = _mm_sub_epi32(S1,
1905                                            _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(D, D1), two), 2));
1906                         _mm_store_si128((__m128i*)(a + i * 8), S);
1907                         _mm_store_si128((__m128i*)(a + (i + 1) * 8), S1);
1908                         Dm1 = D1;
1909                     }
1910                 }
1911 #endif
1912
1913                 for (; i < i_max; i++) {
1914                     /* No bound checking */
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                 for (; i < win_l_x1; i++) {
1920                     /* Right-most case */
1921                     for (off = 0; off < 4; off++) {
1922                         OPJ_S_off(i, off) -= (OPJ_D__off(i - 1, off) + OPJ_D__off(i, off) + 2) >> 2;
1923                     }
1924                 }
1925             }
1926
1927             i = win_h_x0;
1928             if (i < win_h_x1) {
1929                 OPJ_INT32 i_max = win_h_x1;
1930                 if (i_max >= sn) {
1931                     i_max = sn - 1;
1932                 }
1933
1934 #ifdef __SSE2__
1935                 if (i + 1 < i_max) {
1936                     __m128i S =  _mm_load_si128((__m128i * const)(a + i * 8));
1937                     for (; i + 1 < i_max; i += 2) {
1938                         /* No bound checking */
1939                         __m128i D = _mm_load_si128((__m128i * const)(a + 4 + i * 8));
1940                         __m128i S1 = _mm_load_si128((__m128i * const)(a + (i + 1) * 8));
1941                         __m128i D1 = _mm_load_si128((__m128i * const)(a + 4 + (i + 1) * 8));
1942                         __m128i S2 = _mm_load_si128((__m128i * const)(a + (i + 2) * 8));
1943                         D = _mm_add_epi32(D, _mm_srai_epi32(_mm_add_epi32(S, S1), 1));
1944                         D1 = _mm_add_epi32(D1, _mm_srai_epi32(_mm_add_epi32(S1, S2), 1));
1945                         _mm_store_si128((__m128i*)(a + 4 + i * 8), D);
1946                         _mm_store_si128((__m128i*)(a + 4 + (i + 1) * 8), D1);
1947                         S = S2;
1948                     }
1949                 }
1950 #endif
1951
1952                 for (; i < i_max; i++) {
1953                     /* No bound checking */
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                 for (; i < win_h_x1; i++) {
1959                     /* Right-most case */
1960                     for (off = 0; off < 4; off++) {
1961                         OPJ_D_off(i, off) += (OPJ_S__off(i, off) + OPJ_S__off(i + 1, off)) >> 1;
1962                     }
1963                 }
1964             }
1965         }
1966     } else {
1967         if (!sn  && dn == 1) {        /* NEW :  CASE ONE ELEMENT */
1968             for (off = 0; off < 4; off++) {
1969                 OPJ_S_off(0, off) /= 2;
1970             }
1971         } else {
1972             for (i = win_l_x0; i < win_l_x1; i++) {
1973                 for (off = 0; off < 4; off++) {
1974                     OPJ_D_off(i, off) -= (OPJ_SS__off(i, off) + OPJ_SS__off(i + 1, off) + 2) >> 2;
1975                 }
1976             }
1977             for (i = win_h_x0; i < win_h_x1; i++) {
1978                 for (off = 0; off < 4; off++) {
1979                     OPJ_S_off(i, off) += (OPJ_DD__off(i, off) + OPJ_DD__off(i - 1, off)) >> 1;
1980                 }
1981             }
1982         }
1983     }
1984 }
1985
1986 static void opj_dwt_get_band_coordinates(opj_tcd_tilecomp_t* tilec,
1987         OPJ_UINT32 resno,
1988         OPJ_UINT32 bandno,
1989         OPJ_UINT32 tcx0,
1990         OPJ_UINT32 tcy0,
1991         OPJ_UINT32 tcx1,
1992         OPJ_UINT32 tcy1,
1993         OPJ_UINT32* tbx0,
1994         OPJ_UINT32* tby0,
1995         OPJ_UINT32* tbx1,
1996         OPJ_UINT32* tby1)
1997 {
1998     /* Compute number of decomposition for this band. See table F-1 */
1999     OPJ_UINT32 nb = (resno == 0) ?
2000                     tilec->numresolutions - 1 :
2001                     tilec->numresolutions - resno;
2002     /* Map above tile-based coordinates to sub-band-based coordinates per */
2003     /* equation B-15 of the standard */
2004     OPJ_UINT32 x0b = bandno & 1;
2005     OPJ_UINT32 y0b = bandno >> 1;
2006     if (tbx0) {
2007         *tbx0 = (nb == 0) ? tcx0 :
2008                 (tcx0 <= (1U << (nb - 1)) * x0b) ? 0 :
2009                 opj_uint_ceildivpow2(tcx0 - (1U << (nb - 1)) * x0b, nb);
2010     }
2011     if (tby0) {
2012         *tby0 = (nb == 0) ? tcy0 :
2013                 (tcy0 <= (1U << (nb - 1)) * y0b) ? 0 :
2014                 opj_uint_ceildivpow2(tcy0 - (1U << (nb - 1)) * y0b, nb);
2015     }
2016     if (tbx1) {
2017         *tbx1 = (nb == 0) ? tcx1 :
2018                 (tcx1 <= (1U << (nb - 1)) * x0b) ? 0 :
2019                 opj_uint_ceildivpow2(tcx1 - (1U << (nb - 1)) * x0b, nb);
2020     }
2021     if (tby1) {
2022         *tby1 = (nb == 0) ? tcy1 :
2023                 (tcy1 <= (1U << (nb - 1)) * y0b) ? 0 :
2024                 opj_uint_ceildivpow2(tcy1 - (1U << (nb - 1)) * y0b, nb);
2025     }
2026 }
2027
2028 static void opj_dwt_segment_grow(OPJ_UINT32 filter_width,
2029                                  OPJ_UINT32 max_size,
2030                                  OPJ_UINT32* start,
2031                                  OPJ_UINT32* end)
2032 {
2033     *start = opj_uint_subs(*start, filter_width);
2034     *end = opj_uint_adds(*end, filter_width);
2035     *end = opj_uint_min(*end, max_size);
2036 }
2037
2038
2039 static opj_sparse_array_int32_t* opj_dwt_init_sparse_array(
2040     opj_tcd_tilecomp_t* tilec,
2041     OPJ_UINT32 numres)
2042 {
2043     opj_tcd_resolution_t* tr_max = &(tilec->resolutions[numres - 1]);
2044     OPJ_UINT32 w = (OPJ_UINT32)(tr_max->x1 - tr_max->x0);
2045     OPJ_UINT32 h = (OPJ_UINT32)(tr_max->y1 - tr_max->y0);
2046     OPJ_UINT32 resno, bandno, precno, cblkno;
2047     opj_sparse_array_int32_t* sa = opj_sparse_array_int32_create(
2048                                        w, h, opj_uint_min(w, 64), opj_uint_min(h, 64));
2049     if (sa == NULL) {
2050         return NULL;
2051     }
2052
2053     for (resno = 0; resno < numres; ++resno) {
2054         opj_tcd_resolution_t* res = &tilec->resolutions[resno];
2055
2056         for (bandno = 0; bandno < res->numbands; ++bandno) {
2057             opj_tcd_band_t* band = &res->bands[bandno];
2058
2059             for (precno = 0; precno < res->pw * res->ph; ++precno) {
2060                 opj_tcd_precinct_t* precinct = &band->precincts[precno];
2061                 for (cblkno = 0; cblkno < precinct->cw * precinct->ch; ++cblkno) {
2062                     opj_tcd_cblk_dec_t* cblk = &precinct->cblks.dec[cblkno];
2063                     if (cblk->decoded_data != NULL) {
2064                         OPJ_UINT32 x = (OPJ_UINT32)(cblk->x0 - band->x0);
2065                         OPJ_UINT32 y = (OPJ_UINT32)(cblk->y0 - band->y0);
2066                         OPJ_UINT32 cblk_w = (OPJ_UINT32)(cblk->x1 - cblk->x0);
2067                         OPJ_UINT32 cblk_h = (OPJ_UINT32)(cblk->y1 - cblk->y0);
2068
2069                         if (band->bandno & 1) {
2070                             opj_tcd_resolution_t* pres = &tilec->resolutions[resno - 1];
2071                             x += (OPJ_UINT32)(pres->x1 - pres->x0);
2072                         }
2073                         if (band->bandno & 2) {
2074                             opj_tcd_resolution_t* pres = &tilec->resolutions[resno - 1];
2075                             y += (OPJ_UINT32)(pres->y1 - pres->y0);
2076                         }
2077
2078                         if (!opj_sparse_array_int32_write(sa, x, y,
2079                                                           x + cblk_w, y + cblk_h,
2080                                                           cblk->decoded_data,
2081                                                           1, cblk_w, OPJ_TRUE)) {
2082                             opj_sparse_array_int32_free(sa);
2083                             return NULL;
2084                         }
2085                     }
2086                 }
2087             }
2088         }
2089     }
2090
2091     return sa;
2092 }
2093
2094
2095 static OPJ_BOOL opj_dwt_decode_partial_tile(
2096     opj_tcd_tilecomp_t* tilec,
2097     OPJ_UINT32 numres)
2098 {
2099     opj_sparse_array_int32_t* sa;
2100     opj_dwt_t h;
2101     opj_dwt_t v;
2102     OPJ_UINT32 resno;
2103     /* This value matches the maximum left/right extension given in tables */
2104     /* F.2 and F.3 of the standard. */
2105     const OPJ_UINT32 filter_width = 2U;
2106
2107     opj_tcd_resolution_t* tr = tilec->resolutions;
2108     opj_tcd_resolution_t* tr_max = &(tilec->resolutions[numres - 1]);
2109
2110     OPJ_UINT32 rw = (OPJ_UINT32)(tr->x1 -
2111                                  tr->x0);  /* width of the resolution level computed */
2112     OPJ_UINT32 rh = (OPJ_UINT32)(tr->y1 -
2113                                  tr->y0);  /* height of the resolution level computed */
2114
2115     OPJ_SIZE_T h_mem_size;
2116
2117     /* Compute the intersection of the area of interest, expressed in tile coordinates */
2118     /* with the tile coordinates */
2119     OPJ_UINT32 win_tcx0 = tilec->win_x0;
2120     OPJ_UINT32 win_tcy0 = tilec->win_y0;
2121     OPJ_UINT32 win_tcx1 = tilec->win_x1;
2122     OPJ_UINT32 win_tcy1 = tilec->win_y1;
2123
2124     if (tr_max->x0 == tr_max->x1 || tr_max->y0 == tr_max->y1) {
2125         return OPJ_TRUE;
2126     }
2127
2128     sa = opj_dwt_init_sparse_array(tilec, numres);
2129     if (sa == NULL) {
2130         return OPJ_FALSE;
2131     }
2132
2133     if (numres == 1U) {
2134         OPJ_BOOL ret = opj_sparse_array_int32_read(sa,
2135                        tr_max->win_x0 - (OPJ_UINT32)tr_max->x0,
2136                        tr_max->win_y0 - (OPJ_UINT32)tr_max->y0,
2137                        tr_max->win_x1 - (OPJ_UINT32)tr_max->x0,
2138                        tr_max->win_y1 - (OPJ_UINT32)tr_max->y0,
2139                        tilec->data_win,
2140                        1, tr_max->win_x1 - tr_max->win_x0,
2141                        OPJ_TRUE);
2142         assert(ret);
2143         OPJ_UNUSED(ret);
2144         opj_sparse_array_int32_free(sa);
2145         return OPJ_TRUE;
2146     }
2147     h_mem_size = opj_dwt_max_resolution(tr, numres);
2148     /* overflow check */
2149     /* in vertical pass, we process 4 columns at a time */
2150     if (h_mem_size > (SIZE_MAX / (4 * sizeof(OPJ_INT32)))) {
2151         /* FIXME event manager error callback */
2152         opj_sparse_array_int32_free(sa);
2153         return OPJ_FALSE;
2154     }
2155
2156     h_mem_size *= 4 * sizeof(OPJ_INT32);
2157     h.mem = (OPJ_INT32*)opj_aligned_32_malloc(h_mem_size);
2158     if (! h.mem) {
2159         /* FIXME event manager error callback */
2160         opj_sparse_array_int32_free(sa);
2161         return OPJ_FALSE;
2162     }
2163
2164     v.mem = h.mem;
2165
2166     for (resno = 1; resno < numres; resno ++) {
2167         OPJ_UINT32 i, j;
2168         /* Window of interest subband-based coordinates */
2169         OPJ_UINT32 win_ll_x0, win_ll_y0, win_ll_x1, win_ll_y1;
2170         OPJ_UINT32 win_hl_x0, win_hl_x1;
2171         OPJ_UINT32 win_lh_y0, win_lh_y1;
2172         /* Window of interest tile-resolution-based coordinates */
2173         OPJ_UINT32 win_tr_x0, win_tr_x1, win_tr_y0, win_tr_y1;
2174         /* Tile-resolution subband-based coordinates */
2175         OPJ_UINT32 tr_ll_x0, tr_ll_y0, tr_hl_x0, tr_lh_y0;
2176
2177         ++tr;
2178
2179         h.sn = (OPJ_INT32)rw;
2180         v.sn = (OPJ_INT32)rh;
2181
2182         rw = (OPJ_UINT32)(tr->x1 - tr->x0);
2183         rh = (OPJ_UINT32)(tr->y1 - tr->y0);
2184
2185         h.dn = (OPJ_INT32)(rw - (OPJ_UINT32)h.sn);
2186         h.cas = tr->x0 % 2;
2187
2188         v.dn = (OPJ_INT32)(rh - (OPJ_UINT32)v.sn);
2189         v.cas = tr->y0 % 2;
2190
2191         /* Get the subband coordinates for the window of interest */
2192         /* LL band */
2193         opj_dwt_get_band_coordinates(tilec, resno, 0,
2194                                      win_tcx0, win_tcy0, win_tcx1, win_tcy1,
2195                                      &win_ll_x0, &win_ll_y0,
2196                                      &win_ll_x1, &win_ll_y1);
2197
2198         /* HL band */
2199         opj_dwt_get_band_coordinates(tilec, resno, 1,
2200                                      win_tcx0, win_tcy0, win_tcx1, win_tcy1,
2201                                      &win_hl_x0, NULL, &win_hl_x1, NULL);
2202
2203         /* LH band */
2204         opj_dwt_get_band_coordinates(tilec, resno, 2,
2205                                      win_tcx0, win_tcy0, win_tcx1, win_tcy1,
2206                                      NULL, &win_lh_y0, NULL, &win_lh_y1);
2207
2208         /* Beware: band index for non-LL0 resolution are 0=HL, 1=LH and 2=HH */
2209         tr_ll_x0 = (OPJ_UINT32)tr->bands[1].x0;
2210         tr_ll_y0 = (OPJ_UINT32)tr->bands[0].y0;
2211         tr_hl_x0 = (OPJ_UINT32)tr->bands[0].x0;
2212         tr_lh_y0 = (OPJ_UINT32)tr->bands[1].y0;
2213
2214         /* Subtract the origin of the bands for this tile, to the subwindow */
2215         /* of interest band coordinates, so as to get them relative to the */
2216         /* tile */
2217         win_ll_x0 = opj_uint_subs(win_ll_x0, tr_ll_x0);
2218         win_ll_y0 = opj_uint_subs(win_ll_y0, tr_ll_y0);
2219         win_ll_x1 = opj_uint_subs(win_ll_x1, tr_ll_x0);
2220         win_ll_y1 = opj_uint_subs(win_ll_y1, tr_ll_y0);
2221         win_hl_x0 = opj_uint_subs(win_hl_x0, tr_hl_x0);
2222         win_hl_x1 = opj_uint_subs(win_hl_x1, tr_hl_x0);
2223         win_lh_y0 = opj_uint_subs(win_lh_y0, tr_lh_y0);
2224         win_lh_y1 = opj_uint_subs(win_lh_y1, tr_lh_y0);
2225
2226         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)h.sn, &win_ll_x0, &win_ll_x1);
2227         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)h.dn, &win_hl_x0, &win_hl_x1);
2228
2229         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)v.sn, &win_ll_y0, &win_ll_y1);
2230         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)v.dn, &win_lh_y0, &win_lh_y1);
2231
2232         /* Compute the tile-resolution-based coordinates for the window of interest */
2233         if (h.cas == 0) {
2234             win_tr_x0 = opj_uint_min(2 * win_ll_x0, 2 * win_hl_x0 + 1);
2235             win_tr_x1 = opj_uint_min(opj_uint_max(2 * win_ll_x1, 2 * win_hl_x1 + 1), rw);
2236         } else {
2237             win_tr_x0 = opj_uint_min(2 * win_hl_x0, 2 * win_ll_x0 + 1);
2238             win_tr_x1 = opj_uint_min(opj_uint_max(2 * win_hl_x1, 2 * win_ll_x1 + 1), rw);
2239         }
2240
2241         if (v.cas == 0) {
2242             win_tr_y0 = opj_uint_min(2 * win_ll_y0, 2 * win_lh_y0 + 1);
2243             win_tr_y1 = opj_uint_min(opj_uint_max(2 * win_ll_y1, 2 * win_lh_y1 + 1), rh);
2244         } else {
2245             win_tr_y0 = opj_uint_min(2 * win_lh_y0, 2 * win_ll_y0 + 1);
2246             win_tr_y1 = opj_uint_min(opj_uint_max(2 * win_lh_y1, 2 * win_ll_y1 + 1), rh);
2247         }
2248
2249         for (j = 0; j < rh; ++j) {
2250             if ((j >= win_ll_y0 && j < win_ll_y1) ||
2251                     (j >= win_lh_y0 + (OPJ_UINT32)v.sn && j < win_lh_y1 + (OPJ_UINT32)v.sn)) {
2252
2253                 /* Avoids dwt.c:1584:44 (in opj_dwt_decode_partial_1): runtime error: */
2254                 /* signed integer overflow: -1094795586 + -1094795586 cannot be represented in type 'int' */
2255                 /* on opj_decompress -i  ../../openjpeg/MAPA.jp2 -o out.tif -d 0,0,256,256 */
2256                 /* This is less extreme than memsetting the whole buffer to 0 */
2257                 /* although we could potentially do better with better handling of edge conditions */
2258                 if (win_tr_x1 >= 1 && win_tr_x1 < rw) {
2259                     h.mem[win_tr_x1 - 1] = 0;
2260                 }
2261                 if (win_tr_x1 < rw) {
2262                     h.mem[win_tr_x1] = 0;
2263                 }
2264
2265                 opj_dwt_interleave_partial_h(h.mem,
2266                                              h.cas,
2267                                              sa,
2268                                              j,
2269                                              (OPJ_UINT32)h.sn,
2270                                              win_ll_x0,
2271                                              win_ll_x1,
2272                                              win_hl_x0,
2273                                              win_hl_x1);
2274                 opj_dwt_decode_partial_1(h.mem, h.dn, h.sn, h.cas,
2275                                          (OPJ_INT32)win_ll_x0,
2276                                          (OPJ_INT32)win_ll_x1,
2277                                          (OPJ_INT32)win_hl_x0,
2278                                          (OPJ_INT32)win_hl_x1);
2279                 if (!opj_sparse_array_int32_write(sa,
2280                                                   win_tr_x0, j,
2281                                                   win_tr_x1, j + 1,
2282                                                   h.mem + win_tr_x0,
2283                                                   1, 0, OPJ_TRUE)) {
2284                     /* FIXME event manager error callback */
2285                     opj_sparse_array_int32_free(sa);
2286                     opj_aligned_free(h.mem);
2287                     return OPJ_FALSE;
2288                 }
2289             }
2290         }
2291
2292         for (i = win_tr_x0; i < win_tr_x1;) {
2293             OPJ_UINT32 nb_cols = opj_uint_min(4U, win_tr_x1 - i);
2294             opj_dwt_interleave_partial_v(v.mem,
2295                                          v.cas,
2296                                          sa,
2297                                          i,
2298                                          nb_cols,
2299                                          (OPJ_UINT32)v.sn,
2300                                          win_ll_y0,
2301                                          win_ll_y1,
2302                                          win_lh_y0,
2303                                          win_lh_y1);
2304             opj_dwt_decode_partial_1_parallel(v.mem, nb_cols, v.dn, v.sn, v.cas,
2305                                               (OPJ_INT32)win_ll_y0,
2306                                               (OPJ_INT32)win_ll_y1,
2307                                               (OPJ_INT32)win_lh_y0,
2308                                               (OPJ_INT32)win_lh_y1);
2309             if (!opj_sparse_array_int32_write(sa,
2310                                               i, win_tr_y0,
2311                                               i + nb_cols, win_tr_y1,
2312                                               v.mem + 4 * win_tr_y0,
2313                                               1, 4, OPJ_TRUE)) {
2314                 /* FIXME event manager error callback */
2315                 opj_sparse_array_int32_free(sa);
2316                 opj_aligned_free(h.mem);
2317                 return OPJ_FALSE;
2318             }
2319
2320             i += nb_cols;
2321         }
2322     }
2323     opj_aligned_free(h.mem);
2324
2325     {
2326         OPJ_BOOL ret = opj_sparse_array_int32_read(sa,
2327                        tr_max->win_x0 - (OPJ_UINT32)tr_max->x0,
2328                        tr_max->win_y0 - (OPJ_UINT32)tr_max->y0,
2329                        tr_max->win_x1 - (OPJ_UINT32)tr_max->x0,
2330                        tr_max->win_y1 - (OPJ_UINT32)tr_max->y0,
2331                        tilec->data_win,
2332                        1, tr_max->win_x1 - tr_max->win_x0,
2333                        OPJ_TRUE);
2334         assert(ret);
2335         OPJ_UNUSED(ret);
2336     }
2337     opj_sparse_array_int32_free(sa);
2338     return OPJ_TRUE;
2339 }
2340
2341 static void opj_v4dwt_interleave_h(opj_v4dwt_t* OPJ_RESTRICT dwt,
2342                                    OPJ_FLOAT32* OPJ_RESTRICT a,
2343                                    OPJ_UINT32 width,
2344                                    OPJ_UINT32 remaining_height)
2345 {
2346     OPJ_FLOAT32* OPJ_RESTRICT bi = (OPJ_FLOAT32*)(dwt->wavelet + dwt->cas);
2347     OPJ_UINT32 i, k;
2348     OPJ_UINT32 x0 = dwt->win_l_x0;
2349     OPJ_UINT32 x1 = dwt->win_l_x1;
2350
2351     for (k = 0; k < 2; ++k) {
2352         if (remaining_height >= 4 && ((OPJ_SIZE_T) a & 0x0f) == 0 &&
2353                 ((OPJ_SIZE_T) bi & 0x0f) == 0 && (width & 0x0f) == 0) {
2354             /* Fast code path */
2355             for (i = x0; i < x1; ++i) {
2356                 OPJ_UINT32 j = i;
2357                 bi[i * 8    ] = a[j];
2358                 j += width;
2359                 bi[i * 8 + 1] = a[j];
2360                 j += width;
2361                 bi[i * 8 + 2] = a[j];
2362                 j += width;
2363                 bi[i * 8 + 3] = a[j];
2364             }
2365         } else {
2366             /* Slow code path */
2367             for (i = x0; i < x1; ++i) {
2368                 OPJ_UINT32 j = i;
2369                 bi[i * 8    ] = a[j];
2370                 j += width;
2371                 if (remaining_height == 1) {
2372                     continue;
2373                 }
2374                 bi[i * 8 + 1] = a[j];
2375                 j += width;
2376                 if (remaining_height == 2) {
2377                     continue;
2378                 }
2379                 bi[i * 8 + 2] = a[j];
2380                 j += width;
2381                 if (remaining_height == 3) {
2382                     continue;
2383                 }
2384                 bi[i * 8 + 3] = a[j]; /* This one*/
2385             }
2386         }
2387
2388         bi = (OPJ_FLOAT32*)(dwt->wavelet + 1 - dwt->cas);
2389         a += dwt->sn;
2390         x0 = dwt->win_h_x0;
2391         x1 = dwt->win_h_x1;
2392     }
2393 }
2394
2395 static void opj_v4dwt_interleave_partial_h(opj_v4dwt_t* dwt,
2396         opj_sparse_array_int32_t* sa,
2397         OPJ_UINT32 sa_line,
2398         OPJ_UINT32 remaining_height)
2399 {
2400     OPJ_UINT32 i;
2401     for (i = 0; i < remaining_height; i++) {
2402         OPJ_BOOL ret;
2403         ret = opj_sparse_array_int32_read(sa,
2404                                           dwt->win_l_x0, sa_line + i,
2405                                           dwt->win_l_x1, sa_line + i + 1,
2406                                           /* Nasty cast from float* to int32* */
2407                                           (OPJ_INT32*)(dwt->wavelet + dwt->cas + 2 * dwt->win_l_x0) + i,
2408                                           8, 0, OPJ_TRUE);
2409         assert(ret);
2410         ret = opj_sparse_array_int32_read(sa,
2411                                           (OPJ_UINT32)dwt->sn + dwt->win_h_x0, sa_line + i,
2412                                           (OPJ_UINT32)dwt->sn + dwt->win_h_x1, sa_line + i + 1,
2413                                           /* Nasty cast from float* to int32* */
2414                                           (OPJ_INT32*)(dwt->wavelet + 1 - dwt->cas + 2 * dwt->win_h_x0) + i,
2415                                           8, 0, OPJ_TRUE);
2416         assert(ret);
2417         OPJ_UNUSED(ret);
2418     }
2419 }
2420
2421 static void opj_v4dwt_interleave_v(opj_v4dwt_t* OPJ_RESTRICT dwt,
2422                                    OPJ_FLOAT32* OPJ_RESTRICT a,
2423                                    OPJ_UINT32 width,
2424                                    OPJ_UINT32 nb_elts_read)
2425 {
2426     opj_v4_t* OPJ_RESTRICT bi = dwt->wavelet + dwt->cas;
2427     OPJ_UINT32 i;
2428
2429     for (i = dwt->win_l_x0; i < dwt->win_l_x1; ++i) {
2430         memcpy(&bi[i * 2], &a[i * (OPJ_SIZE_T)width],
2431                (OPJ_SIZE_T)nb_elts_read * sizeof(OPJ_FLOAT32));
2432     }
2433
2434     a += (OPJ_UINT32)dwt->sn * (OPJ_SIZE_T)width;
2435     bi = dwt->wavelet + 1 - dwt->cas;
2436
2437     for (i = dwt->win_h_x0; i < dwt->win_h_x1; ++i) {
2438         memcpy(&bi[i * 2], &a[i * (OPJ_SIZE_T)width],
2439                (OPJ_SIZE_T)nb_elts_read * sizeof(OPJ_FLOAT32));
2440     }
2441 }
2442
2443 static void opj_v4dwt_interleave_partial_v(opj_v4dwt_t* OPJ_RESTRICT dwt,
2444         opj_sparse_array_int32_t* sa,
2445         OPJ_UINT32 sa_col,
2446         OPJ_UINT32 nb_elts_read)
2447 {
2448     OPJ_BOOL ret;
2449     ret = opj_sparse_array_int32_read(sa,
2450                                       sa_col, dwt->win_l_x0,
2451                                       sa_col + nb_elts_read, dwt->win_l_x1,
2452                                       (OPJ_INT32*)(dwt->wavelet + dwt->cas + 2 * dwt->win_l_x0),
2453                                       1, 8, OPJ_TRUE);
2454     assert(ret);
2455     ret = opj_sparse_array_int32_read(sa,
2456                                       sa_col, (OPJ_UINT32)dwt->sn + dwt->win_h_x0,
2457                                       sa_col + nb_elts_read, (OPJ_UINT32)dwt->sn + dwt->win_h_x1,
2458                                       (OPJ_INT32*)(dwt->wavelet + 1 - dwt->cas + 2 * dwt->win_h_x0),
2459                                       1, 8, OPJ_TRUE);
2460     assert(ret);
2461     OPJ_UNUSED(ret);
2462 }
2463
2464 #ifdef __SSE__
2465
2466 static void opj_v4dwt_decode_step1_sse(opj_v4_t* w,
2467                                        OPJ_UINT32 start,
2468                                        OPJ_UINT32 end,
2469                                        const __m128 c)
2470 {
2471     __m128* OPJ_RESTRICT vw = (__m128*) w;
2472     OPJ_UINT32 i;
2473     /* 4x unrolled loop */
2474     vw += 2 * start;
2475     for (i = start; i + 3 < end; i += 4, vw += 8) {
2476         __m128 xmm0 = _mm_mul_ps(vw[0], c);
2477         __m128 xmm2 = _mm_mul_ps(vw[2], c);
2478         __m128 xmm4 = _mm_mul_ps(vw[4], c);
2479         __m128 xmm6 = _mm_mul_ps(vw[6], c);
2480         vw[0] = xmm0;
2481         vw[2] = xmm2;
2482         vw[4] = xmm4;
2483         vw[6] = xmm6;
2484     }
2485     for (; i < end; ++i, vw += 2) {
2486         vw[0] = _mm_mul_ps(vw[0], c);
2487     }
2488 }
2489
2490 static void opj_v4dwt_decode_step2_sse(opj_v4_t* l, opj_v4_t* w,
2491                                        OPJ_UINT32 start,
2492                                        OPJ_UINT32 end,
2493                                        OPJ_UINT32 m,
2494                                        __m128 c)
2495 {
2496     __m128* OPJ_RESTRICT vl = (__m128*) l;
2497     __m128* OPJ_RESTRICT vw = (__m128*) w;
2498     OPJ_UINT32 i;
2499     OPJ_UINT32 imax = opj_uint_min(end, m);
2500     __m128 tmp1, tmp2, tmp3;
2501     if (start == 0) {
2502         tmp1 = vl[0];
2503     } else {
2504         vw += start * 2;
2505         tmp1 = vw[-3];
2506     }
2507
2508     i = start;
2509
2510     /* 4x loop unrolling */
2511     for (; i + 3 < imax; i += 4) {
2512         __m128 tmp4, tmp5, tmp6, tmp7, tmp8, tmp9;
2513         tmp2 = vw[-1];
2514         tmp3 = vw[ 0];
2515         tmp4 = vw[ 1];
2516         tmp5 = vw[ 2];
2517         tmp6 = vw[ 3];
2518         tmp7 = vw[ 4];
2519         tmp8 = vw[ 5];
2520         tmp9 = vw[ 6];
2521         vw[-1] = _mm_add_ps(tmp2, _mm_mul_ps(_mm_add_ps(tmp1, tmp3), c));
2522         vw[ 1] = _mm_add_ps(tmp4, _mm_mul_ps(_mm_add_ps(tmp3, tmp5), c));
2523         vw[ 3] = _mm_add_ps(tmp6, _mm_mul_ps(_mm_add_ps(tmp5, tmp7), c));
2524         vw[ 5] = _mm_add_ps(tmp8, _mm_mul_ps(_mm_add_ps(tmp7, tmp9), c));
2525         tmp1 = tmp9;
2526         vw += 8;
2527     }
2528
2529     for (; i < imax; ++i) {
2530         tmp2 = vw[-1];
2531         tmp3 = vw[ 0];
2532         vw[-1] = _mm_add_ps(tmp2, _mm_mul_ps(_mm_add_ps(tmp1, tmp3), c));
2533         tmp1 = tmp3;
2534         vw += 2;
2535     }
2536     if (m < end) {
2537         assert(m + 1 == end);
2538         c = _mm_add_ps(c, c);
2539         c = _mm_mul_ps(c, vw[-2]);
2540         vw[-1] = _mm_add_ps(vw[-1], c);
2541     }
2542 }
2543
2544 #else
2545
2546 static void opj_v4dwt_decode_step1(opj_v4_t* w,
2547                                    OPJ_UINT32 start,
2548                                    OPJ_UINT32 end,
2549                                    const OPJ_FLOAT32 c)
2550 {
2551     OPJ_FLOAT32* OPJ_RESTRICT fw = (OPJ_FLOAT32*) w;
2552     OPJ_UINT32 i;
2553     for (i = start; i < end; ++i) {
2554         OPJ_FLOAT32 tmp1 = fw[i * 8    ];
2555         OPJ_FLOAT32 tmp2 = fw[i * 8 + 1];
2556         OPJ_FLOAT32 tmp3 = fw[i * 8 + 2];
2557         OPJ_FLOAT32 tmp4 = fw[i * 8 + 3];
2558         fw[i * 8    ] = tmp1 * c;
2559         fw[i * 8 + 1] = tmp2 * c;
2560         fw[i * 8 + 2] = tmp3 * c;
2561         fw[i * 8 + 3] = tmp4 * c;
2562     }
2563 }
2564
2565 static void opj_v4dwt_decode_step2(opj_v4_t* l, opj_v4_t* w,
2566                                    OPJ_UINT32 start,
2567                                    OPJ_UINT32 end,
2568                                    OPJ_UINT32 m,
2569                                    OPJ_FLOAT32 c)
2570 {
2571     OPJ_FLOAT32* fl = (OPJ_FLOAT32*) l;
2572     OPJ_FLOAT32* fw = (OPJ_FLOAT32*) w;
2573     OPJ_UINT32 i;
2574     OPJ_UINT32 imax = opj_uint_min(end, m);
2575     if (start > 0) {
2576         fw += 8 * start;
2577         fl = fw - 8;
2578     }
2579     for (i = start; i < imax; ++i) {
2580         OPJ_FLOAT32 tmp1_1 = fl[0];
2581         OPJ_FLOAT32 tmp1_2 = fl[1];
2582         OPJ_FLOAT32 tmp1_3 = fl[2];
2583         OPJ_FLOAT32 tmp1_4 = fl[3];
2584         OPJ_FLOAT32 tmp2_1 = fw[-4];
2585         OPJ_FLOAT32 tmp2_2 = fw[-3];
2586         OPJ_FLOAT32 tmp2_3 = fw[-2];
2587         OPJ_FLOAT32 tmp2_4 = fw[-1];
2588         OPJ_FLOAT32 tmp3_1 = fw[0];
2589         OPJ_FLOAT32 tmp3_2 = fw[1];
2590         OPJ_FLOAT32 tmp3_3 = fw[2];
2591         OPJ_FLOAT32 tmp3_4 = fw[3];
2592         fw[-4] = tmp2_1 + ((tmp1_1 + tmp3_1) * c);
2593         fw[-3] = tmp2_2 + ((tmp1_2 + tmp3_2) * c);
2594         fw[-2] = tmp2_3 + ((tmp1_3 + tmp3_3) * c);
2595         fw[-1] = tmp2_4 + ((tmp1_4 + tmp3_4) * c);
2596         fl = fw;
2597         fw += 8;
2598     }
2599     if (m < end) {
2600         assert(m + 1 == end);
2601         c += c;
2602         fw[-4] = fw[-4] + fl[0] * c;
2603         fw[-3] = fw[-3] + fl[1] * c;
2604         fw[-2] = fw[-2] + fl[2] * c;
2605         fw[-1] = fw[-1] + fl[3] * c;
2606     }
2607 }
2608
2609 #endif
2610
2611 /* <summary>                             */
2612 /* Inverse 9-7 wavelet transform in 1-D. */
2613 /* </summary>                            */
2614 static void opj_v4dwt_decode(opj_v4dwt_t* OPJ_RESTRICT dwt)
2615 {
2616     OPJ_INT32 a, b;
2617     if (dwt->cas == 0) {
2618         if (!((dwt->dn > 0) || (dwt->sn > 1))) {
2619             return;
2620         }
2621         a = 0;
2622         b = 1;
2623     } else {
2624         if (!((dwt->sn > 0) || (dwt->dn > 1))) {
2625             return;
2626         }
2627         a = 1;
2628         b = 0;
2629     }
2630 #ifdef __SSE__
2631     opj_v4dwt_decode_step1_sse(dwt->wavelet + a, dwt->win_l_x0, dwt->win_l_x1,
2632                                _mm_set1_ps(opj_K));
2633     opj_v4dwt_decode_step1_sse(dwt->wavelet + b, dwt->win_h_x0, dwt->win_h_x1,
2634                                _mm_set1_ps(opj_c13318));
2635     opj_v4dwt_decode_step2_sse(dwt->wavelet + b, dwt->wavelet + a + 1,
2636                                dwt->win_l_x0, dwt->win_l_x1,
2637                                (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
2638                                _mm_set1_ps(-opj_dwt_delta));
2639     opj_v4dwt_decode_step2_sse(dwt->wavelet + a, dwt->wavelet + b + 1,
2640                                dwt->win_h_x0, dwt->win_h_x1,
2641                                (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
2642                                _mm_set1_ps(-opj_dwt_gamma));
2643     opj_v4dwt_decode_step2_sse(dwt->wavelet + b, dwt->wavelet + a + 1,
2644                                dwt->win_l_x0, dwt->win_l_x1,
2645                                (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
2646                                _mm_set1_ps(-opj_dwt_beta));
2647     opj_v4dwt_decode_step2_sse(dwt->wavelet + a, dwt->wavelet + b + 1,
2648                                dwt->win_h_x0, dwt->win_h_x1,
2649                                (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
2650                                _mm_set1_ps(-opj_dwt_alpha));
2651 #else
2652     opj_v4dwt_decode_step1(dwt->wavelet + a, dwt->win_l_x0, dwt->win_l_x1,
2653                            opj_K);
2654     opj_v4dwt_decode_step1(dwt->wavelet + b, dwt->win_h_x0, dwt->win_h_x1,
2655                            opj_c13318);
2656     opj_v4dwt_decode_step2(dwt->wavelet + b, dwt->wavelet + a + 1,
2657                            dwt->win_l_x0, dwt->win_l_x1,
2658                            (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
2659                            -opj_dwt_delta);
2660     opj_v4dwt_decode_step2(dwt->wavelet + a, dwt->wavelet + b + 1,
2661                            dwt->win_h_x0, dwt->win_h_x1,
2662                            (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
2663                            -opj_dwt_gamma);
2664     opj_v4dwt_decode_step2(dwt->wavelet + b, dwt->wavelet + a + 1,
2665                            dwt->win_l_x0, dwt->win_l_x1,
2666                            (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
2667                            -opj_dwt_beta);
2668     opj_v4dwt_decode_step2(dwt->wavelet + a, dwt->wavelet + b + 1,
2669                            dwt->win_h_x0, dwt->win_h_x1,
2670                            (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
2671                            -opj_dwt_alpha);
2672 #endif
2673 }
2674
2675
2676 /* <summary>                             */
2677 /* Inverse 9-7 wavelet transform in 2-D. */
2678 /* </summary>                            */
2679 static
2680 OPJ_BOOL opj_dwt_decode_tile_97(opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
2681                                 OPJ_UINT32 numres)
2682 {
2683     opj_v4dwt_t h;
2684     opj_v4dwt_t v;
2685
2686     opj_tcd_resolution_t* res = tilec->resolutions;
2687
2688     OPJ_UINT32 rw = (OPJ_UINT32)(res->x1 -
2689                                  res->x0);    /* width of the resolution level computed */
2690     OPJ_UINT32 rh = (OPJ_UINT32)(res->y1 -
2691                                  res->y0);    /* height of the resolution level computed */
2692
2693     OPJ_UINT32 w = (OPJ_UINT32)(tilec->resolutions[tilec->minimum_num_resolutions -
2694                                                                1].x1 -
2695                                 tilec->resolutions[tilec->minimum_num_resolutions - 1].x0);
2696
2697     OPJ_SIZE_T l_data_size;
2698
2699     l_data_size = opj_dwt_max_resolution(res, numres);
2700     /* overflow check */
2701     if (l_data_size > (SIZE_MAX - 5U)) {
2702         /* FIXME event manager error callback */
2703         return OPJ_FALSE;
2704     }
2705     l_data_size += 5U;
2706     /* overflow check */
2707     if (l_data_size > (SIZE_MAX / sizeof(opj_v4_t))) {
2708         /* FIXME event manager error callback */
2709         return OPJ_FALSE;
2710     }
2711     h.wavelet = (opj_v4_t*) opj_aligned_malloc(l_data_size * sizeof(opj_v4_t));
2712     if (!h.wavelet) {
2713         /* FIXME event manager error callback */
2714         return OPJ_FALSE;
2715     }
2716     v.wavelet = h.wavelet;
2717
2718     while (--numres) {
2719         OPJ_FLOAT32 * OPJ_RESTRICT aj = (OPJ_FLOAT32*) tilec->data;
2720         OPJ_UINT32 j;
2721
2722         h.sn = (OPJ_INT32)rw;
2723         v.sn = (OPJ_INT32)rh;
2724
2725         ++res;
2726
2727         rw = (OPJ_UINT32)(res->x1 -
2728                           res->x0);   /* width of the resolution level computed */
2729         rh = (OPJ_UINT32)(res->y1 -
2730                           res->y0);   /* height of the resolution level computed */
2731
2732         h.dn = (OPJ_INT32)(rw - (OPJ_UINT32)h.sn);
2733         h.cas = res->x0 % 2;
2734
2735         h.win_l_x0 = 0;
2736         h.win_l_x1 = (OPJ_UINT32)h.sn;
2737         h.win_h_x0 = 0;
2738         h.win_h_x1 = (OPJ_UINT32)h.dn;
2739         for (j = 0; j + 3 < rh; j += 4) {
2740             OPJ_UINT32 k;
2741             opj_v4dwt_interleave_h(&h, aj, w, rh - j);
2742             opj_v4dwt_decode(&h);
2743
2744             for (k = 0; k < rw; k++) {
2745                 aj[k      ] = h.wavelet[k].f[0];
2746                 aj[k + (OPJ_SIZE_T)w  ] = h.wavelet[k].f[1];
2747                 aj[k + (OPJ_SIZE_T)w * 2] = h.wavelet[k].f[2];
2748                 aj[k + (OPJ_SIZE_T)w * 3] = h.wavelet[k].f[3];
2749             }
2750
2751             aj += w * 4;
2752         }
2753
2754         if (j < rh) {
2755             OPJ_UINT32 k;
2756             opj_v4dwt_interleave_h(&h, aj, w, rh - j);
2757             opj_v4dwt_decode(&h);
2758             for (k = 0; k < rw; k++) {
2759                 switch (rh - j) {
2760                 case 3:
2761                     aj[k + (OPJ_SIZE_T)w * 2] = h.wavelet[k].f[2];
2762                 /* FALLTHRU */
2763                 case 2:
2764                     aj[k + (OPJ_SIZE_T)w  ] = h.wavelet[k].f[1];
2765                 /* FALLTHRU */
2766                 case 1:
2767                     aj[k] = h.wavelet[k].f[0];
2768                 }
2769             }
2770         }
2771
2772         v.dn = (OPJ_INT32)(rh - (OPJ_UINT32)v.sn);
2773         v.cas = res->y0 % 2;
2774         v.win_l_x0 = 0;
2775         v.win_l_x1 = (OPJ_UINT32)v.sn;
2776         v.win_h_x0 = 0;
2777         v.win_h_x1 = (OPJ_UINT32)v.dn;
2778
2779         aj = (OPJ_FLOAT32*) tilec->data;
2780         for (j = rw; j > 3; j -= 4) {
2781             OPJ_UINT32 k;
2782
2783             opj_v4dwt_interleave_v(&v, aj, w, 4);
2784             opj_v4dwt_decode(&v);
2785
2786             for (k = 0; k < rh; ++k) {
2787                 memcpy(&aj[k * (OPJ_SIZE_T)w], &v.wavelet[k], 4 * sizeof(OPJ_FLOAT32));
2788             }
2789             aj += 4;
2790         }
2791
2792         if (rw & 0x03) {
2793             OPJ_UINT32 k;
2794
2795             j = rw & 0x03;
2796
2797             opj_v4dwt_interleave_v(&v, aj, w, j);
2798             opj_v4dwt_decode(&v);
2799
2800             for (k = 0; k < rh; ++k) {
2801                 memcpy(&aj[k * (OPJ_SIZE_T)w], &v.wavelet[k],
2802                        (OPJ_SIZE_T)j * sizeof(OPJ_FLOAT32));
2803             }
2804         }
2805     }
2806
2807     opj_aligned_free(h.wavelet);
2808     return OPJ_TRUE;
2809 }
2810
2811 static
2812 OPJ_BOOL opj_dwt_decode_partial_97(opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
2813                                    OPJ_UINT32 numres)
2814 {
2815     opj_sparse_array_int32_t* sa;
2816     opj_v4dwt_t h;
2817     opj_v4dwt_t v;
2818     OPJ_UINT32 resno;
2819     /* This value matches the maximum left/right extension given in tables */
2820     /* F.2 and F.3 of the standard. Note: in opj_tcd_is_subband_area_of_interest() */
2821     /* we currently use 3. */
2822     const OPJ_UINT32 filter_width = 4U;
2823
2824     opj_tcd_resolution_t* tr = tilec->resolutions;
2825     opj_tcd_resolution_t* tr_max = &(tilec->resolutions[numres - 1]);
2826
2827     OPJ_UINT32 rw = (OPJ_UINT32)(tr->x1 -
2828                                  tr->x0);    /* width of the resolution level computed */
2829     OPJ_UINT32 rh = (OPJ_UINT32)(tr->y1 -
2830                                  tr->y0);    /* height of the resolution level computed */
2831
2832     OPJ_SIZE_T l_data_size;
2833
2834     /* Compute the intersection of the area of interest, expressed in tile coordinates */
2835     /* with the tile coordinates */
2836     OPJ_UINT32 win_tcx0 = tilec->win_x0;
2837     OPJ_UINT32 win_tcy0 = tilec->win_y0;
2838     OPJ_UINT32 win_tcx1 = tilec->win_x1;
2839     OPJ_UINT32 win_tcy1 = tilec->win_y1;
2840
2841     if (tr_max->x0 == tr_max->x1 || tr_max->y0 == tr_max->y1) {
2842         return OPJ_TRUE;
2843     }
2844
2845     sa = opj_dwt_init_sparse_array(tilec, numres);
2846     if (sa == NULL) {
2847         return OPJ_FALSE;
2848     }
2849
2850     if (numres == 1U) {
2851         OPJ_BOOL ret = opj_sparse_array_int32_read(sa,
2852                        tr_max->win_x0 - (OPJ_UINT32)tr_max->x0,
2853                        tr_max->win_y0 - (OPJ_UINT32)tr_max->y0,
2854                        tr_max->win_x1 - (OPJ_UINT32)tr_max->x0,
2855                        tr_max->win_y1 - (OPJ_UINT32)tr_max->y0,
2856                        tilec->data_win,
2857                        1, tr_max->win_x1 - tr_max->win_x0,
2858                        OPJ_TRUE);
2859         assert(ret);
2860         OPJ_UNUSED(ret);
2861         opj_sparse_array_int32_free(sa);
2862         return OPJ_TRUE;
2863     }
2864
2865     l_data_size = opj_dwt_max_resolution(tr, numres);
2866     /* overflow check */
2867     if (l_data_size > (SIZE_MAX - 5U)) {
2868         /* FIXME event manager error callback */
2869         opj_sparse_array_int32_free(sa);
2870         return OPJ_FALSE;
2871     }
2872     l_data_size += 5U;
2873     /* overflow check */
2874     if (l_data_size > (SIZE_MAX / sizeof(opj_v4_t))) {
2875         /* FIXME event manager error callback */
2876         opj_sparse_array_int32_free(sa);
2877         return OPJ_FALSE;
2878     }
2879     h.wavelet = (opj_v4_t*) opj_aligned_malloc(l_data_size * sizeof(opj_v4_t));
2880     if (!h.wavelet) {
2881         /* FIXME event manager error callback */
2882         opj_sparse_array_int32_free(sa);
2883         return OPJ_FALSE;
2884     }
2885     v.wavelet = h.wavelet;
2886
2887     for (resno = 1; resno < numres; resno ++) {
2888         OPJ_UINT32 j;
2889         /* Window of interest subband-based coordinates */
2890         OPJ_UINT32 win_ll_x0, win_ll_y0, win_ll_x1, win_ll_y1;
2891         OPJ_UINT32 win_hl_x0, win_hl_x1;
2892         OPJ_UINT32 win_lh_y0, win_lh_y1;
2893         /* Window of interest tile-resolution-based coordinates */
2894         OPJ_UINT32 win_tr_x0, win_tr_x1, win_tr_y0, win_tr_y1;
2895         /* Tile-resolution subband-based coordinates */
2896         OPJ_UINT32 tr_ll_x0, tr_ll_y0, tr_hl_x0, tr_lh_y0;
2897
2898         ++tr;
2899
2900         h.sn = (OPJ_INT32)rw;
2901         v.sn = (OPJ_INT32)rh;
2902
2903         rw = (OPJ_UINT32)(tr->x1 - tr->x0);
2904         rh = (OPJ_UINT32)(tr->y1 - tr->y0);
2905
2906         h.dn = (OPJ_INT32)(rw - (OPJ_UINT32)h.sn);
2907         h.cas = tr->x0 % 2;
2908
2909         v.dn = (OPJ_INT32)(rh - (OPJ_UINT32)v.sn);
2910         v.cas = tr->y0 % 2;
2911
2912         /* Get the subband coordinates for the window of interest */
2913         /* LL band */
2914         opj_dwt_get_band_coordinates(tilec, resno, 0,
2915                                      win_tcx0, win_tcy0, win_tcx1, win_tcy1,
2916                                      &win_ll_x0, &win_ll_y0,
2917                                      &win_ll_x1, &win_ll_y1);
2918
2919         /* HL band */
2920         opj_dwt_get_band_coordinates(tilec, resno, 1,
2921                                      win_tcx0, win_tcy0, win_tcx1, win_tcy1,
2922                                      &win_hl_x0, NULL, &win_hl_x1, NULL);
2923
2924         /* LH band */
2925         opj_dwt_get_band_coordinates(tilec, resno, 2,
2926                                      win_tcx0, win_tcy0, win_tcx1, win_tcy1,
2927                                      NULL, &win_lh_y0, NULL, &win_lh_y1);
2928
2929         /* Beware: band index for non-LL0 resolution are 0=HL, 1=LH and 2=HH */
2930         tr_ll_x0 = (OPJ_UINT32)tr->bands[1].x0;
2931         tr_ll_y0 = (OPJ_UINT32)tr->bands[0].y0;
2932         tr_hl_x0 = (OPJ_UINT32)tr->bands[0].x0;
2933         tr_lh_y0 = (OPJ_UINT32)tr->bands[1].y0;
2934
2935         /* Subtract the origin of the bands for this tile, to the subwindow */
2936         /* of interest band coordinates, so as to get them relative to the */
2937         /* tile */
2938         win_ll_x0 = opj_uint_subs(win_ll_x0, tr_ll_x0);
2939         win_ll_y0 = opj_uint_subs(win_ll_y0, tr_ll_y0);
2940         win_ll_x1 = opj_uint_subs(win_ll_x1, tr_ll_x0);
2941         win_ll_y1 = opj_uint_subs(win_ll_y1, tr_ll_y0);
2942         win_hl_x0 = opj_uint_subs(win_hl_x0, tr_hl_x0);
2943         win_hl_x1 = opj_uint_subs(win_hl_x1, tr_hl_x0);
2944         win_lh_y0 = opj_uint_subs(win_lh_y0, tr_lh_y0);
2945         win_lh_y1 = opj_uint_subs(win_lh_y1, tr_lh_y0);
2946
2947         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)h.sn, &win_ll_x0, &win_ll_x1);
2948         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)h.dn, &win_hl_x0, &win_hl_x1);
2949
2950         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)v.sn, &win_ll_y0, &win_ll_y1);
2951         opj_dwt_segment_grow(filter_width, (OPJ_UINT32)v.dn, &win_lh_y0, &win_lh_y1);
2952
2953         /* Compute the tile-resolution-based coordinates for the window of interest */
2954         if (h.cas == 0) {
2955             win_tr_x0 = opj_uint_min(2 * win_ll_x0, 2 * win_hl_x0 + 1);
2956             win_tr_x1 = opj_uint_min(opj_uint_max(2 * win_ll_x1, 2 * win_hl_x1 + 1), rw);
2957         } else {
2958             win_tr_x0 = opj_uint_min(2 * win_hl_x0, 2 * win_ll_x0 + 1);
2959             win_tr_x1 = opj_uint_min(opj_uint_max(2 * win_hl_x1, 2 * win_ll_x1 + 1), rw);
2960         }
2961
2962         if (v.cas == 0) {
2963             win_tr_y0 = opj_uint_min(2 * win_ll_y0, 2 * win_lh_y0 + 1);
2964             win_tr_y1 = opj_uint_min(opj_uint_max(2 * win_ll_y1, 2 * win_lh_y1 + 1), rh);
2965         } else {
2966             win_tr_y0 = opj_uint_min(2 * win_lh_y0, 2 * win_ll_y0 + 1);
2967             win_tr_y1 = opj_uint_min(opj_uint_max(2 * win_lh_y1, 2 * win_ll_y1 + 1), rh);
2968         }
2969
2970         h.win_l_x0 = win_ll_x0;
2971         h.win_l_x1 = win_ll_x1;
2972         h.win_h_x0 = win_hl_x0;
2973         h.win_h_x1 = win_hl_x1;
2974         for (j = 0; j + 3 < rh; j += 4) {
2975             if ((j + 3 >= win_ll_y0 && j < win_ll_y1) ||
2976                     (j + 3 >= win_lh_y0 + (OPJ_UINT32)v.sn &&
2977                      j < win_lh_y1 + (OPJ_UINT32)v.sn)) {
2978                 opj_v4dwt_interleave_partial_h(&h, sa, j, opj_uint_min(4U, rh - j));
2979                 opj_v4dwt_decode(&h);
2980                 if (!opj_sparse_array_int32_write(sa,
2981                                                   win_tr_x0, j,
2982                                                   win_tr_x1, j + 4,
2983                                                   (OPJ_INT32*)&h.wavelet[win_tr_x0].f[0],
2984                                                   4, 1, OPJ_TRUE)) {
2985                     /* FIXME event manager error callback */
2986                     opj_sparse_array_int32_free(sa);
2987                     opj_aligned_free(h.wavelet);
2988                     return OPJ_FALSE;
2989                 }
2990             }
2991         }
2992
2993         if (j < rh &&
2994                 ((j + 3 >= win_ll_y0 && j < win_ll_y1) ||
2995                  (j + 3 >= win_lh_y0 + (OPJ_UINT32)v.sn &&
2996                   j < win_lh_y1 + (OPJ_UINT32)v.sn))) {
2997             opj_v4dwt_interleave_partial_h(&h, sa, j, rh - j);
2998             opj_v4dwt_decode(&h);
2999             if (!opj_sparse_array_int32_write(sa,
3000                                               win_tr_x0, j,
3001                                               win_tr_x1, rh,
3002                                               (OPJ_INT32*)&h.wavelet[win_tr_x0].f[0],
3003                                               4, 1, OPJ_TRUE)) {
3004                 /* FIXME event manager error callback */
3005                 opj_sparse_array_int32_free(sa);
3006                 opj_aligned_free(h.wavelet);
3007                 return OPJ_FALSE;
3008             }
3009         }
3010
3011         v.win_l_x0 = win_ll_y0;
3012         v.win_l_x1 = win_ll_y1;
3013         v.win_h_x0 = win_lh_y0;
3014         v.win_h_x1 = win_lh_y1;
3015         for (j = win_tr_x0; j < win_tr_x1; j += 4) {
3016             OPJ_UINT32 nb_elts = opj_uint_min(4U, win_tr_x1 - j);
3017
3018             opj_v4dwt_interleave_partial_v(&v, sa, j, nb_elts);
3019             opj_v4dwt_decode(&v);
3020
3021             if (!opj_sparse_array_int32_write(sa,
3022                                               j, win_tr_y0,
3023                                               j + nb_elts, win_tr_y1,
3024                                               (OPJ_INT32*)&h.wavelet[win_tr_y0].f[0],
3025                                               1, 4, OPJ_TRUE)) {
3026                 /* FIXME event manager error callback */
3027                 opj_sparse_array_int32_free(sa);
3028                 opj_aligned_free(h.wavelet);
3029                 return OPJ_FALSE;
3030             }
3031         }
3032     }
3033
3034     {
3035         OPJ_BOOL ret = opj_sparse_array_int32_read(sa,
3036                        tr_max->win_x0 - (OPJ_UINT32)tr_max->x0,
3037                        tr_max->win_y0 - (OPJ_UINT32)tr_max->y0,
3038                        tr_max->win_x1 - (OPJ_UINT32)tr_max->x0,
3039                        tr_max->win_y1 - (OPJ_UINT32)tr_max->y0,
3040                        tilec->data_win,
3041                        1, tr_max->win_x1 - tr_max->win_x0,
3042                        OPJ_TRUE);
3043         assert(ret);
3044         OPJ_UNUSED(ret);
3045     }
3046     opj_sparse_array_int32_free(sa);
3047
3048     opj_aligned_free(h.wavelet);
3049     return OPJ_TRUE;
3050 }
3051
3052
3053 OPJ_BOOL opj_dwt_decode_real(opj_tcd_t *p_tcd,
3054                              opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
3055                              OPJ_UINT32 numres)
3056 {
3057     if (p_tcd->whole_tile_decoding) {
3058         return opj_dwt_decode_tile_97(tilec, numres);
3059     } else {
3060         return opj_dwt_decode_partial_97(tilec, numres);
3061     }
3062 }