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