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