Fix windows arm builds
[openjpeg.git] / src / lib / openjp2 / ht_dec.c
1 //***************************************************************************/
2 // This software is released under the 2-Clause BSD license, included
3 // below.
4 //
5 // Copyright (c) 2021, Aous Naman
6 // Copyright (c) 2021, Kakadu Software Pty Ltd, Australia
7 // Copyright (c) 2021, The University of New South Wales, Australia
8 //
9 // Redistribution and use in source and binary forms, with or without
10 // modification, are permitted provided that the following conditions are
11 // met:
12 //
13 // 1. Redistributions of source code must retain the above copyright
14 // notice, this list of conditions and the following disclaimer.
15 //
16 // 2. Redistributions in binary form must reproduce the above copyright
17 // notice, this list of conditions and the following disclaimer in the
18 // documentation and/or other materials provided with the distribution.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
21 // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
23 // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
26 // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 //***************************************************************************/
32 // This file is part of the OpenJpeg software implementation.
33 // File: ht_dec.c
34 // Author: Aous Naman
35 // Date: 01 September 2021
36 //***************************************************************************/
37
38 //***************************************************************************/
39 /** @file ht_dec.c
40  *  @brief implements HTJ2K block decoder
41  */
42
43 #include <assert.h>
44 #include <string.h>
45 #include "opj_includes.h"
46
47 #include "t1_ht_luts.h"
48
49 /////////////////////////////////////////////////////////////////////////////
50 // compiler detection
51 /////////////////////////////////////////////////////////////////////////////
52 #ifdef _MSC_VER
53 #define OPJ_COMPILER_MSVC
54 #elif (defined __GNUC__)
55 #define OPJ_COMPILER_GNUC
56 #endif
57
58 //************************************************************************/
59 /** @brief Displays the error message for disabling the decoding of SPP and
60   * MRP passes
61   */
62 static OPJ_BOOL only_cleanup_pass_is_decoded = OPJ_FALSE;
63
64 //************************************************************************/
65 /** @brief Generates population count (i.e., the number of set bits)
66   *
67   *   @param [in]  val is the value for which population count is sought
68   */
69 static INLINE
70 OPJ_UINT32 population_count(OPJ_UINT32 val)
71 {
72 #if defined(OPJ_COMPILER_MSVC) && (defined(_M_IX86) || defined(_M_AMD64))
73     return (OPJ_UINT32)__popcnt(val);
74 #elif (defined OPJ_COMPILER_GNUC)
75     return (OPJ_UINT32)__builtin_popcount(val);
76 #else
77     val -= ((val >> 1) & 0x55555555);
78     val = (((val >> 2) & 0x33333333) + (val & 0x33333333));
79     val = (((val >> 4) + val) & 0x0f0f0f0f);
80     val += (val >> 8);
81     val += (val >> 16);
82     return (OPJ_UINT32)(val & 0x0000003f);
83 #endif
84 }
85
86 //************************************************************************/
87 /** @brief Counts the number of leading zeros
88   *
89   *   @param [in]  val is the value for which leading zero count is sought
90   */
91 #ifdef OPJ_COMPILER_MSVC
92 #pragma intrinsic(_BitScanReverse)
93 #endif
94 static INLINE
95 OPJ_UINT32 count_leading_zeros(OPJ_UINT32 val)
96 {
97 #ifdef OPJ_COMPILER_MSVC
98     unsigned long result = 0;
99     _BitScanReverse(&result, val);
100     return 31U ^ (OPJ_UINT32)result;
101 #elif (defined OPJ_COMPILER_GNUC)
102     return (OPJ_UINT32)__builtin_clz(val);
103 #else
104     val |= (val >> 1);
105     val |= (val >> 2);
106     val |= (val >> 4);
107     val |= (val >> 8);
108     val |= (val >> 16);
109     return 32U - population_count(val);
110 #endif
111 }
112
113 //************************************************************************/
114 /** @brief Read a little-endian serialized UINT32.
115   *
116   *   @param [in]  dataIn pointer to byte stream to read from
117   */
118 static INLINE OPJ_UINT32 read_le_uint32(const void* dataIn)
119 {
120 #if defined(OPJ_BIG_ENDIAN)
121     const OPJ_UINT8* data = (const OPJ_UINT8*)dataIn;
122     return ((OPJ_UINT32)data[0]) | (OPJ_UINT32)(data[1] << 8) | (OPJ_UINT32)(
123                data[2] << 16) | (((
124                                       OPJ_UINT32)data[3]) <<
125                                  24U);
126 #else
127     return *(OPJ_UINT32*)dataIn;
128 #endif
129 }
130
131 //************************************************************************/
132 /** @brief MEL state structure for reading and decoding the MEL bitstream
133   *
134   *  A number of events is decoded from the MEL bitstream ahead of time
135   *  and stored in run/num_runs.
136   *  Each run represents the number of zero events before a one event.
137   */
138 typedef struct dec_mel {
139     // data decoding machinery
140     OPJ_UINT8* data;  //!<the address of data (or bitstream)
141     OPJ_UINT64 tmp;   //!<temporary buffer for read data
142     int bits;         //!<number of bits stored in tmp
143     int size;         //!<number of bytes in MEL code
144     OPJ_BOOL unstuff; //!<true if the next bit needs to be unstuffed
145     int k;            //!<state of MEL decoder
146
147     // queue of decoded runs
148     int num_runs;    //!<number of decoded runs left in runs (maximum 8)
149     OPJ_UINT64 runs; //!<runs of decoded MEL codewords (7 bits/run)
150 } dec_mel_t;
151
152 //************************************************************************/
153 /** @brief Reads and unstuffs the MEL bitstream
154   *
155   *  This design needs more bytes in the codeblock buffer than the length
156   *  of the cleanup pass by up to 2 bytes.
157   *
158   *  Unstuffing removes the MSB of the byte following a byte whose
159   *  value is 0xFF; this prevents sequences larger than 0xFF7F in value
160   *  from appearing the bitstream.
161   *
162   *  @param [in]  melp is a pointer to dec_mel_t structure
163   */
164 static INLINE
165 void mel_read(dec_mel_t *melp)
166 {
167     OPJ_UINT32 val;
168     int bits;
169     OPJ_UINT32 t;
170     OPJ_BOOL unstuff;
171
172     if (melp->bits > 32) { //there are enough bits in the tmp variable
173         return;    // return without reading new data
174     }
175
176     val = 0xFFFFFFFF;      // feed in 0xFF if buffer is exhausted
177     if (melp->size > 4) {  // if there is more than 4 bytes the MEL segment
178         val = read_le_uint32(melp->data);  // read 32 bits from MEL data
179         melp->data += 4;           // advance pointer
180         melp->size -= 4;           // reduce counter
181     } else if (melp->size > 0) { // 4 or less
182         OPJ_UINT32 m, v;
183         int i = 0;
184         while (melp->size > 1) {
185             OPJ_UINT32 v = *melp->data++; // read one byte at a time
186             OPJ_UINT32 m = ~(0xFFu << i); // mask of location
187             val = (val & m) | (v << i);   // put byte in its correct location
188             --melp->size;
189             i += 8;
190         }
191         // size equal to 1
192         v = *melp->data++;  // the one before the last is different
193         v |= 0xF;                         // MEL and VLC segments can overlap
194         m = ~(0xFFu << i);
195         val = (val & m) | (v << i);
196         --melp->size;
197     }
198
199     // next we unstuff them before adding them to the buffer
200     bits = 32 - melp->unstuff;      // number of bits in val, subtract 1 if
201     // the previously read byte requires
202     // unstuffing
203
204     // data is unstuffed and accumulated in t
205     // bits has the number of bits in t
206     t = val & 0xFF;
207     unstuff = ((val & 0xFF) == 0xFF); // true if the byte needs unstuffing
208     bits -= unstuff; // there is one less bit in t if unstuffing is needed
209     t = t << (8 - unstuff); // move up to make room for the next byte
210
211     //this is a repeat of the above
212     t |= (val >> 8) & 0xFF;
213     unstuff = (((val >> 8) & 0xFF) == 0xFF);
214     bits -= unstuff;
215     t = t << (8 - unstuff);
216
217     t |= (val >> 16) & 0xFF;
218     unstuff = (((val >> 16) & 0xFF) == 0xFF);
219     bits -= unstuff;
220     t = t << (8 - unstuff);
221
222     t |= (val >> 24) & 0xFF;
223     melp->unstuff = (((val >> 24) & 0xFF) == 0xFF);
224
225     // move t to tmp, and push the result all the way up, so we read from
226     // the MSB
227     melp->tmp |= ((OPJ_UINT64)t) << (64 - bits - melp->bits);
228     melp->bits += bits; //increment the number of bits in tmp
229 }
230
231 //************************************************************************/
232 /** @brief Decodes unstuffed MEL segment bits stored in tmp to runs
233   *
234   *  Runs are stored in "runs" and the number of runs in "num_runs".
235   *  Each run represents a number of zero events that may or may not
236   *  terminate in a 1 event.
237   *  Each run is stored in 7 bits.  The LSB is 1 if the run terminates in
238   *  a 1 event, 0 otherwise.  The next 6 bits, for the case terminating
239   *  with 1, contain the number of consecutive 0 zero events * 2; for the
240   *  case terminating with 0, they store (number of consecutive 0 zero
241   *  events - 1) * 2.
242   *  A total of 6 bits (made up of 1 + 5) should have been enough.
243   *
244   *  @param [in]  melp is a pointer to dec_mel_t structure
245   */
246 static INLINE
247 void mel_decode(dec_mel_t *melp)
248 {
249     static const int mel_exp[13] = { //MEL exponents
250         0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5
251     };
252
253     if (melp->bits < 6) { // if there are less than 6 bits in tmp
254         mel_read(melp);    // then read from the MEL bitstream
255     }
256     // 6 bits is the largest decodable MEL cwd
257
258     //repeat so long that there is enough decodable bits in tmp,
259     // and the runs store is not full (num_runs < 8)
260     while (melp->bits >= 6 && melp->num_runs < 8) {
261         int eval = mel_exp[melp->k]; // number of bits associated with state
262         int run = 0;
263         if (melp->tmp & (1ull << 63)) { //The next bit to decode (stored in MSB)
264             //one is found
265             run = 1 << eval;
266             run--; // consecutive runs of 0 events - 1
267             melp->k = melp->k + 1 < 12 ? melp->k + 1 : 12;//increment, max is 12
268             melp->tmp <<= 1; // consume one bit from tmp
269             melp->bits -= 1;
270             run = run << 1; // a stretch of zeros not terminating in one
271         } else {
272             //0 is found
273             run = (int)(melp->tmp >> (63 - eval)) & ((1 << eval) - 1);
274             melp->k = melp->k - 1 > 0 ? melp->k - 1 : 0; //decrement, min is 0
275             melp->tmp <<= eval + 1; //consume eval + 1 bits (max is 6)
276             melp->bits -= eval + 1;
277             run = (run << 1) + 1; // a stretch of zeros terminating with one
278         }
279         eval = melp->num_runs * 7;                 // 7 bits per run
280         melp->runs &= ~((OPJ_UINT64)0x3F << eval); // 6 bits are sufficient
281         melp->runs |= ((OPJ_UINT64)run) << eval;   // store the value in runs
282         melp->num_runs++;                          // increment count
283     }
284 }
285
286 //************************************************************************/
287 /** @brief Initiates a dec_mel_t structure for MEL decoding and reads
288   *         some bytes in order to get the read address to a multiple
289   *         of 4
290   *
291   *  @param [in]  melp is a pointer to dec_mel_t structure
292   *  @param [in]  bbuf is a pointer to byte buffer
293   *  @param [in]  lcup is the length of MagSgn+MEL+VLC segments
294   *  @param [in]  scup is the length of MEL+VLC segments
295   */
296 static INLINE
297 void mel_init(dec_mel_t *melp, OPJ_UINT8* bbuf, int lcup, int scup)
298 {
299     int num;
300     int i;
301
302     melp->data = bbuf + lcup - scup; // move the pointer to the start of MEL
303     melp->bits = 0;                  // 0 bits in tmp
304     melp->tmp = 0;                   //
305     melp->unstuff = OPJ_FALSE;       // no unstuffing
306     melp->size = scup - 1;           // size is the length of MEL+VLC-1
307     melp->k = 0;                     // 0 for state
308     melp->num_runs = 0;              // num_runs is 0
309     melp->runs = 0;                  //
310
311     //This code is borrowed; original is for a different architecture
312     //These few lines take care of the case where data is not at a multiple
313     // of 4 boundary.  It reads 1,2,3 up to 4 bytes from the MEL segment
314     num = 4 - (int)((intptr_t)(melp->data) & 0x3);
315     for (i = 0; i < num; ++i) { // this code is similar to mel_read
316         OPJ_UINT64 d;
317         int d_bits;
318
319         assert(melp->unstuff == OPJ_FALSE || melp->data[0] <= 0x8F);
320         d = (melp->size > 0) ? *melp->data : 0xFF; // if buffer is consumed
321         // set data to 0xFF
322         if (melp->size == 1) {
323             d |= 0xF;    //if this is MEL+VLC-1, set LSBs to 0xF
324         }
325         // see the standard
326         melp->data += melp->size-- > 0; //increment if the end is not reached
327         d_bits = 8 - melp->unstuff; //if unstuffing is needed, reduce by 1
328         melp->tmp = (melp->tmp << d_bits) | d; //store bits in tmp
329         melp->bits += d_bits;  //increment tmp by number of bits
330         melp->unstuff = ((d & 0xFF) == 0xFF); //true of next byte needs
331         //unstuffing
332     }
333     melp->tmp <<= (64 - melp->bits); //push all the way up so the first bit
334     // is the MSB
335 }
336
337 //************************************************************************/
338 /** @brief Retrieves one run from dec_mel_t; if there are no runs stored
339   *         MEL segment is decoded
340   *
341   * @param [in]  melp is a pointer to dec_mel_t structure
342   */
343 static INLINE
344 int mel_get_run(dec_mel_t *melp)
345 {
346     int t;
347     if (melp->num_runs == 0) { //if no runs, decode more bit from MEL segment
348         mel_decode(melp);
349     }
350
351     t = melp->runs & 0x7F; //retrieve one run
352     melp->runs >>= 7;  // remove the retrieved run
353     melp->num_runs--;
354     return t; // return run
355 }
356
357 //************************************************************************/
358 /** @brief A structure for reading and unstuffing a segment that grows
359   *         backward, such as VLC and MRP
360   */
361 typedef struct rev_struct {
362     //storage
363     OPJ_UINT8* data;  //!<pointer to where to read data
364     OPJ_UINT64 tmp;     //!<temporary buffer of read data
365     OPJ_UINT32 bits;  //!<number of bits stored in tmp
366     int size;         //!<number of bytes left
367     OPJ_BOOL unstuff; //!<true if the last byte is more than 0x8F
368     //!<then the current byte is unstuffed if it is 0x7F
369 } rev_struct_t;
370
371 //************************************************************************/
372 /** @brief Read and unstuff data from a backwardly-growing segment
373   *
374   *  This reader can read up to 8 bytes from before the VLC segment.
375   *  Care must be taken not read from unreadable memory, causing a
376   *  segmentation fault.
377   *
378   *  Note that there is another subroutine rev_read_mrp that is slightly
379   *  different.  The other one fills zeros when the buffer is exhausted.
380   *  This one basically does not care if the bytes are consumed, because
381   *  any extra data should not be used in the actual decoding.
382   *
383   *  Unstuffing is needed to prevent sequences more than 0xFF8F from
384   *  appearing in the bits stream; since we are reading backward, we keep
385   *  watch when a value larger than 0x8F appears in the bitstream.
386   *  If the byte following this is 0x7F, we unstuff this byte (ignore the
387   *  MSB of that byte, which should be 0).
388   *
389   *  @param [in]  vlcp is a pointer to rev_struct_t structure
390   */
391 static INLINE
392 void rev_read(rev_struct_t *vlcp)
393 {
394     OPJ_UINT32 val;
395     OPJ_UINT32 tmp;
396     OPJ_UINT32 bits;
397     OPJ_BOOL unstuff;
398
399     //process 4 bytes at a time
400     if (vlcp->bits > 32) { // if there are more than 32 bits in tmp, then
401         return;    // reading 32 bits can overflow vlcp->tmp
402     }
403     val = 0;
404     //the next line (the if statement) needs to be tested first
405     if (vlcp->size > 3) { // if there are more than 3 bytes left in VLC
406         // (vlcp->data - 3) move pointer back to read 32 bits at once
407         val = read_le_uint32(vlcp->data - 3); // then read 32 bits
408         vlcp->data -= 4;                // move data pointer back by 4
409         vlcp->size -= 4;                // reduce available byte by 4
410     } else if (vlcp->size > 0) { // 4 or less
411         int i = 24;
412         while (vlcp->size > 0) {
413             OPJ_UINT32 v = *vlcp->data--; // read one byte at a time
414             val |= (v << i);              // put byte in its correct location
415             --vlcp->size;
416             i -= 8;
417         }
418     }
419
420     //accumulate in tmp, number of bits in tmp are stored in bits
421     tmp = val >> 24;  //start with the MSB byte
422
423     // test unstuff (previous byte is >0x8F), and this byte is 0x7F
424     bits = 8u - ((vlcp->unstuff && (((val >> 24) & 0x7F) == 0x7F)) ? 1u : 0u);
425     unstuff = (val >> 24) > 0x8F; //this is for the next byte
426
427     tmp |= ((val >> 16) & 0xFF) << bits; //process the next byte
428     bits += 8u - ((unstuff && (((val >> 16) & 0x7F) == 0x7F)) ? 1u : 0u);
429     unstuff = ((val >> 16) & 0xFF) > 0x8F;
430
431     tmp |= ((val >> 8) & 0xFF) << bits;
432     bits += 8u - ((unstuff && (((val >> 8) & 0x7F) == 0x7F)) ? 1u : 0u);
433     unstuff = ((val >> 8) & 0xFF) > 0x8F;
434
435     tmp |= (val & 0xFF) << bits;
436     bits += 8u - ((unstuff && ((val & 0x7F) == 0x7F)) ? 1u : 0u);
437     unstuff = (val & 0xFF) > 0x8F;
438
439     // now move the read and unstuffed bits into vlcp->tmp
440     vlcp->tmp |= (OPJ_UINT64)tmp << vlcp->bits;
441     vlcp->bits += bits;
442     vlcp->unstuff = unstuff; // this for the next read
443 }
444
445 //************************************************************************/
446 /** @brief Initiates the rev_struct_t structure and reads a few bytes to
447   *         move the read address to multiple of 4
448   *
449   *  There is another similar rev_init_mrp subroutine.  The difference is
450   *  that this one, rev_init, discards the first 12 bits (they have the
451   *  sum of the lengths of VLC and MEL segments), and first unstuff depends
452   *  on first 4 bits.
453   *
454   *  @param [in]  vlcp is a pointer to rev_struct_t structure
455   *  @param [in]  data is a pointer to byte at the start of the cleanup pass
456   *  @param [in]  lcup is the length of MagSgn+MEL+VLC segments
457   *  @param [in]  scup is the length of MEL+VLC segments
458   */
459 static INLINE
460 void rev_init(rev_struct_t *vlcp, OPJ_UINT8* data, int lcup, int scup)
461 {
462     OPJ_UINT32 d;
463     int num, tnum, i;
464
465     //first byte has only the upper 4 bits
466     vlcp->data = data + lcup - 2;
467
468     //size can not be larger than this, in fact it should be smaller
469     vlcp->size = scup - 2;
470
471     d = *vlcp->data--;            // read one byte (this is a half byte)
472     vlcp->tmp = d >> 4;           // both initialize and set
473     vlcp->bits = 4 - ((vlcp->tmp & 7) == 7); //check standard
474     vlcp->unstuff = (d | 0xF) > 0x8F; //this is useful for the next byte
475
476     //This code is designed for an architecture that read address should
477     // align to the read size (address multiple of 4 if read size is 4)
478     //These few lines take care of the case where data is not at a multiple
479     // of 4 boundary. It reads 1,2,3 up to 4 bytes from the VLC bitstream.
480     // To read 32 bits, read from (vlcp->data - 3)
481     num = 1 + (int)((intptr_t)(vlcp->data) & 0x3);
482     tnum = num < vlcp->size ? num : vlcp->size;
483     for (i = 0; i < tnum; ++i) {
484         OPJ_UINT64 d;
485         OPJ_UINT32 d_bits;
486         d = *vlcp->data--;  // read one byte and move read pointer
487         //check if the last byte was >0x8F (unstuff == true) and this is 0x7F
488         d_bits = 8u - ((vlcp->unstuff && ((d & 0x7F) == 0x7F)) ? 1u : 0u);
489         vlcp->tmp |= d << vlcp->bits; // move data to vlcp->tmp
490         vlcp->bits += d_bits;
491         vlcp->unstuff = d > 0x8F; // for next byte
492     }
493     vlcp->size -= tnum;
494     rev_read(vlcp);  // read another 32 buts
495 }
496
497 //************************************************************************/
498 /** @brief Retrieves 32 bits from the head of a rev_struct structure
499   *
500   *  By the end of this call, vlcp->tmp must have no less than 33 bits
501   *
502   *  @param [in]  vlcp is a pointer to rev_struct structure
503   */
504 static INLINE
505 OPJ_UINT32 rev_fetch(rev_struct_t *vlcp)
506 {
507     if (vlcp->bits < 32) { // if there are less then 32 bits, read more
508         rev_read(vlcp);     // read 32 bits, but unstuffing might reduce this
509         if (vlcp->bits < 32) { // if there is still space in vlcp->tmp for 32 bits
510             rev_read(vlcp);    // read another 32
511         }
512     }
513     return (OPJ_UINT32)vlcp->tmp; // return the head (bottom-most) of vlcp->tmp
514 }
515
516 //************************************************************************/
517 /** @brief Consumes num_bits from a rev_struct structure
518   *
519   *  @param [in]  vlcp is a pointer to rev_struct structure
520   *  @param [in]  num_bits is the number of bits to be removed
521   */
522 static INLINE
523 OPJ_UINT32 rev_advance(rev_struct_t *vlcp, OPJ_UINT32 num_bits)
524 {
525     assert(num_bits <= vlcp->bits); // vlcp->tmp must have more than num_bits
526     vlcp->tmp >>= num_bits;         // remove bits
527     vlcp->bits -= num_bits;         // decrement the number of bits
528     return (OPJ_UINT32)vlcp->tmp;
529 }
530
531 //************************************************************************/
532 /** @brief Reads and unstuffs from rev_struct
533   *
534   *  This is different than rev_read in that this fills in zeros when the
535   *  the available data is consumed.  The other does not care about the
536   *  values when all data is consumed.
537   *
538   *  See rev_read for more information about unstuffing
539   *
540   *  @param [in]  mrp is a pointer to rev_struct structure
541   */
542 static INLINE
543 void rev_read_mrp(rev_struct_t *mrp)
544 {
545     OPJ_UINT32 val;
546     OPJ_UINT32 tmp;
547     OPJ_UINT32 bits;
548     OPJ_BOOL unstuff;
549
550     //process 4 bytes at a time
551     if (mrp->bits > 32) {
552         return;
553     }
554     val = 0;
555     if (mrp->size > 3) { // If there are 3 byte or more
556         // (mrp->data - 3) move pointer back to read 32 bits at once
557         val = read_le_uint32(mrp->data - 3); // read 32 bits
558         mrp->data -= 4;                      // move back pointer
559         mrp->size -= 4;                      // reduce count
560     } else if (mrp->size > 0) {
561         int i = 24;
562         while (mrp->size > 0) {
563             OPJ_UINT32 v = *mrp->data--; // read one byte at a time
564             val |= (v << i);             // put byte in its correct location
565             --mrp->size;
566             i -= 8;
567         }
568     }
569
570
571     //accumulate in tmp, and keep count in bits
572     tmp = val >> 24;
573
574     //test if the last byte > 0x8F (unstuff must be true) and this is 0x7F
575     bits = 8u - ((mrp->unstuff && (((val >> 24) & 0x7F) == 0x7F)) ? 1u : 0u);
576     unstuff = (val >> 24) > 0x8F;
577
578     //process the next byte
579     tmp |= ((val >> 16) & 0xFF) << bits;
580     bits += 8u - ((unstuff && (((val >> 16) & 0x7F) == 0x7F)) ? 1u : 0u);
581     unstuff = ((val >> 16) & 0xFF) > 0x8F;
582
583     tmp |= ((val >> 8) & 0xFF) << bits;
584     bits += 8u - ((unstuff && (((val >> 8) & 0x7F) == 0x7F)) ? 1u : 0u);
585     unstuff = ((val >> 8) & 0xFF) > 0x8F;
586
587     tmp |= (val & 0xFF) << bits;
588     bits += 8u - ((unstuff && ((val & 0x7F) == 0x7F)) ? 1u : 0u);
589     unstuff = (val & 0xFF) > 0x8F;
590
591     mrp->tmp |= (OPJ_UINT64)tmp << mrp->bits; // move data to mrp pointer
592     mrp->bits += bits;
593     mrp->unstuff = unstuff;                   // next byte
594 }
595
596 //************************************************************************/
597 /** @brief Initialized rev_struct structure for MRP segment, and reads
598   *         a number of bytes such that the next 32 bits read are from
599   *         an address that is a multiple of 4. Note this is designed for
600   *         an architecture that read size must be compatible with the
601   *         alignment of the read address
602   *
603   *  There is another similar subroutine rev_init.  This subroutine does
604   *  NOT skip the first 12 bits, and starts with unstuff set to true.
605   *
606   *  @param [in]  mrp is a pointer to rev_struct structure
607   *  @param [in]  data is a pointer to byte at the start of the cleanup pass
608   *  @param [in]  lcup is the length of MagSgn+MEL+VLC segments
609   *  @param [in]  len2 is the length of SPP+MRP segments
610   */
611 static INLINE
612 void rev_init_mrp(rev_struct_t *mrp, OPJ_UINT8* data, int lcup, int len2)
613 {
614     int num, i;
615
616     mrp->data = data + lcup + len2 - 1;
617     mrp->size = len2;
618     mrp->unstuff = OPJ_TRUE;
619     mrp->bits = 0;
620     mrp->tmp = 0;
621
622     //This code is designed for an architecture that read address should
623     // align to the read size (address multiple of 4 if read size is 4)
624     //These few lines take care of the case where data is not at a multiple
625     // of 4 boundary.  It reads 1,2,3 up to 4 bytes from the MRP stream
626     num = 1 + (int)((intptr_t)(mrp->data) & 0x3);
627     for (i = 0; i < num; ++i) {
628         OPJ_UINT64 d;
629         OPJ_UINT32 d_bits;
630
631         //read a byte, 0 if no more data
632         d = (mrp->size-- > 0) ? *mrp->data-- : 0;
633         //check if unstuffing is needed
634         d_bits = 8u - ((mrp->unstuff && ((d & 0x7F) == 0x7F)) ? 1u : 0u);
635         mrp->tmp |= d << mrp->bits; // move data to vlcp->tmp
636         mrp->bits += d_bits;
637         mrp->unstuff = d > 0x8F; // for next byte
638     }
639     rev_read_mrp(mrp);
640 }
641
642 //************************************************************************/
643 /** @brief Retrieves 32 bits from the head of a rev_struct structure
644   *
645   *  By the end of this call, mrp->tmp must have no less than 33 bits
646   *
647   *  @param [in]  mrp is a pointer to rev_struct structure
648   */
649 static INLINE
650 OPJ_UINT32 rev_fetch_mrp(rev_struct_t *mrp)
651 {
652     if (mrp->bits < 32) { // if there are less than 32 bits in mrp->tmp
653         rev_read_mrp(mrp);    // read 30-32 bits from mrp
654         if (mrp->bits < 32) { // if there is a space of 32 bits
655             rev_read_mrp(mrp);    // read more
656         }
657     }
658     return (OPJ_UINT32)mrp->tmp;  // return the head of mrp->tmp
659 }
660
661 //************************************************************************/
662 /** @brief Consumes num_bits from a rev_struct structure
663   *
664   *  @param [in]  mrp is a pointer to rev_struct structure
665   *  @param [in]  num_bits is the number of bits to be removed
666   */
667 static INLINE
668 OPJ_UINT32 rev_advance_mrp(rev_struct_t *mrp, OPJ_UINT32 num_bits)
669 {
670     assert(num_bits <= mrp->bits); // we must not consume more than mrp->bits
671     mrp->tmp >>= num_bits;         // discard the lowest num_bits bits
672     mrp->bits -= num_bits;
673     return (OPJ_UINT32)mrp->tmp;   // return data after consumption
674 }
675
676 //************************************************************************/
677 /** @brief Decode initial UVLC to get the u value (or u_q)
678   *
679   *  @param [in]  vlc is the head of the VLC bitstream
680   *  @param [in]  mode is 0, 1, 2, 3, or 4. Values in 0 to 3 are composed of
681   *               u_off of 1st quad and 2nd quad of a quad pair.  The value
682   *               4 occurs when both bits are 1, and the event decoded
683   *               from MEL bitstream is also 1.
684   *  @param [out] u is the u value (or u_q) + 1.  Note: we produce u + 1;
685   *               this value is a partial calculation of u + kappa.
686   */
687 static INLINE
688 OPJ_UINT32 decode_init_uvlc(OPJ_UINT32 vlc, OPJ_UINT32 mode, OPJ_UINT32 *u)
689 {
690     //table stores possible decoding three bits from vlc
691     // there are 8 entries for xx1, x10, 100, 000, where x means do not care
692     // table value is made up of
693     // 2 bits in the LSB for prefix length
694     // 3 bits for suffix length
695     // 3 bits in the MSB for prefix value (u_pfx in Table 3 of ITU T.814)
696     static const OPJ_UINT8 dec[8] = { // the index is the prefix codeword
697         3 | (5 << 2) | (5 << 5),        //000 == 000, prefix codeword "000"
698         1 | (0 << 2) | (1 << 5),        //001 == xx1, prefix codeword "1"
699         2 | (0 << 2) | (2 << 5),        //010 == x10, prefix codeword "01"
700         1 | (0 << 2) | (1 << 5),        //011 == xx1, prefix codeword "1"
701         3 | (1 << 2) | (3 << 5),        //100 == 100, prefix codeword "001"
702         1 | (0 << 2) | (1 << 5),        //101 == xx1, prefix codeword "1"
703         2 | (0 << 2) | (2 << 5),        //110 == x10, prefix codeword "01"
704         1 | (0 << 2) | (1 << 5)         //111 == xx1, prefix codeword "1"
705     };
706
707     OPJ_UINT32 consumed_bits = 0;
708     if (mode == 0) { // both u_off are 0
709         u[0] = u[1] = 1; //Kappa is 1 for initial line
710     } else if (mode <= 2) { // u_off are either 01 or 10
711         OPJ_UINT32 d;
712         OPJ_UINT32 suffix_len;
713
714         d = dec[vlc & 0x7];   //look at the least significant 3 bits
715         vlc >>= d & 0x3;                 //prefix length
716         consumed_bits += d & 0x3;
717
718         suffix_len = ((d >> 2) & 0x7);
719         consumed_bits += suffix_len;
720
721         d = (d >> 5) + (vlc & ((1U << suffix_len) - 1)); // u value
722         u[0] = (mode == 1) ? d + 1 : 1; // kappa is 1 for initial line
723         u[1] = (mode == 1) ? 1 : d + 1; // kappa is 1 for initial line
724     } else if (mode == 3) { // both u_off are 1, and MEL event is 0
725         OPJ_UINT32 d1 = dec[vlc & 0x7];  // LSBs of VLC are prefix codeword
726         vlc >>= d1 & 0x3;                // Consume bits
727         consumed_bits += d1 & 0x3;
728
729         if ((d1 & 0x3) > 2) {
730             OPJ_UINT32 suffix_len;
731
732             //u_{q_2} prefix
733             u[1] = (vlc & 1) + 1 + 1; //Kappa is 1 for initial line
734             ++consumed_bits;
735             vlc >>= 1;
736
737             suffix_len = ((d1 >> 2) & 0x7);
738             consumed_bits += suffix_len;
739             d1 = (d1 >> 5) + (vlc & ((1U << suffix_len) - 1)); // u value
740             u[0] = d1 + 1; //Kappa is 1 for initial line
741         } else {
742             OPJ_UINT32 d2;
743             OPJ_UINT32 suffix_len;
744
745             d2 = dec[vlc & 0x7];  // LSBs of VLC are prefix codeword
746             vlc >>= d2 & 0x3;                // Consume bits
747             consumed_bits += d2 & 0x3;
748
749             suffix_len = ((d1 >> 2) & 0x7);
750             consumed_bits += suffix_len;
751
752             d1 = (d1 >> 5) + (vlc & ((1U << suffix_len) - 1)); // u value
753             u[0] = d1 + 1; //Kappa is 1 for initial line
754             vlc >>= suffix_len;
755
756             suffix_len = ((d2 >> 2) & 0x7);
757             consumed_bits += suffix_len;
758
759             d2 = (d2 >> 5) + (vlc & ((1U << suffix_len) - 1)); // u value
760             u[1] = d2 + 1; //Kappa is 1 for initial line
761         }
762     } else if (mode == 4) { // both u_off are 1, and MEL event is 1
763         OPJ_UINT32 d1;
764         OPJ_UINT32 d2;
765         OPJ_UINT32 suffix_len;
766
767         d1 = dec[vlc & 0x7];  // LSBs of VLC are prefix codeword
768         vlc >>= d1 & 0x3;                // Consume bits
769         consumed_bits += d1 & 0x3;
770
771         d2 = dec[vlc & 0x7];  // LSBs of VLC are prefix codeword
772         vlc >>= d2 & 0x3;                // Consume bits
773         consumed_bits += d2 & 0x3;
774
775         suffix_len = ((d1 >> 2) & 0x7);
776         consumed_bits += suffix_len;
777
778         d1 = (d1 >> 5) + (vlc & ((1U << suffix_len) - 1)); // u value
779         u[0] = d1 + 3; // add 2+kappa
780         vlc >>= suffix_len;
781
782         suffix_len = ((d2 >> 2) & 0x7);
783         consumed_bits += suffix_len;
784
785         d2 = (d2 >> 5) + (vlc & ((1U << suffix_len) - 1)); // u value
786         u[1] = d2 + 3; // add 2+kappa
787     }
788     return consumed_bits;
789 }
790
791 //************************************************************************/
792 /** @brief Decode non-initial UVLC to get the u value (or u_q)
793   *
794   *  @param [in]  vlc is the head of the VLC bitstream
795   *  @param [in]  mode is 0, 1, 2, or 3. The 1st bit is u_off of 1st quad
796   *               and 2nd for 2nd quad of a quad pair
797   *  @param [out] u is the u value (or u_q) + 1.  Note: we produce u + 1;
798   *               this value is a partial calculation of u + kappa.
799   */
800 static INLINE
801 OPJ_UINT32 decode_noninit_uvlc(OPJ_UINT32 vlc, OPJ_UINT32 mode, OPJ_UINT32 *u)
802 {
803     //table stores possible decoding three bits from vlc
804     // there are 8 entries for xx1, x10, 100, 000, where x means do not care
805     // table value is made up of
806     // 2 bits in the LSB for prefix length
807     // 3 bits for suffix length
808     // 3 bits in the MSB for prefix value (u_pfx in Table 3 of ITU T.814)
809     static const OPJ_UINT8 dec[8] = {
810         3 | (5 << 2) | (5 << 5), //000 == 000, prefix codeword "000"
811         1 | (0 << 2) | (1 << 5), //001 == xx1, prefix codeword "1"
812         2 | (0 << 2) | (2 << 5), //010 == x10, prefix codeword "01"
813         1 | (0 << 2) | (1 << 5), //011 == xx1, prefix codeword "1"
814         3 | (1 << 2) | (3 << 5), //100 == 100, prefix codeword "001"
815         1 | (0 << 2) | (1 << 5), //101 == xx1, prefix codeword "1"
816         2 | (0 << 2) | (2 << 5), //110 == x10, prefix codeword "01"
817         1 | (0 << 2) | (1 << 5)  //111 == xx1, prefix codeword "1"
818     };
819
820     OPJ_UINT32 consumed_bits = 0;
821     if (mode == 0) {
822         u[0] = u[1] = 1; //for kappa
823     } else if (mode <= 2) { //u_off are either 01 or 10
824         OPJ_UINT32 d;
825         OPJ_UINT32 suffix_len;
826
827         d = dec[vlc & 0x7];  //look at the least significant 3 bits
828         vlc >>= d & 0x3;                //prefix length
829         consumed_bits += d & 0x3;
830
831         suffix_len = ((d >> 2) & 0x7);
832         consumed_bits += suffix_len;
833
834         d = (d >> 5) + (vlc & ((1U << suffix_len) - 1)); // u value
835         u[0] = (mode == 1) ? d + 1 : 1; //for kappa
836         u[1] = (mode == 1) ? 1 : d + 1; //for kappa
837     } else if (mode == 3) { // both u_off are 1
838         OPJ_UINT32 d1;
839         OPJ_UINT32 d2;
840         OPJ_UINT32 suffix_len;
841
842         d1 = dec[vlc & 0x7];  // LSBs of VLC are prefix codeword
843         vlc >>= d1 & 0x3;                // Consume bits
844         consumed_bits += d1 & 0x3;
845
846         d2 = dec[vlc & 0x7];  // LSBs of VLC are prefix codeword
847         vlc >>= d2 & 0x3;                // Consume bits
848         consumed_bits += d2 & 0x3;
849
850         suffix_len = ((d1 >> 2) & 0x7);
851         consumed_bits += suffix_len;
852
853         d1 = (d1 >> 5) + (vlc & ((1U << suffix_len) - 1)); // u value
854         u[0] = d1 + 1;  //1 for kappa
855         vlc >>= suffix_len;
856
857         suffix_len = ((d2 >> 2) & 0x7);
858         consumed_bits += suffix_len;
859
860         d2 = (d2 >> 5) + (vlc & ((1U << suffix_len) - 1)); // u value
861         u[1] = d2 + 1;  //1 for kappa
862     }
863     return consumed_bits;
864 }
865
866 //************************************************************************/
867 /** @brief State structure for reading and unstuffing of forward-growing
868   *         bitstreams; these are: MagSgn and SPP bitstreams
869   */
870 typedef struct frwd_struct {
871     const OPJ_UINT8* data; //!<pointer to bitstream
872     OPJ_UINT64 tmp;        //!<temporary buffer of read data
873     OPJ_UINT32 bits;       //!<number of bits stored in tmp
874     OPJ_BOOL unstuff;      //!<true if a bit needs to be unstuffed from next byte
875     int size;              //!<size of data
876     OPJ_UINT32 X;          //!<0 or 0xFF, X's are inserted at end of bitstream
877 } frwd_struct_t;
878
879 //************************************************************************/
880 /** @brief Read and unstuffs 32 bits from forward-growing bitstream
881   *
882   *  A subroutine to read from both the MagSgn or SPP bitstreams;
883   *  in particular, when MagSgn bitstream is consumed, 0xFF's are fed,
884   *  while when SPP is exhausted 0's are fed in.
885   *  X controls this value.
886   *
887   *  Unstuffing prevent sequences that are more than 0xFF7F from appearing
888   *  in the conpressed sequence.  So whenever a value of 0xFF is coded, the
889   *  MSB of the next byte is set 0 and must be ignored during decoding.
890   *
891   *  Reading can go beyond the end of buffer by up to 3 bytes.
892   *
893   *  @param  [in]  msp is a pointer to frwd_struct_t structure
894   *
895   */
896 static INLINE
897 void frwd_read(frwd_struct_t *msp)
898 {
899     OPJ_UINT32 val;
900     OPJ_UINT32 bits;
901     OPJ_UINT32 t;
902     OPJ_BOOL unstuff;
903
904     assert(msp->bits <= 32); // assert that there is a space for 32 bits
905
906     val = 0u;
907     if (msp->size > 3) {
908         val = read_le_uint32(msp->data);  // read 32 bits
909         msp->data += 4;           // increment pointer
910         msp->size -= 4;           // reduce size
911     } else if (msp->size > 0) {
912         int i = 0;
913         val = msp->X != 0 ? 0xFFFFFFFFu : 0;
914         while (msp->size > 0) {
915             OPJ_UINT32 v = *msp->data++;  // read one byte at a time
916             OPJ_UINT32 m = ~(0xFFu << i); // mask of location
917             val = (val & m) | (v << i);   // put one byte in its correct location
918             --msp->size;
919             i += 8;
920         }
921     } else {
922         val = msp->X != 0 ? 0xFFFFFFFFu : 0;
923     }
924
925     // we accumulate in t and keep a count of the number of bits in bits
926     bits = 8u - (msp->unstuff ? 1u : 0u);
927     t = val & 0xFF;
928     unstuff = ((val & 0xFF) == 0xFF);  // Do we need unstuffing next?
929
930     t |= ((val >> 8) & 0xFF) << bits;
931     bits += 8u - (unstuff ? 1u : 0u);
932     unstuff = (((val >> 8) & 0xFF) == 0xFF);
933
934     t |= ((val >> 16) & 0xFF) << bits;
935     bits += 8u - (unstuff ? 1u : 0u);
936     unstuff = (((val >> 16) & 0xFF) == 0xFF);
937
938     t |= ((val >> 24) & 0xFF) << bits;
939     bits += 8u - (unstuff ? 1u : 0u);
940     msp->unstuff = (((val >> 24) & 0xFF) == 0xFF); // for next byte
941
942     msp->tmp |= ((OPJ_UINT64)t) << msp->bits;  // move data to msp->tmp
943     msp->bits += bits;
944 }
945
946 //************************************************************************/
947 /** @brief Initialize frwd_struct_t struct and reads some bytes
948   *
949   *  @param [in]  msp is a pointer to frwd_struct_t
950   *  @param [in]  data is a pointer to the start of data
951   *  @param [in]  size is the number of byte in the bitstream
952   *  @param [in]  X is the value fed in when the bitstream is exhausted.
953   *               See frwd_read.
954   */
955 static INLINE
956 void frwd_init(frwd_struct_t *msp, const OPJ_UINT8* data, int size,
957                OPJ_UINT32 X)
958 {
959     int num, i;
960
961     msp->data = data;
962     msp->tmp = 0;
963     msp->bits = 0;
964     msp->unstuff = OPJ_FALSE;
965     msp->size = size;
966     msp->X = X;
967     assert(msp->X == 0 || msp->X == 0xFF);
968
969     //This code is designed for an architecture that read address should
970     // align to the read size (address multiple of 4 if read size is 4)
971     //These few lines take care of the case where data is not at a multiple
972     // of 4 boundary.  It reads 1,2,3 up to 4 bytes from the bitstream
973     num = 4 - (int)((intptr_t)(msp->data) & 0x3);
974     for (i = 0; i < num; ++i) {
975         OPJ_UINT64 d;
976         //read a byte if the buffer is not exhausted, otherwise set it to X
977         d = msp->size-- > 0 ? *msp->data++ : msp->X;
978         msp->tmp |= (d << msp->bits);      // store data in msp->tmp
979         msp->bits += 8u - (msp->unstuff ? 1u : 0u); // number of bits added to msp->tmp
980         msp->unstuff = ((d & 0xFF) == 0xFF); // unstuffing for next byte
981     }
982     frwd_read(msp); // read 32 bits more
983 }
984
985 //************************************************************************/
986 /** @brief Consume num_bits bits from the bitstream of frwd_struct_t
987   *
988   *  @param [in]  msp is a pointer to frwd_struct_t
989   *  @param [in]  num_bits is the number of bit to consume
990   */
991 static INLINE
992 void frwd_advance(frwd_struct_t *msp, OPJ_UINT32 num_bits)
993 {
994     assert(num_bits <= msp->bits);
995     msp->tmp >>= num_bits;  // consume num_bits
996     msp->bits -= num_bits;
997 }
998
999 //************************************************************************/
1000 /** @brief Fetches 32 bits from the frwd_struct_t bitstream
1001   *
1002   *  @param [in]  msp is a pointer to frwd_struct_t
1003   */
1004 static INLINE
1005 OPJ_UINT32 frwd_fetch(frwd_struct_t *msp)
1006 {
1007     if (msp->bits < 32) {
1008         frwd_read(msp);
1009         if (msp->bits < 32) { //need to test
1010             frwd_read(msp);
1011         }
1012     }
1013     return (OPJ_UINT32)msp->tmp;
1014 }
1015
1016 //************************************************************************/
1017 /** @brief Allocates T1 buffers
1018   *
1019   *  @param [in, out]  t1 is codeblock cofficients storage
1020   *  @param [in]       w is codeblock width
1021   *  @param [in]       h is codeblock height
1022   */
1023 static OPJ_BOOL opj_t1_allocate_buffers(
1024     opj_t1_t *t1,
1025     OPJ_UINT32 w,
1026     OPJ_UINT32 h)
1027 {
1028     OPJ_UINT32 flagssize;
1029
1030     /* No risk of overflow. Prior checks ensure those assert are met */
1031     /* They are per the specification */
1032     assert(w <= 1024);
1033     assert(h <= 1024);
1034     assert(w * h <= 4096);
1035
1036     /* encoder uses tile buffer, so no need to allocate */
1037     {
1038         OPJ_UINT32 datasize = w * h;
1039
1040         if (datasize > t1->datasize) {
1041             opj_aligned_free(t1->data);
1042             t1->data = (OPJ_INT32*)
1043                        opj_aligned_malloc(datasize * sizeof(OPJ_INT32));
1044             if (!t1->data) {
1045                 /* FIXME event manager error callback */
1046                 return OPJ_FALSE;
1047             }
1048             t1->datasize = datasize;
1049         }
1050         /* memset first arg is declared to never be null by gcc */
1051         if (t1->data != NULL) {
1052             memset(t1->data, 0, datasize * sizeof(OPJ_INT32));
1053         }
1054     }
1055
1056     // We expand these buffers to multiples of 16 bytes.
1057     // We need 4 buffers of 129 integers each, expanded to 132 integers each
1058     // We also need 514 bytes of buffer, expanded to 528 bytes
1059     flagssize = 132U * sizeof(OPJ_UINT32) * 4U; // expanded to multiple of 16
1060     flagssize += 528U; // 514 expanded to multiples of 16
1061
1062     {
1063         if (flagssize > t1->flagssize) {
1064
1065             opj_aligned_free(t1->flags);
1066             t1->flags = (opj_flag_t*) opj_aligned_malloc(flagssize);
1067             if (!t1->flags) {
1068                 /* FIXME event manager error callback */
1069                 return OPJ_FALSE;
1070             }
1071         }
1072         t1->flagssize = flagssize;
1073
1074         memset(t1->flags, 0, flagssize);
1075     }
1076
1077     t1->w = w;
1078     t1->h = h;
1079
1080     return OPJ_TRUE;
1081 }
1082
1083 //************************************************************************/
1084 /** @brief Decodes one codeblock, processing the cleanup, siginificance
1085   *         propagation, and magnitude refinement pass
1086   *
1087   *  @param [in, out]  t1 is codeblock cofficients storage
1088   *  @param [in]       cblk is codeblock properties
1089   *  @param [in]       orient is the subband to which the codeblock belongs (not needed)
1090   *  @param [in]       roishift is region of interest shift
1091   *  @param [in]       cblksty is codeblock style
1092   *  @param [in]       p_manager is events print manager
1093   *  @param [in]       p_manager_mutex a mutex to control access to p_manager
1094   *  @param [in]       check_pterm: check termination (not used)
1095   */
1096 OPJ_BOOL opj_t1_ht_decode_cblk(opj_t1_t *t1,
1097                                opj_tcd_cblk_dec_t* cblk,
1098                                OPJ_UINT32 orient,
1099                                OPJ_UINT32 roishift,
1100                                OPJ_UINT32 cblksty,
1101                                opj_event_mgr_t *p_manager,
1102                                opj_mutex_t* p_manager_mutex,
1103                                OPJ_BOOL check_pterm)
1104 {
1105     OPJ_BYTE* cblkdata = NULL;
1106     OPJ_UINT8* coded_data;
1107     OPJ_UINT32* decoded_data;
1108     OPJ_UINT32 zero_bplanes;
1109     OPJ_UINT32 num_passes;
1110     OPJ_UINT32 lengths1;
1111     OPJ_UINT32 lengths2;
1112     OPJ_INT32 width;
1113     OPJ_INT32 height;
1114     OPJ_INT32 stride;
1115     OPJ_UINT32 *pflags, *sigma1, *sigma2, *mbr1, *mbr2, *sip, sip_shift;
1116     OPJ_UINT32 p;
1117     OPJ_UINT32 zero_bplanes_p1;
1118     int lcup, scup;
1119     dec_mel_t mel;
1120     rev_struct_t vlc;
1121     frwd_struct_t magsgn;
1122     frwd_struct_t sigprop;
1123     rev_struct_t magref;
1124     OPJ_UINT8 *lsp, *line_state;
1125     int run;
1126     OPJ_UINT32 vlc_val;              // fetched data from VLC bitstream
1127     OPJ_UINT32 qinf[2];
1128     OPJ_UINT32 c_q;
1129     OPJ_UINT32* sp;
1130     OPJ_INT32 x, y; // loop indices
1131     OPJ_BOOL stripe_causal = (cblksty & J2K_CCP_CBLKSTY_VSC) != 0;
1132     OPJ_UINT32 cblk_len = 0;
1133
1134     (void)(orient);      // stops unused parameter message
1135     (void)(check_pterm); // stops unused parameter message
1136
1137     // We ignor orient, because the same decoder is used for all subbands
1138     // We also ignore check_pterm, because I am not sure how it applies
1139     if (roishift != 0) {
1140         if (p_manager_mutex) {
1141             opj_mutex_lock(p_manager_mutex);
1142         }
1143         opj_event_msg(p_manager, EVT_ERROR, "We do not support ROI in decoding "
1144                       "HT codeblocks\n");
1145         if (p_manager_mutex) {
1146             opj_mutex_unlock(p_manager_mutex);
1147         }
1148         return OPJ_FALSE;
1149     }
1150
1151     if (!opj_t1_allocate_buffers(
1152                 t1,
1153                 (OPJ_UINT32)(cblk->x1 - cblk->x0),
1154                 (OPJ_UINT32)(cblk->y1 - cblk->y0))) {
1155         return OPJ_FALSE;
1156     }
1157
1158     if (cblk->Mb == 0) {
1159         return OPJ_TRUE;
1160     }
1161
1162     /* numbps = Mb + 1 - zero_bplanes, Mb = Kmax, zero_bplanes = missing_msbs */
1163     zero_bplanes = (cblk->Mb + 1) - cblk->numbps;
1164
1165     /* Compute whole codeblock length from chunk lengths */
1166     cblk_len = 0;
1167     {
1168         OPJ_UINT32 i;
1169         for (i = 0; i < cblk->numchunks; i++) {
1170             cblk_len += cblk->chunks[i].len;
1171         }
1172     }
1173
1174     if (cblk->numchunks > 1 || t1->mustuse_cblkdatabuffer) {
1175         OPJ_UINT32 i;
1176
1177         /* Allocate temporary memory if needed */
1178         if (cblk_len > t1->cblkdatabuffersize) {
1179             cblkdata = (OPJ_BYTE*)opj_realloc(
1180                            t1->cblkdatabuffer, cblk_len);
1181             if (cblkdata == NULL) {
1182                 return OPJ_FALSE;
1183             }
1184             t1->cblkdatabuffer = cblkdata;
1185             t1->cblkdatabuffersize = cblk_len;
1186         }
1187
1188         /* Concatenate all chunks */
1189         cblkdata = t1->cblkdatabuffer;
1190         cblk_len = 0;
1191         for (i = 0; i < cblk->numchunks; i++) {
1192             memcpy(cblkdata + cblk_len, cblk->chunks[i].data, cblk->chunks[i].len);
1193             cblk_len += cblk->chunks[i].len;
1194         }
1195     } else if (cblk->numchunks == 1) {
1196         cblkdata = cblk->chunks[0].data;
1197     } else {
1198         /* Not sure if that can happen in practice, but avoid Coverity to */
1199         /* think we will dereference a null cblkdta pointer */
1200         return OPJ_TRUE;
1201     }
1202
1203     // OPJ_BYTE* coded_data is a pointer to bitstream
1204     coded_data = cblkdata;
1205     // OPJ_UINT32* decoded_data is a pointer to decoded codeblock data buf.
1206     decoded_data = (OPJ_UINT32*)t1->data;
1207     // OPJ_UINT32 num_passes is the number of passes: 1 if CUP only, 2 for
1208     // CUP+SPP, and 3 for CUP+SPP+MRP
1209     num_passes = cblk->numsegs > 0 ? cblk->segs[0].real_num_passes : 0;
1210     num_passes += cblk->numsegs > 1 ? cblk->segs[1].real_num_passes : 0;
1211     // OPJ_UINT32 lengths1 is the length of cleanup pass
1212     lengths1 = num_passes > 0 ? cblk->segs[0].len : 0;
1213     // OPJ_UINT32 lengths2 is the length of refinement passes (either SPP only or SPP+MRP)
1214     lengths2 = num_passes > 1 ? cblk->segs[1].len : 0;
1215     // OPJ_INT32 width is the decoded codeblock width
1216     width = cblk->x1 - cblk->x0;
1217     // OPJ_INT32 height is the decoded codeblock height
1218     height = cblk->y1 - cblk->y0;
1219     // OPJ_INT32 stride is the decoded codeblock buffer stride
1220     stride = width;
1221
1222     /*  sigma1 and sigma2 contains significant (i.e., non-zero) pixel
1223      *  locations.  The buffers are used interchangeably, because we need
1224      *  more than 4 rows of significance information at a given time.
1225      *  Each 32 bits contain significance information for 4 rows of 8
1226      *  columns each.  If we denote 32 bits by 0xaaaaaaaa, the each "a" is
1227      *  called a nibble and has significance information for 4 rows.
1228      *  The least significant nibble has information for the first column,
1229      *  and so on. The nibble's LSB is for the first row, and so on.
1230      *  Since, at most, we can have 1024 columns in a quad, we need 128
1231      *  entries; we added 1 for convenience when propagation of signifcance
1232      *  goes outside the structure
1233      *  To work in OpenJPEG these buffers has been expanded to 132.
1234      */
1235     // OPJ_UINT32 *pflags, *sigma1, *sigma2, *mbr1, *mbr2, *sip, sip_shift;
1236     pflags = (OPJ_UINT32 *)t1->flags;
1237     sigma1 = pflags;
1238     sigma2 = sigma1 + 132;
1239     // mbr arrangement is similar to sigma; mbr contains locations
1240     // that become significant during significance propagation pass
1241     mbr1 = sigma2 + 132;
1242     mbr2 = mbr1 + 132;
1243     //a pointer to sigma
1244     sip = sigma1;  //pointers to arrays to be used interchangeably
1245     sip_shift = 0; //the amount of shift needed for sigma
1246
1247     if (num_passes > 1 && lengths2 == 0) {
1248         if (p_manager_mutex) {
1249             opj_mutex_lock(p_manager_mutex);
1250         }
1251         opj_event_msg(p_manager, EVT_WARNING, "A malformed codeblock that has "
1252                       "more than one coding pass, but zero length for "
1253                       "2nd and potentially the 3rd pass in an HT codeblock.\n");
1254         if (p_manager_mutex) {
1255             opj_mutex_unlock(p_manager_mutex);
1256         }
1257         num_passes = 1;
1258     }
1259     if (num_passes > 3) {
1260         if (p_manager_mutex) {
1261             opj_mutex_lock(p_manager_mutex);
1262         }
1263         opj_event_msg(p_manager, EVT_ERROR, "We do not support more than 3 "
1264                       "coding passes in an HT codeblock; This codeblocks has "
1265                       "%d passes.\n", num_passes);
1266         if (p_manager_mutex) {
1267             opj_mutex_unlock(p_manager_mutex);
1268         }
1269         return OPJ_FALSE;
1270     }
1271
1272     if (cblk->Mb > 30) {
1273         /* This check is better moved to opj_t2_read_packet_header() in t2.c
1274            We do not have enough precision to decode any passes
1275            The design of openjpeg assumes that the bits of a 32-bit integer are
1276            assigned as follows:
1277            bit 31 is for sign
1278            bits 30-1 are for magnitude
1279            bit 0 is for the center of the quantization bin
1280            Therefore we can only do values of cblk->Mb <= 30
1281          */
1282         if (p_manager_mutex) {
1283             opj_mutex_lock(p_manager_mutex);
1284         }
1285         opj_event_msg(p_manager, EVT_ERROR, "32 bits are not enough to "
1286                       "decode this codeblock, since the number of "
1287                       "bitplane, %d, is larger than 30.\n", cblk->Mb);
1288         if (p_manager_mutex) {
1289             opj_mutex_unlock(p_manager_mutex);
1290         }
1291         return OPJ_FALSE;
1292     }
1293     if (zero_bplanes > cblk->Mb) {
1294         /* This check is better moved to opj_t2_read_packet_header() in t2.c,
1295            in the line "l_cblk->numbps = (OPJ_UINT32)l_band->numbps + 1 - i;"
1296            where i is the zero bitplanes, and should be no larger than cblk->Mb
1297            We cannot have more zero bitplanes than there are planes. */
1298         if (p_manager_mutex) {
1299             opj_mutex_lock(p_manager_mutex);
1300         }
1301         opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1302                       "Decoding this codeblock is stopped. There are "
1303                       "%d zero bitplanes in %d bitplanes.\n",
1304                       zero_bplanes, cblk->Mb);
1305
1306         if (p_manager_mutex) {
1307             opj_mutex_unlock(p_manager_mutex);
1308         }
1309         return OPJ_FALSE;
1310     } else if (zero_bplanes == cblk->Mb && num_passes > 1) {
1311         /* When the number of zero bitplanes is equal to the number of bitplanes,
1312            only the cleanup pass makes sense*/
1313         if (only_cleanup_pass_is_decoded == OPJ_FALSE) {
1314             if (p_manager_mutex) {
1315                 opj_mutex_lock(p_manager_mutex);
1316             }
1317             /* We have a second check to prevent the possibility of an overrun condition,
1318                in the very unlikely event of a second thread discovering that
1319                only_cleanup_pass_is_decoded is false before the first thread changing
1320                the condition. */
1321             if (only_cleanup_pass_is_decoded == OPJ_FALSE) {
1322                 only_cleanup_pass_is_decoded = OPJ_TRUE;
1323                 opj_event_msg(p_manager, EVT_WARNING, "Malformed HT codeblock. "
1324                               "When the number of zero planes bitplanes is "
1325                               "equal to the number of bitplanes, only the cleanup "
1326                               "pass makes sense, but we have %d passes in this "
1327                               "codeblock. Therefore, only the cleanup pass will be "
1328                               "decoded. This message will not be displayed again.\n",
1329                               num_passes);
1330             }
1331             if (p_manager_mutex) {
1332                 opj_mutex_unlock(p_manager_mutex);
1333             }
1334         }
1335         num_passes = 1;
1336     }
1337
1338     /* OPJ_UINT32 */
1339     p = cblk->numbps;
1340
1341     // OPJ_UINT32 zero planes plus 1
1342     zero_bplanes_p1 = zero_bplanes + 1;
1343
1344     if (lengths1 < 2 || (OPJ_UINT32)lengths1 > cblk_len ||
1345             (OPJ_UINT32)(lengths1 + lengths2) > cblk_len) {
1346         if (p_manager_mutex) {
1347             opj_mutex_lock(p_manager_mutex);
1348         }
1349         opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1350                       "Invalid codeblock length values.\n");
1351
1352         if (p_manager_mutex) {
1353             opj_mutex_unlock(p_manager_mutex);
1354         }
1355         return OPJ_FALSE;
1356     }
1357     // read scup and fix the bytes there
1358     lcup = (int)lengths1;  // length of CUP
1359     //scup is the length of MEL + VLC
1360     scup = (((int)coded_data[lcup - 1]) << 4) + (coded_data[lcup - 2] & 0xF);
1361     if (scup < 2 || scup > lcup || scup > 4079) { //something is wrong
1362         /* The standard stipulates 2 <= Scup <= min(Lcup, 4079) */
1363         if (p_manager_mutex) {
1364             opj_mutex_lock(p_manager_mutex);
1365         }
1366         opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1367                       "One of the following condition is not met: "
1368                       "2 <= Scup <= min(Lcup, 4079)\n");
1369
1370         if (p_manager_mutex) {
1371             opj_mutex_unlock(p_manager_mutex);
1372         }
1373         return OPJ_FALSE;
1374     }
1375
1376     // init structures
1377     mel_init(&mel, coded_data, lcup, scup);
1378     rev_init(&vlc, coded_data, lcup, scup);
1379     frwd_init(&magsgn, coded_data, lcup - scup, 0xFF);
1380     if (num_passes > 1) { // needs to be tested
1381         frwd_init(&sigprop, coded_data + lengths1, (int)lengths2, 0);
1382     }
1383     if (num_passes > 2) {
1384         rev_init_mrp(&magref, coded_data, (int)lengths1, (int)lengths2);
1385     }
1386
1387     /** State storage
1388       *  One byte per quad; for 1024 columns, or 512 quads, we need
1389       *  512 bytes. We are using 2 extra bytes one on the left and one on
1390       *  the right for convenience.
1391       *
1392       *  The MSB bit in each byte is (\sigma^nw | \sigma^n), and the 7 LSBs
1393       *  contain max(E^nw | E^n)
1394       */
1395
1396     // 514 is enough for a block width of 1024, +2 extra
1397     // here expanded to 528
1398     line_state = (OPJ_UINT8 *)(mbr2 + 132);
1399
1400     //initial 2 lines
1401     /////////////////
1402     lsp = line_state;              // point to line state
1403     lsp[0] = 0;                    // for initial row of quad, we set to 0
1404     run = mel_get_run(&mel);    // decode runs of events from MEL bitstrm
1405     // data represented as runs of 0 events
1406     // See mel_decode description
1407     qinf[0] = qinf[1] = 0;      // quad info decoded from VLC bitstream
1408     c_q = 0;                    // context for quad q
1409     sp = decoded_data;          // decoded codeblock samples
1410     // vlc_val;                 // fetched data from VLC bitstream
1411
1412     for (x = 0; x < width; x += 4) { // one iteration per quad pair
1413         OPJ_UINT32 U_q[2]; // u values for the quad pair
1414         OPJ_UINT32 uvlc_mode;
1415         OPJ_UINT32 consumed_bits;
1416         OPJ_UINT32 m_n, v_n;
1417         OPJ_UINT32 ms_val;
1418         OPJ_UINT32 locs;
1419
1420         // decode VLC
1421         /////////////
1422
1423         //first quad
1424         // Get the head of the VLC bitstream. One fetch is enough for two
1425         // quads, since the largest VLC code is 7 bits, and maximum number of
1426         // bits used for u is 8.  Therefore for two quads we need 30 bits
1427         // (if we include unstuffing, then 32 bits are enough, since we have
1428         // a maximum of one stuffing per two bytes)
1429         vlc_val = rev_fetch(&vlc);
1430
1431         //decode VLC using the context c_q and the head of the VLC bitstream
1432         qinf[0] = vlc_tbl0[(c_q << 7) | (vlc_val & 0x7F) ];
1433
1434         if (c_q == 0) { // if zero context, we need to use one MEL event
1435             run -= 2; //the number of 0 events is multiplied by 2, so subtract 2
1436
1437             // Is the run terminated in 1? if so, use decoded VLC code,
1438             // otherwise, discard decoded data, since we will decoded again
1439             // using a different context
1440             qinf[0] = (run == -1) ? qinf[0] : 0;
1441
1442             // is run -1 or -2? this means a run has been consumed
1443             if (run < 0) {
1444                 run = mel_get_run(&mel);    // get another run
1445             }
1446         }
1447
1448         // prepare context for the next quad; eqn. 1 in ITU T.814
1449         c_q = ((qinf[0] & 0x10) >> 4) | ((qinf[0] & 0xE0) >> 5);
1450
1451         //remove data from vlc stream (0 bits are removed if qinf is not used)
1452         vlc_val = rev_advance(&vlc, qinf[0] & 0x7);
1453
1454         //update sigma
1455         // The update depends on the value of x; consider one OPJ_UINT32
1456         // if x is 0, 8, 16 and so on, then this line update c locations
1457         //      nibble (4 bits) number   0 1 2 3 4 5 6 7
1458         //                         LSB   c c 0 0 0 0 0 0
1459         //                               c c 0 0 0 0 0 0
1460         //                               0 0 0 0 0 0 0 0
1461         //                               0 0 0 0 0 0 0 0
1462         // if x is 4, 12, 20, then this line update locations c
1463         //      nibble (4 bits) number   0 1 2 3 4 5 6 7
1464         //                         LSB   0 0 0 0 c c 0 0
1465         //                               0 0 0 0 c c 0 0
1466         //                               0 0 0 0 0 0 0 0
1467         //                               0 0 0 0 0 0 0 0
1468         *sip |= (((qinf[0] & 0x30) >> 4) | ((qinf[0] & 0xC0) >> 2)) << sip_shift;
1469
1470         //second quad
1471         qinf[1] = 0;
1472         if (x + 2 < width) { // do not run if codeblock is narrower
1473             //decode VLC using the context c_q and the head of the VLC bitstream
1474             qinf[1] = vlc_tbl0[(c_q << 7) | (vlc_val & 0x7F)];
1475
1476             // if context is zero, use one MEL event
1477             if (c_q == 0) { //zero context
1478                 run -= 2; //subtract 2, since events number if multiplied by 2
1479
1480                 // if event is 0, discard decoded qinf
1481                 qinf[1] = (run == -1) ? qinf[1] : 0;
1482
1483                 if (run < 0) { // have we consumed all events in a run
1484                     run = mel_get_run(&mel);    // if yes, then get another run
1485                 }
1486             }
1487
1488             //prepare context for the next quad, eqn. 1 in ITU T.814
1489             c_q = ((qinf[1] & 0x10) >> 4) | ((qinf[1] & 0xE0) >> 5);
1490
1491             //remove data from vlc stream, if qinf is not used, cwdlen is 0
1492             vlc_val = rev_advance(&vlc, qinf[1] & 0x7);
1493         }
1494
1495         //update sigma
1496         // The update depends on the value of x; consider one OPJ_UINT32
1497         // if x is 0, 8, 16 and so on, then this line update c locations
1498         //      nibble (4 bits) number   0 1 2 3 4 5 6 7
1499         //                         LSB   0 0 c c 0 0 0 0
1500         //                               0 0 c c 0 0 0 0
1501         //                               0 0 0 0 0 0 0 0
1502         //                               0 0 0 0 0 0 0 0
1503         // if x is 4, 12, 20, then this line update locations c
1504         //      nibble (4 bits) number   0 1 2 3 4 5 6 7
1505         //                         LSB   0 0 0 0 0 0 c c
1506         //                               0 0 0 0 0 0 c c
1507         //                               0 0 0 0 0 0 0 0
1508         //                               0 0 0 0 0 0 0 0
1509         *sip |= (((qinf[1] & 0x30) | ((qinf[1] & 0xC0) << 2))) << (4 + sip_shift);
1510
1511         sip += x & 0x7 ? 1 : 0; // move sigma pointer to next entry
1512         sip_shift ^= 0x10;      // increment/decrement sip_shift by 16
1513
1514         // retrieve u
1515         /////////////
1516
1517         // uvlc_mode is made up of u_offset bits from the quad pair
1518         uvlc_mode = ((qinf[0] & 0x8) >> 3) | ((qinf[1] & 0x8) >> 2);
1519         if (uvlc_mode == 3) { // if both u_offset are set, get an event from
1520             // the MEL run of events
1521             run -= 2; //subtract 2, since events number if multiplied by 2
1522             uvlc_mode += (run == -1) ? 1 : 0; //increment uvlc_mode if event is 1
1523             if (run < 0) { // if run is consumed (run is -1 or -2), get another run
1524                 run = mel_get_run(&mel);
1525             }
1526         }
1527         //decode uvlc_mode to get u for both quads
1528         consumed_bits = decode_init_uvlc(vlc_val, uvlc_mode, U_q);
1529         if (U_q[0] > zero_bplanes_p1 || U_q[1] > zero_bplanes_p1) {
1530             if (p_manager_mutex) {
1531                 opj_mutex_lock(p_manager_mutex);
1532             }
1533             opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. Decoding "
1534                           "this codeblock is stopped. U_q is larger than zero "
1535                           "bitplanes + 1 \n");
1536             if (p_manager_mutex) {
1537                 opj_mutex_unlock(p_manager_mutex);
1538             }
1539             return OPJ_FALSE;
1540         }
1541
1542         //consume u bits in the VLC code
1543         vlc_val = rev_advance(&vlc, consumed_bits);
1544
1545         //decode magsgn and update line_state
1546         /////////////////////////////////////
1547
1548         //We obtain a mask for the samples locations that needs evaluation
1549         locs = 0xFF;
1550         if (x + 4 > width) {
1551             locs >>= (x + 4 - width) << 1;    // limits width
1552         }
1553         locs = height > 1 ? locs : (locs & 0x55);         // limits height
1554
1555         if ((((qinf[0] & 0xF0) >> 4) | (qinf[1] & 0xF0)) & ~locs) {
1556             if (p_manager_mutex) {
1557                 opj_mutex_lock(p_manager_mutex);
1558             }
1559             opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1560                           "VLC code produces significant samples outside "
1561                           "the codeblock area.\n");
1562             if (p_manager_mutex) {
1563                 opj_mutex_unlock(p_manager_mutex);
1564             }
1565             return OPJ_FALSE;
1566         }
1567
1568         //first quad, starting at first sample in quad and moving on
1569         if (qinf[0] & 0x10) { //is it significant? (sigma_n)
1570             OPJ_UINT32 val;
1571
1572             ms_val = frwd_fetch(&magsgn);         //get 32 bits of magsgn data
1573             m_n = U_q[0] - ((qinf[0] >> 12) & 1); //evaluate m_n (number of bits
1574             // to read from bitstream), using EMB e_k
1575             frwd_advance(&magsgn, m_n);         //consume m_n
1576             val = ms_val << 31;                 //get sign bit
1577             v_n = ms_val & ((1U << m_n) - 1);   //keep only m_n bits
1578             v_n |= ((qinf[0] & 0x100) >> 8) << m_n;  //add EMB e_1 as MSB
1579             v_n |= 1;                                //add center of bin
1580             //v_n now has 2 * (\mu - 1) + 0.5 with correct sign bit
1581             //add 2 to make it 2*\mu+0.5, shift it up to missing MSBs
1582             sp[0] = val | ((v_n + 2) << (p - 1));
1583         } else if (locs & 0x1) { // if this is inside the codeblock, set the
1584             sp[0] = 0;           // sample to zero
1585         }
1586
1587         if (qinf[0] & 0x20) { //sigma_n
1588             OPJ_UINT32 val, t;
1589
1590             ms_val = frwd_fetch(&magsgn);         //get 32 bits
1591             m_n = U_q[0] - ((qinf[0] >> 13) & 1); //m_n, uses EMB e_k
1592             frwd_advance(&magsgn, m_n);           //consume m_n
1593             val = ms_val << 31;                   //get sign bit
1594             v_n = ms_val & ((1U << m_n) - 1);     //keep only m_n bits
1595             v_n |= ((qinf[0] & 0x200) >> 9) << m_n; //add EMB e_1
1596             v_n |= 1;                               //bin center
1597             //v_n now has 2 * (\mu - 1) + 0.5 with correct sign bit
1598             //add 2 to make it 2*\mu+0.5, shift it up to missing MSBs
1599             sp[stride] = val | ((v_n + 2) << (p - 1));
1600
1601             //update line_state: bit 7 (\sigma^N), and E^N
1602             t = lsp[0] & 0x7F;       // keep E^NW
1603             v_n = 32 - count_leading_zeros(v_n);
1604             lsp[0] = (OPJ_UINT8)(0x80 | (t > v_n ? t : v_n)); //max(E^NW, E^N) | s
1605         } else if (locs & 0x2) { // if this is inside the codeblock, set the
1606             sp[stride] = 0;      // sample to zero
1607         }
1608
1609         ++lsp; // move to next quad information
1610         ++sp;  // move to next column of samples
1611
1612         //this is similar to the above two samples
1613         if (qinf[0] & 0x40) {
1614             OPJ_UINT32 val;
1615
1616             ms_val = frwd_fetch(&magsgn);
1617             m_n = U_q[0] - ((qinf[0] >> 14) & 1);
1618             frwd_advance(&magsgn, m_n);
1619             val = ms_val << 31;
1620             v_n = ms_val & ((1U << m_n) - 1);
1621             v_n |= (((qinf[0] & 0x400) >> 10) << m_n);
1622             v_n |= 1;
1623             sp[0] = val | ((v_n + 2) << (p - 1));
1624         } else if (locs & 0x4) {
1625             sp[0] = 0;
1626         }
1627
1628         lsp[0] = 0;
1629         if (qinf[0] & 0x80) {
1630             OPJ_UINT32 val;
1631             ms_val = frwd_fetch(&magsgn);
1632             m_n = U_q[0] - ((qinf[0] >> 15) & 1); //m_n
1633             frwd_advance(&magsgn, m_n);
1634             val = ms_val << 31;
1635             v_n = ms_val & ((1U << m_n) - 1);
1636             v_n |= ((qinf[0] & 0x800) >> 11) << m_n;
1637             v_n |= 1; //center of bin
1638             sp[stride] = val | ((v_n + 2) << (p - 1));
1639
1640             //line_state: bit 7 (\sigma^NW), and E^NW for next quad
1641             lsp[0] = (OPJ_UINT8)(0x80 | (32 - count_leading_zeros(v_n)));
1642         } else if (locs & 0x8) { //if outside set to 0
1643             sp[stride] = 0;
1644         }
1645
1646         ++sp; //move to next column
1647
1648         //second quad
1649         if (qinf[1] & 0x10) {
1650             OPJ_UINT32 val;
1651
1652             ms_val = frwd_fetch(&magsgn);
1653             m_n = U_q[1] - ((qinf[1] >> 12) & 1); //m_n
1654             frwd_advance(&magsgn, m_n);
1655             val = ms_val << 31;
1656             v_n = ms_val & ((1U << m_n) - 1);
1657             v_n |= (((qinf[1] & 0x100) >> 8) << m_n);
1658             v_n |= 1;
1659             sp[0] = val | ((v_n + 2) << (p - 1));
1660         } else if (locs & 0x10) {
1661             sp[0] = 0;
1662         }
1663
1664         if (qinf[1] & 0x20) {
1665             OPJ_UINT32 val, t;
1666
1667             ms_val = frwd_fetch(&magsgn);
1668             m_n = U_q[1] - ((qinf[1] >> 13) & 1); //m_n
1669             frwd_advance(&magsgn, m_n);
1670             val = ms_val << 31;
1671             v_n = ms_val & ((1U << m_n) - 1);
1672             v_n |= (((qinf[1] & 0x200) >> 9) << m_n);
1673             v_n |= 1;
1674             sp[stride] = val | ((v_n + 2) << (p - 1));
1675
1676             //update line_state: bit 7 (\sigma^N), and E^N
1677             t = lsp[0] & 0x7F;            //E^NW
1678             v_n = 32 - count_leading_zeros(v_n);     //E^N
1679             lsp[0] = (OPJ_UINT8)(0x80 | (t > v_n ? t : v_n)); //max(E^NW, E^N) | s
1680         } else if (locs & 0x20) {
1681             sp[stride] = 0;    //no need to update line_state
1682         }
1683
1684         ++lsp; //move line state to next quad
1685         ++sp;  //move to next sample
1686
1687         if (qinf[1] & 0x40) {
1688             OPJ_UINT32 val;
1689
1690             ms_val = frwd_fetch(&magsgn);
1691             m_n = U_q[1] - ((qinf[1] >> 14) & 1); //m_n
1692             frwd_advance(&magsgn, m_n);
1693             val = ms_val << 31;
1694             v_n = ms_val & ((1U << m_n) - 1);
1695             v_n |= (((qinf[1] & 0x400) >> 10) << m_n);
1696             v_n |= 1;
1697             sp[0] = val | ((v_n + 2) << (p - 1));
1698         } else if (locs & 0x40) {
1699             sp[0] = 0;
1700         }
1701
1702         lsp[0] = 0;
1703         if (qinf[1] & 0x80) {
1704             OPJ_UINT32 val;
1705
1706             ms_val = frwd_fetch(&magsgn);
1707             m_n = U_q[1] - ((qinf[1] >> 15) & 1); //m_n
1708             frwd_advance(&magsgn, m_n);
1709             val = ms_val << 31;
1710             v_n = ms_val & ((1U << m_n) - 1);
1711             v_n |= (((qinf[1] & 0x800) >> 11) << m_n);
1712             v_n |= 1; //center of bin
1713             sp[stride] = val | ((v_n + 2) << (p - 1));
1714
1715             //line_state: bit 7 (\sigma^NW), and E^NW for next quad
1716             lsp[0] = (OPJ_UINT8)(0x80 | (32 - count_leading_zeros(v_n)));
1717         } else if (locs & 0x80) {
1718             sp[stride] = 0;
1719         }
1720
1721         ++sp;
1722     }
1723
1724     //non-initial lines
1725     //////////////////////////
1726     for (y = 2; y < height; /*done at the end of loop*/) {
1727         OPJ_UINT32 *sip;
1728         OPJ_UINT8 ls0;
1729         OPJ_INT32 x;
1730
1731         sip_shift ^= 0x2;  // shift sigma to the upper half od the nibble
1732         sip_shift &= 0xFFFFFFEFU; //move back to 0 (it might have been at 0x10)
1733         sip = y & 0x4 ? sigma2 : sigma1; //choose sigma array
1734
1735         lsp = line_state;
1736         ls0 = lsp[0];                   // read the line state value
1737         lsp[0] = 0;                     // and set it to zero
1738         sp = decoded_data + y * stride; // generated samples
1739         c_q = 0;                        // context
1740         for (x = 0; x < width; x += 4) {
1741             OPJ_UINT32 U_q[2];
1742             OPJ_UINT32 uvlc_mode, consumed_bits;
1743             OPJ_UINT32 m_n, v_n;
1744             OPJ_UINT32 ms_val;
1745             OPJ_UINT32 locs;
1746
1747             // decode vlc
1748             /////////////
1749
1750             //first quad
1751             // get context, eqn. 2 ITU T.814
1752             // c_q has \sigma^W | \sigma^SW
1753             c_q |= (ls0 >> 7);          //\sigma^NW | \sigma^N
1754             c_q |= (lsp[1] >> 5) & 0x4; //\sigma^NE | \sigma^NF
1755
1756             //the following is very similar to previous code, so please refer to
1757             // that
1758             vlc_val = rev_fetch(&vlc);
1759             qinf[0] = vlc_tbl1[(c_q << 7) | (vlc_val & 0x7F)];
1760             if (c_q == 0) { //zero context
1761                 run -= 2;
1762                 qinf[0] = (run == -1) ? qinf[0] : 0;
1763                 if (run < 0) {
1764                     run = mel_get_run(&mel);
1765                 }
1766             }
1767             //prepare context for the next quad, \sigma^W | \sigma^SW
1768             c_q = ((qinf[0] & 0x40) >> 5) | ((qinf[0] & 0x80) >> 6);
1769
1770             //remove data from vlc stream
1771             vlc_val = rev_advance(&vlc, qinf[0] & 0x7);
1772
1773             //update sigma
1774             // The update depends on the value of x and y; consider one OPJ_UINT32
1775             // if x is 0, 8, 16 and so on, and y is 2, 6, etc., then this
1776             // line update c locations
1777             //      nibble (4 bits) number   0 1 2 3 4 5 6 7
1778             //                         LSB   0 0 0 0 0 0 0 0
1779             //                               0 0 0 0 0 0 0 0
1780             //                               c c 0 0 0 0 0 0
1781             //                               c c 0 0 0 0 0 0
1782             *sip |= (((qinf[0] & 0x30) >> 4) | ((qinf[0] & 0xC0) >> 2)) << sip_shift;
1783
1784             //second quad
1785             qinf[1] = 0;
1786             if (x + 2 < width) {
1787                 c_q |= (lsp[1] >> 7);
1788                 c_q |= (lsp[2] >> 5) & 0x4;
1789                 qinf[1] = vlc_tbl1[(c_q << 7) | (vlc_val & 0x7F)];
1790                 if (c_q == 0) { //zero context
1791                     run -= 2;
1792                     qinf[1] = (run == -1) ? qinf[1] : 0;
1793                     if (run < 0) {
1794                         run = mel_get_run(&mel);
1795                     }
1796                 }
1797                 //prepare context for the next quad
1798                 c_q = ((qinf[1] & 0x40) >> 5) | ((qinf[1] & 0x80) >> 6);
1799                 //remove data from vlc stream
1800                 vlc_val = rev_advance(&vlc, qinf[1] & 0x7);
1801             }
1802
1803             //update sigma
1804             *sip |= (((qinf[1] & 0x30) | ((qinf[1] & 0xC0) << 2))) << (4 + sip_shift);
1805
1806             sip += x & 0x7 ? 1 : 0;
1807             sip_shift ^= 0x10;
1808
1809             //retrieve u
1810             ////////////
1811             uvlc_mode = ((qinf[0] & 0x8) >> 3) | ((qinf[1] & 0x8) >> 2);
1812             consumed_bits = decode_noninit_uvlc(vlc_val, uvlc_mode, U_q);
1813             vlc_val = rev_advance(&vlc, consumed_bits);
1814
1815             //calculate E^max and add it to U_q, eqns 5 and 6 in ITU T.814
1816             if ((qinf[0] & 0xF0) & ((qinf[0] & 0xF0) - 1)) { // is \gamma_q 1?
1817                 OPJ_UINT32 E = (ls0 & 0x7Fu);
1818                 E = E > (lsp[1] & 0x7Fu) ? E : (lsp[1] & 0x7Fu); //max(E, E^NE, E^NF)
1819                 //since U_q already has u_q + 1, we subtract 2 instead of 1
1820                 U_q[0] += E > 2 ? E - 2 : 0;
1821             }
1822
1823             if ((qinf[1] & 0xF0) & ((qinf[1] & 0xF0) - 1)) { //is \gamma_q 1?
1824                 OPJ_UINT32 E = (lsp[1] & 0x7Fu);
1825                 E = E > (lsp[2] & 0x7Fu) ? E : (lsp[2] & 0x7Fu); //max(E, E^NE, E^NF)
1826                 //since U_q already has u_q + 1, we subtract 2 instead of 1
1827                 U_q[1] += E > 2 ? E - 2 : 0;
1828             }
1829
1830             if (U_q[0] > zero_bplanes_p1 || U_q[1] > zero_bplanes_p1) {
1831                 if (p_manager_mutex) {
1832                     opj_mutex_lock(p_manager_mutex);
1833                 }
1834                 opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1835                               "Decoding this codeblock is stopped. U_q is"
1836                               "larger than bitplanes + 1 \n");
1837                 if (p_manager_mutex) {
1838                     opj_mutex_unlock(p_manager_mutex);
1839                 }
1840                 return OPJ_FALSE;
1841             }
1842
1843             ls0 = lsp[2]; //for next double quad
1844             lsp[1] = lsp[2] = 0;
1845
1846             //decode magsgn and update line_state
1847             /////////////////////////////////////
1848
1849             //locations where samples need update
1850             locs = 0xFF;
1851             if (x + 4 > width) {
1852                 locs >>= (x + 4 - width) << 1;
1853             }
1854             locs = y + 2 <= height ? locs : (locs & 0x55);
1855
1856             if ((((qinf[0] & 0xF0) >> 4) | (qinf[1] & 0xF0)) & ~locs) {
1857                 if (p_manager_mutex) {
1858                     opj_mutex_lock(p_manager_mutex);
1859                 }
1860                 opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1861                               "VLC code produces significant samples outside "
1862                               "the codeblock area.\n");
1863                 if (p_manager_mutex) {
1864                     opj_mutex_unlock(p_manager_mutex);
1865                 }
1866                 return OPJ_FALSE;
1867             }
1868
1869
1870
1871             if (qinf[0] & 0x10) { //sigma_n
1872                 OPJ_UINT32 val;
1873
1874                 ms_val = frwd_fetch(&magsgn);
1875                 m_n = U_q[0] - ((qinf[0] >> 12) & 1); //m_n
1876                 frwd_advance(&magsgn, m_n);
1877                 val = ms_val << 31;
1878                 v_n = ms_val & ((1U << m_n) - 1);
1879                 v_n |= ((qinf[0] & 0x100) >> 8) << m_n;
1880                 v_n |= 1; //center of bin
1881                 sp[0] = val | ((v_n + 2) << (p - 1));
1882             } else if (locs & 0x1) {
1883                 sp[0] = 0;
1884             }
1885
1886             if (qinf[0] & 0x20) { //sigma_n
1887                 OPJ_UINT32 val, t;
1888
1889                 ms_val = frwd_fetch(&magsgn);
1890                 m_n = U_q[0] - ((qinf[0] >> 13) & 1); //m_n
1891                 frwd_advance(&magsgn, m_n);
1892                 val = ms_val << 31;
1893                 v_n = ms_val & ((1U << m_n) - 1);
1894                 v_n |= ((qinf[0] & 0x200) >> 9) << m_n;
1895                 v_n |= 1; //center of bin
1896                 sp[stride] = val | ((v_n + 2) << (p - 1));
1897
1898                 //update line_state: bit 7 (\sigma^N), and E^N
1899                 t = lsp[0] & 0x7F;          //E^NW
1900                 v_n = 32 - count_leading_zeros(v_n);
1901                 lsp[0] = (OPJ_UINT8)(0x80 | (t > v_n ? t : v_n));
1902             } else if (locs & 0x2) {
1903                 sp[stride] = 0;    //no need to update line_state
1904             }
1905
1906             ++lsp;
1907             ++sp;
1908
1909             if (qinf[0] & 0x40) { //sigma_n
1910                 OPJ_UINT32 val;
1911
1912                 ms_val = frwd_fetch(&magsgn);
1913                 m_n = U_q[0] - ((qinf[0] >> 14) & 1); //m_n
1914                 frwd_advance(&magsgn, m_n);
1915                 val = ms_val << 31;
1916                 v_n = ms_val & ((1U << m_n) - 1);
1917                 v_n |= (((qinf[0] & 0x400) >> 10) << m_n);
1918                 v_n |= 1;                            //center of bin
1919                 sp[0] = val | ((v_n + 2) << (p - 1));
1920             } else if (locs & 0x4) {
1921                 sp[0] = 0;
1922             }
1923
1924             if (qinf[0] & 0x80) { //sigma_n
1925                 OPJ_UINT32 val;
1926
1927                 ms_val = frwd_fetch(&magsgn);
1928                 m_n = U_q[0] - ((qinf[0] >> 15) & 1); //m_n
1929                 frwd_advance(&magsgn, m_n);
1930                 val = ms_val << 31;
1931                 v_n = ms_val & ((1U << m_n) - 1);
1932                 v_n |= ((qinf[0] & 0x800) >> 11) << m_n;
1933                 v_n |= 1; //center of bin
1934                 sp[stride] = val | ((v_n + 2) << (p - 1));
1935
1936                 //update line_state: bit 7 (\sigma^NW), and E^NW for next quad
1937                 lsp[0] = (OPJ_UINT8)(0x80 | (32 - count_leading_zeros(v_n)));
1938             } else if (locs & 0x8) {
1939                 sp[stride] = 0;
1940             }
1941
1942             ++sp;
1943
1944             if (qinf[1] & 0x10) { //sigma_n
1945                 OPJ_UINT32 val;
1946
1947                 ms_val = frwd_fetch(&magsgn);
1948                 m_n = U_q[1] - ((qinf[1] >> 12) & 1); //m_n
1949                 frwd_advance(&magsgn, m_n);
1950                 val = ms_val << 31;
1951                 v_n = ms_val & ((1U << m_n) - 1);
1952                 v_n |= (((qinf[1] & 0x100) >> 8) << m_n);
1953                 v_n |= 1;                            //center of bin
1954                 sp[0] = val | ((v_n + 2) << (p - 1));
1955             } else if (locs & 0x10) {
1956                 sp[0] = 0;
1957             }
1958
1959             if (qinf[1] & 0x20) { //sigma_n
1960                 OPJ_UINT32 val, t;
1961
1962                 ms_val = frwd_fetch(&magsgn);
1963                 m_n = U_q[1] - ((qinf[1] >> 13) & 1); //m_n
1964                 frwd_advance(&magsgn, m_n);
1965                 val = ms_val << 31;
1966                 v_n = ms_val & ((1U << m_n) - 1);
1967                 v_n |= (((qinf[1] & 0x200) >> 9) << m_n);
1968                 v_n |= 1; //center of bin
1969                 sp[stride] = val | ((v_n + 2) << (p - 1));
1970
1971                 //update line_state: bit 7 (\sigma^N), and E^N
1972                 t = lsp[0] & 0x7F;          //E^NW
1973                 v_n = 32 - count_leading_zeros(v_n);
1974                 lsp[0] = (OPJ_UINT8)(0x80 | (t > v_n ? t : v_n));
1975             } else if (locs & 0x20) {
1976                 sp[stride] = 0;    //no need to update line_state
1977             }
1978
1979             ++lsp;
1980             ++sp;
1981
1982             if (qinf[1] & 0x40) { //sigma_n
1983                 OPJ_UINT32 val;
1984
1985                 ms_val = frwd_fetch(&magsgn);
1986                 m_n = U_q[1] - ((qinf[1] >> 14) & 1); //m_n
1987                 frwd_advance(&magsgn, m_n);
1988                 val = ms_val << 31;
1989                 v_n = ms_val & ((1U << m_n) - 1);
1990                 v_n |= (((qinf[1] & 0x400) >> 10) << m_n);
1991                 v_n |= 1;                            //center of bin
1992                 sp[0] = val | ((v_n + 2) << (p - 1));
1993             } else if (locs & 0x40) {
1994                 sp[0] = 0;
1995             }
1996
1997             if (qinf[1] & 0x80) { //sigma_n
1998                 OPJ_UINT32 val;
1999
2000                 ms_val = frwd_fetch(&magsgn);
2001                 m_n = U_q[1] - ((qinf[1] >> 15) & 1); //m_n
2002                 frwd_advance(&magsgn, m_n);
2003                 val = ms_val << 31;
2004                 v_n = ms_val & ((1U << m_n) - 1);
2005                 v_n |= (((qinf[1] & 0x800) >> 11) << m_n);
2006                 v_n |= 1; //center of bin
2007                 sp[stride] = val | ((v_n + 2) << (p - 1));
2008
2009                 //update line_state: bit 7 (\sigma^NW), and E^NW for next quad
2010                 lsp[0] = (OPJ_UINT8)(0x80 | (32 - count_leading_zeros(v_n)));
2011             } else if (locs & 0x80) {
2012                 sp[stride] = 0;
2013             }
2014
2015             ++sp;
2016         }
2017
2018         y += 2;
2019         if (num_passes > 1 && (y & 3) == 0) { //executed at multiples of 4
2020             // This is for SPP and potentially MRP
2021
2022             if (num_passes > 2) { //do MRP
2023                 // select the current stripe
2024                 OPJ_UINT32 *cur_sig = y & 0x4 ? sigma1 : sigma2;
2025                 // the address of the data that needs updating
2026                 OPJ_UINT32 *dpp = decoded_data + (y - 4) * stride;
2027                 OPJ_UINT32 half = 1u << (p - 2); // half the center of the bin
2028                 OPJ_INT32 i;
2029                 for (i = 0; i < width; i += 8) {
2030                     //Process one entry from sigma array at a time
2031                     // Each nibble (4 bits) in the sigma array represents 4 rows,
2032                     // and the 32 bits contain 8 columns
2033                     OPJ_UINT32 cwd = rev_fetch_mrp(&magref); // get 32 bit data
2034                     OPJ_UINT32 sig = *cur_sig++; // 32 bit that will be processed now
2035                     OPJ_UINT32 col_mask = 0xFu;  // a mask for a column in sig
2036                     OPJ_UINT32 *dp = dpp + i;    // next column in decode samples
2037                     if (sig) { // if any of the 32 bits are set
2038                         int j;
2039                         for (j = 0; j < 8; ++j, dp++) { //one column at a time
2040                             if (sig & col_mask) { // lowest nibble
2041                                 OPJ_UINT32 sample_mask = 0x11111111u & col_mask; //LSB
2042
2043                                 if (sig & sample_mask) { //if LSB is set
2044                                     OPJ_UINT32 sym;
2045
2046                                     assert(dp[0] != 0); // decoded value cannot be zero
2047                                     sym = cwd & 1; // get it value
2048                                     // remove center of bin if sym is 0
2049                                     dp[0] ^= (1 - sym) << (p - 1);
2050                                     dp[0] |= half;      // put half the center of bin
2051                                     cwd >>= 1;          //consume word
2052                                 }
2053                                 sample_mask += sample_mask; //next row
2054
2055                                 if (sig & sample_mask) {
2056                                     OPJ_UINT32 sym;
2057
2058                                     assert(dp[stride] != 0);
2059                                     sym = cwd & 1;
2060                                     dp[stride] ^= (1 - sym) << (p - 1);
2061                                     dp[stride] |= half;
2062                                     cwd >>= 1;
2063                                 }
2064                                 sample_mask += sample_mask;
2065
2066                                 if (sig & sample_mask) {
2067                                     OPJ_UINT32 sym;
2068
2069                                     assert(dp[2 * stride] != 0);
2070                                     sym = cwd & 1;
2071                                     dp[2 * stride] ^= (1 - sym) << (p - 1);
2072                                     dp[2 * stride] |= half;
2073                                     cwd >>= 1;
2074                                 }
2075                                 sample_mask += sample_mask;
2076
2077                                 if (sig & sample_mask) {
2078                                     OPJ_UINT32 sym;
2079
2080                                     assert(dp[3 * stride] != 0);
2081                                     sym = cwd & 1;
2082                                     dp[3 * stride] ^= (1 - sym) << (p - 1);
2083                                     dp[3 * stride] |= half;
2084                                     cwd >>= 1;
2085                                 }
2086                                 sample_mask += sample_mask;
2087                             }
2088                             col_mask <<= 4; //next column
2089                         }
2090                     }
2091                     // consume data according to the number of bits set
2092                     rev_advance_mrp(&magref, population_count(sig));
2093                 }
2094             }
2095
2096             if (y >= 4) { // update mbr array at the end of each stripe
2097                 //generate mbr corresponding to a stripe
2098                 OPJ_UINT32 *sig = y & 0x4 ? sigma1 : sigma2;
2099                 OPJ_UINT32 *mbr = y & 0x4 ? mbr1 : mbr2;
2100
2101                 //data is processed in patches of 8 columns, each
2102                 // each 32 bits in sigma1 or mbr1 represent 4 rows
2103
2104                 //integrate horizontally
2105                 OPJ_UINT32 prev = 0; // previous columns
2106                 OPJ_INT32 i;
2107                 for (i = 0; i < width; i += 8, mbr++, sig++) {
2108                     OPJ_UINT32 t, z;
2109
2110                     mbr[0] = sig[0];         //start with significant samples
2111                     mbr[0] |= prev >> 28;    //for first column, left neighbors
2112                     mbr[0] |= sig[0] << 4;   //left neighbors
2113                     mbr[0] |= sig[0] >> 4;   //right neighbors
2114                     mbr[0] |= sig[1] << 28;  //for last column, right neighbors
2115                     prev = sig[0];           // for next group of columns
2116
2117                     //integrate vertically
2118                     t = mbr[0], z = mbr[0];
2119                     z |= (t & 0x77777777) << 1; //above neighbors
2120                     z |= (t & 0xEEEEEEEE) >> 1; //below neighbors
2121                     mbr[0] = z & ~sig[0]; //remove already significance samples
2122                 }
2123             }
2124
2125             if (y >= 8) { //wait until 8 rows has been processed
2126                 OPJ_UINT32 *cur_sig, *cur_mbr, *nxt_sig, *nxt_mbr;
2127                 OPJ_UINT32 prev;
2128                 OPJ_UINT32 val;
2129                 OPJ_INT32 i;
2130
2131                 // add membership from the next stripe, obtained above
2132                 cur_sig = y & 0x4 ? sigma2 : sigma1;
2133                 cur_mbr = y & 0x4 ? mbr2 : mbr1;
2134                 nxt_sig = y & 0x4 ? sigma1 : sigma2;  //future samples
2135                 prev = 0; // the columns before these group of 8 columns
2136                 for (i = 0; i < width; i += 8, cur_mbr++, cur_sig++, nxt_sig++) {
2137                     OPJ_UINT32 t = nxt_sig[0];
2138                     t |= prev >> 28;        //for first column, left neighbors
2139                     t |= nxt_sig[0] << 4;   //left neighbors
2140                     t |= nxt_sig[0] >> 4;   //right neighbors
2141                     t |= nxt_sig[1] << 28;  //for last column, right neighbors
2142                     prev = nxt_sig[0];      // for next group of columns
2143
2144                     if (!stripe_causal) {
2145                         cur_mbr[0] |= (t & 0x11111111u) << 3; //propagate up to cur_mbr
2146                     }
2147                     cur_mbr[0] &= ~cur_sig[0]; //remove already significance samples
2148                 }
2149
2150                 //find new locations and get signs
2151                 cur_sig = y & 0x4 ? sigma2 : sigma1;
2152                 cur_mbr = y & 0x4 ? mbr2 : mbr1;
2153                 nxt_sig = y & 0x4 ? sigma1 : sigma2; //future samples
2154                 nxt_mbr = y & 0x4 ? mbr1 : mbr2;     //future samples
2155                 val = 3u << (p - 2); // sample values for newly discovered
2156                 // significant samples including the bin center
2157                 for (i = 0; i < width;
2158                         i += 8, cur_sig++, cur_mbr++, nxt_sig++, nxt_mbr++) {
2159                     OPJ_UINT32 ux, tx;
2160                     OPJ_UINT32 mbr = *cur_mbr;
2161                     OPJ_UINT32 new_sig = 0;
2162                     if (mbr) { //are there any samples that might be significant
2163                         OPJ_INT32 n;
2164                         for (n = 0; n < 8; n += 4) {
2165                             OPJ_UINT32 col_mask;
2166                             OPJ_UINT32 inv_sig;
2167                             OPJ_INT32 end;
2168                             OPJ_INT32 j;
2169
2170                             OPJ_UINT32 cwd = frwd_fetch(&sigprop); //get 32 bits
2171                             OPJ_UINT32 cnt = 0;
2172
2173                             OPJ_UINT32 *dp = decoded_data + (y - 8) * stride;
2174                             dp += i + n; //address for decoded samples
2175
2176                             col_mask = 0xFu << (4 * n); //a mask to select a column
2177
2178                             inv_sig = ~cur_sig[0]; // insignificant samples
2179
2180                             //find the last sample we operate on
2181                             end = n + 4 + i < width ? n + 4 : width - i;
2182
2183                             for (j = n; j < end; ++j, ++dp, col_mask <<= 4) {
2184                                 OPJ_UINT32 sample_mask;
2185
2186                                 if ((col_mask & mbr) == 0) { //no samples need checking
2187                                     continue;
2188                                 }
2189
2190                                 //scan mbr to find a new significant sample
2191                                 sample_mask = 0x11111111u & col_mask; // LSB
2192                                 if (mbr & sample_mask) {
2193                                     assert(dp[0] == 0); // the sample must have been 0
2194                                     if (cwd & 1) { //if this sample has become significant
2195                                         // must propagate it to nearby samples
2196                                         OPJ_UINT32 t;
2197                                         new_sig |= sample_mask;  // new significant samples
2198                                         t = 0x32u << (j * 4);// propagation to neighbors
2199                                         mbr |= t & inv_sig; //remove already significant samples
2200                                     }
2201                                     cwd >>= 1;
2202                                     ++cnt; //consume bit and increment number of
2203                                     //consumed bits
2204                                 }
2205
2206                                 sample_mask += sample_mask;  // next row
2207                                 if (mbr & sample_mask) {
2208                                     assert(dp[stride] == 0);
2209                                     if (cwd & 1) {
2210                                         OPJ_UINT32 t;
2211                                         new_sig |= sample_mask;
2212                                         t = 0x74u << (j * 4);
2213                                         mbr |= t & inv_sig;
2214                                     }
2215                                     cwd >>= 1;
2216                                     ++cnt;
2217                                 }
2218
2219                                 sample_mask += sample_mask;
2220                                 if (mbr & sample_mask) {
2221                                     assert(dp[2 * stride] == 0);
2222                                     if (cwd & 1) {
2223                                         OPJ_UINT32 t;
2224                                         new_sig |= sample_mask;
2225                                         t = 0xE8u << (j * 4);
2226                                         mbr |= t & inv_sig;
2227                                     }
2228                                     cwd >>= 1;
2229                                     ++cnt;
2230                                 }
2231
2232                                 sample_mask += sample_mask;
2233                                 if (mbr & sample_mask) {
2234                                     assert(dp[3 * stride] == 0);
2235                                     if (cwd & 1) {
2236                                         OPJ_UINT32 t;
2237                                         new_sig |= sample_mask;
2238                                         t = 0xC0u << (j * 4);
2239                                         mbr |= t & inv_sig;
2240                                     }
2241                                     cwd >>= 1;
2242                                     ++cnt;
2243                                 }
2244                             }
2245
2246                             //obtain signs here
2247                             if (new_sig & (0xFFFFu << (4 * n))) { //if any
2248                                 OPJ_UINT32 col_mask;
2249                                 OPJ_INT32 j;
2250                                 OPJ_UINT32 *dp = decoded_data + (y - 8) * stride;
2251                                 dp += i + n; // decoded samples address
2252                                 col_mask = 0xFu << (4 * n); //mask to select a column
2253
2254                                 for (j = n; j < end; ++j, ++dp, col_mask <<= 4) {
2255                                     OPJ_UINT32 sample_mask;
2256
2257                                     if ((col_mask & new_sig) == 0) { //if non is significant
2258                                         continue;
2259                                     }
2260
2261                                     //scan 4 signs
2262                                     sample_mask = 0x11111111u & col_mask;
2263                                     if (new_sig & sample_mask) {
2264                                         assert(dp[0] == 0);
2265                                         dp[0] |= ((cwd & 1) << 31) | val; //put value and sign
2266                                         cwd >>= 1;
2267                                         ++cnt; //consume bit and increment number
2268                                         //of consumed bits
2269                                     }
2270
2271                                     sample_mask += sample_mask;
2272                                     if (new_sig & sample_mask) {
2273                                         assert(dp[stride] == 0);
2274                                         dp[stride] |= ((cwd & 1) << 31) | val;
2275                                         cwd >>= 1;
2276                                         ++cnt;
2277                                     }
2278
2279                                     sample_mask += sample_mask;
2280                                     if (new_sig & sample_mask) {
2281                                         assert(dp[2 * stride] == 0);
2282                                         dp[2 * stride] |= ((cwd & 1) << 31) | val;
2283                                         cwd >>= 1;
2284                                         ++cnt;
2285                                     }
2286
2287                                     sample_mask += sample_mask;
2288                                     if (new_sig & sample_mask) {
2289                                         assert(dp[3 * stride] == 0);
2290                                         dp[3 * stride] |= ((cwd & 1) << 31) | val;
2291                                         cwd >>= 1;
2292                                         ++cnt;
2293                                     }
2294                                 }
2295
2296                             }
2297                             frwd_advance(&sigprop, cnt); //consume the bits from bitstrm
2298                             cnt = 0;
2299
2300                             //update the next 8 columns
2301                             if (n == 4) {
2302                                 //horizontally
2303                                 OPJ_UINT32 t = new_sig >> 28;
2304                                 t |= ((t & 0xE) >> 1) | ((t & 7) << 1);
2305                                 cur_mbr[1] |= t & ~cur_sig[1];
2306                             }
2307                         }
2308                     }
2309                     //update the next stripe (vertically propagation)
2310                     new_sig |= cur_sig[0];
2311                     ux = (new_sig & 0x88888888) >> 3;
2312                     tx = ux | (ux << 4) | (ux >> 4); //left and right neighbors
2313                     if (i > 0) {
2314                         nxt_mbr[-1] |= (ux << 28) & ~nxt_sig[-1];
2315                     }
2316                     nxt_mbr[0] |= tx & ~nxt_sig[0];
2317                     nxt_mbr[1] |= (ux >> 28) & ~nxt_sig[1];
2318                 }
2319
2320                 //clear current sigma
2321                 //mbr need not be cleared because it is overwritten
2322                 cur_sig = y & 0x4 ? sigma2 : sigma1;
2323                 memset(cur_sig, 0, ((((OPJ_UINT32)width + 7u) >> 3) + 1u) << 2);
2324             }
2325         }
2326     }
2327
2328     //terminating
2329     if (num_passes > 1) {
2330         OPJ_INT32 st, y;
2331
2332         if (num_passes > 2 && ((height & 3) == 1 || (height & 3) == 2)) {
2333             //do magref
2334             OPJ_UINT32 *cur_sig = height & 0x4 ? sigma2 : sigma1; //reversed
2335             OPJ_UINT32 *dpp = decoded_data + (height & 0xFFFFFC) * stride;
2336             OPJ_UINT32 half = 1u << (p - 2);
2337             OPJ_INT32 i;
2338             for (i = 0; i < width; i += 8) {
2339                 OPJ_UINT32 cwd = rev_fetch_mrp(&magref);
2340                 OPJ_UINT32 sig = *cur_sig++;
2341                 OPJ_UINT32 col_mask = 0xF;
2342                 OPJ_UINT32 *dp = dpp + i;
2343                 if (sig) {
2344                     int j;
2345                     for (j = 0; j < 8; ++j, dp++) {
2346                         if (sig & col_mask) {
2347                             OPJ_UINT32 sample_mask = 0x11111111 & col_mask;
2348
2349                             if (sig & sample_mask) {
2350                                 OPJ_UINT32 sym;
2351                                 assert(dp[0] != 0);
2352                                 sym = cwd & 1;
2353                                 dp[0] ^= (1 - sym) << (p - 1);
2354                                 dp[0] |= half;
2355                                 cwd >>= 1;
2356                             }
2357                             sample_mask += sample_mask;
2358
2359                             if (sig & sample_mask) {
2360                                 OPJ_UINT32 sym;
2361                                 assert(dp[stride] != 0);
2362                                 sym = cwd & 1;
2363                                 dp[stride] ^= (1 - sym) << (p - 1);
2364                                 dp[stride] |= half;
2365                                 cwd >>= 1;
2366                             }
2367                             sample_mask += sample_mask;
2368
2369                             if (sig & sample_mask) {
2370                                 OPJ_UINT32 sym;
2371                                 assert(dp[2 * stride] != 0);
2372                                 sym = cwd & 1;
2373                                 dp[2 * stride] ^= (1 - sym) << (p - 1);
2374                                 dp[2 * stride] |= half;
2375                                 cwd >>= 1;
2376                             }
2377                             sample_mask += sample_mask;
2378
2379                             if (sig & sample_mask) {
2380                                 OPJ_UINT32 sym;
2381                                 assert(dp[3 * stride] != 0);
2382                                 sym = cwd & 1;
2383                                 dp[3 * stride] ^= (1 - sym) << (p - 1);
2384                                 dp[3 * stride] |= half;
2385                                 cwd >>= 1;
2386                             }
2387                             sample_mask += sample_mask;
2388                         }
2389                         col_mask <<= 4;
2390                     }
2391                 }
2392                 rev_advance_mrp(&magref, population_count(sig));
2393             }
2394         }
2395
2396         //do the last incomplete stripe
2397         // for cases of (height & 3) == 0 and 3
2398         // the should have been processed previously
2399         if ((height & 3) == 1 || (height & 3) == 2) {
2400             //generate mbr of first stripe
2401             OPJ_UINT32 *sig = height & 0x4 ? sigma2 : sigma1;
2402             OPJ_UINT32 *mbr = height & 0x4 ? mbr2 : mbr1;
2403             //integrate horizontally
2404             OPJ_UINT32 prev = 0;
2405             OPJ_INT32 i;
2406             for (i = 0; i < width; i += 8, mbr++, sig++) {
2407                 OPJ_UINT32 t, z;
2408
2409                 mbr[0] = sig[0];
2410                 mbr[0] |= prev >> 28;    //for first column, left neighbors
2411                 mbr[0] |= sig[0] << 4;   //left neighbors
2412                 mbr[0] |= sig[0] >> 4;   //left neighbors
2413                 mbr[0] |= sig[1] << 28;  //for last column, right neighbors
2414                 prev = sig[0];
2415
2416                 //integrate vertically
2417                 t = mbr[0], z = mbr[0];
2418                 z |= (t & 0x77777777) << 1; //above neighbors
2419                 z |= (t & 0xEEEEEEEE) >> 1; //below neighbors
2420                 mbr[0] = z & ~sig[0]; //remove already significance samples
2421             }
2422         }
2423
2424         st = height;
2425         st -= height > 6 ? (((height + 1) & 3) + 3) : height;
2426         for (y = st; y < height; y += 4) {
2427             OPJ_UINT32 *cur_sig, *cur_mbr, *nxt_sig, *nxt_mbr;
2428             OPJ_UINT32 val;
2429             OPJ_INT32 i;
2430
2431             OPJ_UINT32 pattern = 0xFFFFFFFFu; // a pattern needed samples
2432             if (height - y == 3) {
2433                 pattern = 0x77777777u;
2434             } else if (height - y == 2) {
2435                 pattern = 0x33333333u;
2436             } else if (height - y == 1) {
2437                 pattern = 0x11111111u;
2438             }
2439
2440             //add membership from the next stripe, obtained above
2441             if (height - y > 4) {
2442                 OPJ_UINT32 prev = 0;
2443                 OPJ_INT32 i;
2444                 cur_sig = y & 0x4 ? sigma2 : sigma1;
2445                 cur_mbr = y & 0x4 ? mbr2 : mbr1;
2446                 nxt_sig = y & 0x4 ? sigma1 : sigma2;
2447                 for (i = 0; i < width; i += 8, cur_mbr++, cur_sig++, nxt_sig++) {
2448                     OPJ_UINT32 t = nxt_sig[0];
2449                     t |= prev >> 28;     //for first column, left neighbors
2450                     t |= nxt_sig[0] << 4;   //left neighbors
2451                     t |= nxt_sig[0] >> 4;   //left neighbors
2452                     t |= nxt_sig[1] << 28;  //for last column, right neighbors
2453                     prev = nxt_sig[0];
2454
2455                     if (!stripe_causal) {
2456                         cur_mbr[0] |= (t & 0x11111111u) << 3;
2457                     }
2458                     //remove already significance samples
2459                     cur_mbr[0] &= ~cur_sig[0];
2460                 }
2461             }
2462
2463             //find new locations and get signs
2464             cur_sig = y & 0x4 ? sigma2 : sigma1;
2465             cur_mbr = y & 0x4 ? mbr2 : mbr1;
2466             nxt_sig = y & 0x4 ? sigma1 : sigma2;
2467             nxt_mbr = y & 0x4 ? mbr1 : mbr2;
2468             val = 3u << (p - 2);
2469             for (i = 0; i < width; i += 8,
2470                     cur_sig++, cur_mbr++, nxt_sig++, nxt_mbr++) {
2471                 OPJ_UINT32 mbr = *cur_mbr & pattern; //skip unneeded samples
2472                 OPJ_UINT32 new_sig = 0;
2473                 OPJ_UINT32 ux, tx;
2474                 if (mbr) {
2475                     OPJ_INT32 n;
2476                     for (n = 0; n < 8; n += 4) {
2477                         OPJ_UINT32 col_mask;
2478                         OPJ_UINT32 inv_sig;
2479                         OPJ_INT32 end;
2480                         OPJ_INT32 j;
2481
2482                         OPJ_UINT32 cwd = frwd_fetch(&sigprop);
2483                         OPJ_UINT32 cnt = 0;
2484
2485                         OPJ_UINT32 *dp = decoded_data + y * stride;
2486                         dp += i + n;
2487
2488                         col_mask = 0xFu << (4 * n);
2489
2490                         inv_sig = ~cur_sig[0] & pattern;
2491
2492                         end = n + 4 + i < width ? n + 4 : width - i;
2493                         for (j = n; j < end; ++j, ++dp, col_mask <<= 4) {
2494                             OPJ_UINT32 sample_mask;
2495
2496                             if ((col_mask & mbr) == 0) {
2497                                 continue;
2498                             }
2499
2500                             //scan 4 mbr
2501                             sample_mask = 0x11111111u & col_mask;
2502                             if (mbr & sample_mask) {
2503                                 assert(dp[0] == 0);
2504                                 if (cwd & 1) {
2505                                     OPJ_UINT32 t;
2506                                     new_sig |= sample_mask;
2507                                     t = 0x32u << (j * 4);
2508                                     mbr |= t & inv_sig;
2509                                 }
2510                                 cwd >>= 1;
2511                                 ++cnt;
2512                             }
2513
2514                             sample_mask += sample_mask;
2515                             if (mbr & sample_mask) {
2516                                 assert(dp[stride] == 0);
2517                                 if (cwd & 1) {
2518                                     OPJ_UINT32 t;
2519                                     new_sig |= sample_mask;
2520                                     t = 0x74u << (j * 4);
2521                                     mbr |= t & inv_sig;
2522                                 }
2523                                 cwd >>= 1;
2524                                 ++cnt;
2525                             }
2526
2527                             sample_mask += sample_mask;
2528                             if (mbr & sample_mask) {
2529                                 assert(dp[2 * stride] == 0);
2530                                 if (cwd & 1) {
2531                                     OPJ_UINT32 t;
2532                                     new_sig |= sample_mask;
2533                                     t = 0xE8u << (j * 4);
2534                                     mbr |= t & inv_sig;
2535                                 }
2536                                 cwd >>= 1;
2537                                 ++cnt;
2538                             }
2539
2540                             sample_mask += sample_mask;
2541                             if (mbr & sample_mask) {
2542                                 assert(dp[3 * stride] == 0);
2543                                 if (cwd & 1) {
2544                                     OPJ_UINT32 t;
2545                                     new_sig |= sample_mask;
2546                                     t = 0xC0u << (j * 4);
2547                                     mbr |= t & inv_sig;
2548                                 }
2549                                 cwd >>= 1;
2550                                 ++cnt;
2551                             }
2552                         }
2553
2554                         //signs here
2555                         if (new_sig & (0xFFFFu << (4 * n))) {
2556                             OPJ_UINT32 col_mask;
2557                             OPJ_INT32 j;
2558                             OPJ_UINT32 *dp = decoded_data + y * stride;
2559                             dp += i + n;
2560                             col_mask = 0xFu << (4 * n);
2561
2562                             for (j = n; j < end; ++j, ++dp, col_mask <<= 4) {
2563                                 OPJ_UINT32 sample_mask;
2564                                 if ((col_mask & new_sig) == 0) {
2565                                     continue;
2566                                 }
2567
2568                                 //scan 4 signs
2569                                 sample_mask = 0x11111111u & col_mask;
2570                                 if (new_sig & sample_mask) {
2571                                     assert(dp[0] == 0);
2572                                     dp[0] |= ((cwd & 1) << 31) | val;
2573                                     cwd >>= 1;
2574                                     ++cnt;
2575                                 }
2576
2577                                 sample_mask += sample_mask;
2578                                 if (new_sig & sample_mask) {
2579                                     assert(dp[stride] == 0);
2580                                     dp[stride] |= ((cwd & 1) << 31) | val;
2581                                     cwd >>= 1;
2582                                     ++cnt;
2583                                 }
2584
2585                                 sample_mask += sample_mask;
2586                                 if (new_sig & sample_mask) {
2587                                     assert(dp[2 * stride] == 0);
2588                                     dp[2 * stride] |= ((cwd & 1) << 31) | val;
2589                                     cwd >>= 1;
2590                                     ++cnt;
2591                                 }
2592
2593                                 sample_mask += sample_mask;
2594                                 if (new_sig & sample_mask) {
2595                                     assert(dp[3 * stride] == 0);
2596                                     dp[3 * stride] |= ((cwd & 1) << 31) | val;
2597                                     cwd >>= 1;
2598                                     ++cnt;
2599                                 }
2600                             }
2601
2602                         }
2603                         frwd_advance(&sigprop, cnt);
2604                         cnt = 0;
2605
2606                         //update next columns
2607                         if (n == 4) {
2608                             //horizontally
2609                             OPJ_UINT32 t = new_sig >> 28;
2610                             t |= ((t & 0xE) >> 1) | ((t & 7) << 1);
2611                             cur_mbr[1] |= t & ~cur_sig[1];
2612                         }
2613                     }
2614                 }
2615                 //propagate down (vertically propagation)
2616                 new_sig |= cur_sig[0];
2617                 ux = (new_sig & 0x88888888) >> 3;
2618                 tx = ux | (ux << 4) | (ux >> 4);
2619                 if (i > 0) {
2620                     nxt_mbr[-1] |= (ux << 28) & ~nxt_sig[-1];
2621                 }
2622                 nxt_mbr[0] |= tx & ~nxt_sig[0];
2623                 nxt_mbr[1] |= (ux >> 28) & ~nxt_sig[1];
2624             }
2625         }
2626     }
2627
2628     {
2629         OPJ_INT32 x, y;
2630         for (y = 0; y < height; ++y) {
2631             OPJ_INT32* sp = (OPJ_INT32*)decoded_data + y * stride;
2632             for (x = 0; x < width; ++x, ++sp) {
2633                 OPJ_INT32 val = (*sp & 0x7FFFFFFF);
2634                 *sp = ((OPJ_UINT32) * sp & 0x80000000) ? -val : val;
2635             }
2636         }
2637     }
2638
2639     return OPJ_TRUE;
2640 }