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