opj_t1_ht_decode_cblk(): avoid memcpy() with 0-input size and nullptr destination...
[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 Decode 1 HT code-block
1088 @param t1 T1 handle
1089 @param cblk Code-block coding parameters
1090 @param orient
1091 @param roishift Region of interest shifting value
1092 @param cblksty Code-block style
1093 @param p_manager the event manager
1094 @param p_manager_mutex mutex for the event manager
1095 @param check_pterm whether PTERM correct termination should be checked
1096 */
1097 OPJ_BOOL opj_t1_ht_decode_cblk(opj_t1_t *t1,
1098                                opj_tcd_cblk_dec_t* cblk,
1099                                OPJ_UINT32 orient,
1100                                OPJ_UINT32 roishift,
1101                                OPJ_UINT32 cblksty,
1102                                opj_event_mgr_t *p_manager,
1103                                opj_mutex_t* p_manager_mutex,
1104                                OPJ_BOOL check_pterm);
1105
1106 //************************************************************************/
1107 /** @brief Decodes one codeblock, processing the cleanup, siginificance
1108   *         propagation, and magnitude refinement pass
1109   *
1110   *  @param [in, out]  t1 is codeblock cofficients storage
1111   *  @param [in]       cblk is codeblock properties
1112   *  @param [in]       orient is the subband to which the codeblock belongs (not needed)
1113   *  @param [in]       roishift is region of interest shift
1114   *  @param [in]       cblksty is codeblock style
1115   *  @param [in]       p_manager is events print manager
1116   *  @param [in]       p_manager_mutex a mutex to control access to p_manager
1117   *  @param [in]       check_pterm: check termination (not used)
1118   */
1119 OPJ_BOOL opj_t1_ht_decode_cblk(opj_t1_t *t1,
1120                                opj_tcd_cblk_dec_t* cblk,
1121                                OPJ_UINT32 orient,
1122                                OPJ_UINT32 roishift,
1123                                OPJ_UINT32 cblksty,
1124                                opj_event_mgr_t *p_manager,
1125                                opj_mutex_t* p_manager_mutex,
1126                                OPJ_BOOL check_pterm)
1127 {
1128     OPJ_BYTE* cblkdata = NULL;
1129     OPJ_UINT8* coded_data;
1130     OPJ_UINT32* decoded_data;
1131     OPJ_UINT32 zero_bplanes;
1132     OPJ_UINT32 num_passes;
1133     OPJ_UINT32 lengths1;
1134     OPJ_UINT32 lengths2;
1135     OPJ_INT32 width;
1136     OPJ_INT32 height;
1137     OPJ_INT32 stride;
1138     OPJ_UINT32 *pflags, *sigma1, *sigma2, *mbr1, *mbr2, *sip, sip_shift;
1139     OPJ_UINT32 p;
1140     OPJ_UINT32 zero_bplanes_p1;
1141     int lcup, scup;
1142     dec_mel_t mel;
1143     rev_struct_t vlc;
1144     frwd_struct_t magsgn;
1145     frwd_struct_t sigprop;
1146     rev_struct_t magref;
1147     OPJ_UINT8 *lsp, *line_state;
1148     int run;
1149     OPJ_UINT32 vlc_val;              // fetched data from VLC bitstream
1150     OPJ_UINT32 qinf[2];
1151     OPJ_UINT32 c_q;
1152     OPJ_UINT32* sp;
1153     OPJ_INT32 x, y; // loop indices
1154     OPJ_BOOL stripe_causal = (cblksty & J2K_CCP_CBLKSTY_VSC) != 0;
1155     OPJ_UINT32 cblk_len = 0;
1156
1157     (void)(orient);      // stops unused parameter message
1158     (void)(check_pterm); // stops unused parameter message
1159
1160     // We ignor orient, because the same decoder is used for all subbands
1161     // We also ignore check_pterm, because I am not sure how it applies
1162     if (roishift != 0) {
1163         if (p_manager_mutex) {
1164             opj_mutex_lock(p_manager_mutex);
1165         }
1166         opj_event_msg(p_manager, EVT_ERROR, "We do not support ROI in decoding "
1167                       "HT codeblocks\n");
1168         if (p_manager_mutex) {
1169             opj_mutex_unlock(p_manager_mutex);
1170         }
1171         return OPJ_FALSE;
1172     }
1173
1174     if (!opj_t1_allocate_buffers(
1175                 t1,
1176                 (OPJ_UINT32)(cblk->x1 - cblk->x0),
1177                 (OPJ_UINT32)(cblk->y1 - cblk->y0))) {
1178         return OPJ_FALSE;
1179     }
1180
1181     if (cblk->Mb == 0) {
1182         return OPJ_TRUE;
1183     }
1184
1185     /* numbps = Mb + 1 - zero_bplanes, Mb = Kmax, zero_bplanes = missing_msbs */
1186     zero_bplanes = (cblk->Mb + 1) - cblk->numbps;
1187
1188     /* Compute whole codeblock length from chunk lengths */
1189     cblk_len = 0;
1190     {
1191         OPJ_UINT32 i;
1192         for (i = 0; i < cblk->numchunks; i++) {
1193             cblk_len += cblk->chunks[i].len;
1194         }
1195     }
1196
1197     if (cblk->numchunks > 1 || t1->mustuse_cblkdatabuffer) {
1198         OPJ_UINT32 i;
1199
1200         /* Allocate temporary memory if needed */
1201         if (cblk_len > t1->cblkdatabuffersize) {
1202             cblkdata = (OPJ_BYTE*)opj_realloc(
1203                            t1->cblkdatabuffer, cblk_len);
1204             if (cblkdata == NULL) {
1205                 return OPJ_FALSE;
1206             }
1207             t1->cblkdatabuffer = cblkdata;
1208             t1->cblkdatabuffersize = cblk_len;
1209         }
1210
1211         /* Concatenate all chunks */
1212         cblkdata = t1->cblkdatabuffer;
1213         if (cblkdata == NULL) {
1214             return OPJ_FALSE;
1215         }
1216         cblk_len = 0;
1217         for (i = 0; i < cblk->numchunks; i++) {
1218             memcpy(cblkdata + cblk_len, cblk->chunks[i].data, cblk->chunks[i].len);
1219             cblk_len += cblk->chunks[i].len;
1220         }
1221     } else if (cblk->numchunks == 1) {
1222         cblkdata = cblk->chunks[0].data;
1223     } else {
1224         /* Not sure if that can happen in practice, but avoid Coverity to */
1225         /* think we will dereference a null cblkdta pointer */
1226         return OPJ_TRUE;
1227     }
1228
1229     // OPJ_BYTE* coded_data is a pointer to bitstream
1230     coded_data = cblkdata;
1231     // OPJ_UINT32* decoded_data is a pointer to decoded codeblock data buf.
1232     decoded_data = (OPJ_UINT32*)t1->data;
1233     // OPJ_UINT32 num_passes is the number of passes: 1 if CUP only, 2 for
1234     // CUP+SPP, and 3 for CUP+SPP+MRP
1235     num_passes = cblk->numsegs > 0 ? cblk->segs[0].real_num_passes : 0;
1236     num_passes += cblk->numsegs > 1 ? cblk->segs[1].real_num_passes : 0;
1237     // OPJ_UINT32 lengths1 is the length of cleanup pass
1238     lengths1 = num_passes > 0 ? cblk->segs[0].len : 0;
1239     // OPJ_UINT32 lengths2 is the length of refinement passes (either SPP only or SPP+MRP)
1240     lengths2 = num_passes > 1 ? cblk->segs[1].len : 0;
1241     // OPJ_INT32 width is the decoded codeblock width
1242     width = cblk->x1 - cblk->x0;
1243     // OPJ_INT32 height is the decoded codeblock height
1244     height = cblk->y1 - cblk->y0;
1245     // OPJ_INT32 stride is the decoded codeblock buffer stride
1246     stride = width;
1247
1248     /*  sigma1 and sigma2 contains significant (i.e., non-zero) pixel
1249      *  locations.  The buffers are used interchangeably, because we need
1250      *  more than 4 rows of significance information at a given time.
1251      *  Each 32 bits contain significance information for 4 rows of 8
1252      *  columns each.  If we denote 32 bits by 0xaaaaaaaa, the each "a" is
1253      *  called a nibble and has significance information for 4 rows.
1254      *  The least significant nibble has information for the first column,
1255      *  and so on. The nibble's LSB is for the first row, and so on.
1256      *  Since, at most, we can have 1024 columns in a quad, we need 128
1257      *  entries; we added 1 for convenience when propagation of signifcance
1258      *  goes outside the structure
1259      *  To work in OpenJPEG these buffers has been expanded to 132.
1260      */
1261     // OPJ_UINT32 *pflags, *sigma1, *sigma2, *mbr1, *mbr2, *sip, sip_shift;
1262     pflags = (OPJ_UINT32 *)t1->flags;
1263     sigma1 = pflags;
1264     sigma2 = sigma1 + 132;
1265     // mbr arrangement is similar to sigma; mbr contains locations
1266     // that become significant during significance propagation pass
1267     mbr1 = sigma2 + 132;
1268     mbr2 = mbr1 + 132;
1269     //a pointer to sigma
1270     sip = sigma1;  //pointers to arrays to be used interchangeably
1271     sip_shift = 0; //the amount of shift needed for sigma
1272
1273     if (num_passes > 1 && lengths2 == 0) {
1274         if (p_manager_mutex) {
1275             opj_mutex_lock(p_manager_mutex);
1276         }
1277         opj_event_msg(p_manager, EVT_WARNING, "A malformed codeblock that has "
1278                       "more than one coding pass, but zero length for "
1279                       "2nd and potentially the 3rd pass in an HT codeblock.\n");
1280         if (p_manager_mutex) {
1281             opj_mutex_unlock(p_manager_mutex);
1282         }
1283         num_passes = 1;
1284     }
1285     if (num_passes > 3) {
1286         if (p_manager_mutex) {
1287             opj_mutex_lock(p_manager_mutex);
1288         }
1289         opj_event_msg(p_manager, EVT_ERROR, "We do not support more than 3 "
1290                       "coding passes in an HT codeblock; This codeblocks has "
1291                       "%d passes.\n", num_passes);
1292         if (p_manager_mutex) {
1293             opj_mutex_unlock(p_manager_mutex);
1294         }
1295         return OPJ_FALSE;
1296     }
1297
1298     if (cblk->Mb > 30) {
1299         /* This check is better moved to opj_t2_read_packet_header() in t2.c
1300            We do not have enough precision to decode any passes
1301            The design of openjpeg assumes that the bits of a 32-bit integer are
1302            assigned as follows:
1303            bit 31 is for sign
1304            bits 30-1 are for magnitude
1305            bit 0 is for the center of the quantization bin
1306            Therefore we can only do values of cblk->Mb <= 30
1307          */
1308         if (p_manager_mutex) {
1309             opj_mutex_lock(p_manager_mutex);
1310         }
1311         opj_event_msg(p_manager, EVT_ERROR, "32 bits are not enough to "
1312                       "decode this codeblock, since the number of "
1313                       "bitplane, %d, is larger than 30.\n", cblk->Mb);
1314         if (p_manager_mutex) {
1315             opj_mutex_unlock(p_manager_mutex);
1316         }
1317         return OPJ_FALSE;
1318     }
1319     if (zero_bplanes > cblk->Mb) {
1320         /* This check is better moved to opj_t2_read_packet_header() in t2.c,
1321            in the line "l_cblk->numbps = (OPJ_UINT32)l_band->numbps + 1 - i;"
1322            where i is the zero bitplanes, and should be no larger than cblk->Mb
1323            We cannot have more zero bitplanes than there are planes. */
1324         if (p_manager_mutex) {
1325             opj_mutex_lock(p_manager_mutex);
1326         }
1327         opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1328                       "Decoding this codeblock is stopped. There are "
1329                       "%d zero bitplanes in %d bitplanes.\n",
1330                       zero_bplanes, cblk->Mb);
1331
1332         if (p_manager_mutex) {
1333             opj_mutex_unlock(p_manager_mutex);
1334         }
1335         return OPJ_FALSE;
1336     } else if (zero_bplanes == cblk->Mb && num_passes > 1) {
1337         /* When the number of zero bitplanes is equal to the number of bitplanes,
1338            only the cleanup pass makes sense*/
1339         if (only_cleanup_pass_is_decoded == OPJ_FALSE) {
1340             if (p_manager_mutex) {
1341                 opj_mutex_lock(p_manager_mutex);
1342             }
1343             /* We have a second check to prevent the possibility of an overrun condition,
1344                in the very unlikely event of a second thread discovering that
1345                only_cleanup_pass_is_decoded is false before the first thread changing
1346                the condition. */
1347             if (only_cleanup_pass_is_decoded == OPJ_FALSE) {
1348                 only_cleanup_pass_is_decoded = OPJ_TRUE;
1349                 opj_event_msg(p_manager, EVT_WARNING, "Malformed HT codeblock. "
1350                               "When the number of zero planes bitplanes is "
1351                               "equal to the number of bitplanes, only the cleanup "
1352                               "pass makes sense, but we have %d passes in this "
1353                               "codeblock. Therefore, only the cleanup pass will be "
1354                               "decoded. This message will not be displayed again.\n",
1355                               num_passes);
1356             }
1357             if (p_manager_mutex) {
1358                 opj_mutex_unlock(p_manager_mutex);
1359             }
1360         }
1361         num_passes = 1;
1362     }
1363
1364     /* OPJ_UINT32 */
1365     p = cblk->numbps;
1366
1367     // OPJ_UINT32 zero planes plus 1
1368     zero_bplanes_p1 = zero_bplanes + 1;
1369
1370     if (lengths1 < 2 || (OPJ_UINT32)lengths1 > cblk_len ||
1371             (OPJ_UINT32)(lengths1 + lengths2) > cblk_len) {
1372         if (p_manager_mutex) {
1373             opj_mutex_lock(p_manager_mutex);
1374         }
1375         opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1376                       "Invalid codeblock length values.\n");
1377
1378         if (p_manager_mutex) {
1379             opj_mutex_unlock(p_manager_mutex);
1380         }
1381         return OPJ_FALSE;
1382     }
1383     // read scup and fix the bytes there
1384     lcup = (int)lengths1;  // length of CUP
1385     //scup is the length of MEL + VLC
1386     scup = (((int)coded_data[lcup - 1]) << 4) + (coded_data[lcup - 2] & 0xF);
1387     if (scup < 2 || scup > lcup || scup > 4079) { //something is wrong
1388         /* The standard stipulates 2 <= Scup <= min(Lcup, 4079) */
1389         if (p_manager_mutex) {
1390             opj_mutex_lock(p_manager_mutex);
1391         }
1392         opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1393                       "One of the following condition is not met: "
1394                       "2 <= Scup <= min(Lcup, 4079)\n");
1395
1396         if (p_manager_mutex) {
1397             opj_mutex_unlock(p_manager_mutex);
1398         }
1399         return OPJ_FALSE;
1400     }
1401
1402     // init structures
1403     if (mel_init(&mel, coded_data, lcup, scup) == OPJ_FALSE) {
1404         if (p_manager_mutex) {
1405             opj_mutex_lock(p_manager_mutex);
1406         }
1407         opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1408                       "Incorrect MEL segment sequence.\n");
1409         if (p_manager_mutex) {
1410             opj_mutex_unlock(p_manager_mutex);
1411         }
1412         return OPJ_FALSE;
1413     }
1414     rev_init(&vlc, coded_data, lcup, scup);
1415     frwd_init(&magsgn, coded_data, lcup - scup, 0xFF);
1416     if (num_passes > 1) { // needs to be tested
1417         frwd_init(&sigprop, coded_data + lengths1, (int)lengths2, 0);
1418     }
1419     if (num_passes > 2) {
1420         rev_init_mrp(&magref, coded_data, (int)lengths1, (int)lengths2);
1421     }
1422
1423     /** State storage
1424       *  One byte per quad; for 1024 columns, or 512 quads, we need
1425       *  512 bytes. We are using 2 extra bytes one on the left and one on
1426       *  the right for convenience.
1427       *
1428       *  The MSB bit in each byte is (\sigma^nw | \sigma^n), and the 7 LSBs
1429       *  contain max(E^nw | E^n)
1430       */
1431
1432     // 514 is enough for a block width of 1024, +2 extra
1433     // here expanded to 528
1434     line_state = (OPJ_UINT8 *)(mbr2 + 132);
1435
1436     //initial 2 lines
1437     /////////////////
1438     lsp = line_state;              // point to line state
1439     lsp[0] = 0;                    // for initial row of quad, we set to 0
1440     run = mel_get_run(&mel);    // decode runs of events from MEL bitstrm
1441     // data represented as runs of 0 events
1442     // See mel_decode description
1443     qinf[0] = qinf[1] = 0;      // quad info decoded from VLC bitstream
1444     c_q = 0;                    // context for quad q
1445     sp = decoded_data;          // decoded codeblock samples
1446     // vlc_val;                 // fetched data from VLC bitstream
1447
1448     for (x = 0; x < width; x += 4) { // one iteration per quad pair
1449         OPJ_UINT32 U_q[2]; // u values for the quad pair
1450         OPJ_UINT32 uvlc_mode;
1451         OPJ_UINT32 consumed_bits;
1452         OPJ_UINT32 m_n, v_n;
1453         OPJ_UINT32 ms_val;
1454         OPJ_UINT32 locs;
1455
1456         // decode VLC
1457         /////////////
1458
1459         //first quad
1460         // Get the head of the VLC bitstream. One fetch is enough for two
1461         // quads, since the largest VLC code is 7 bits, and maximum number of
1462         // bits used for u is 8.  Therefore for two quads we need 30 bits
1463         // (if we include unstuffing, then 32 bits are enough, since we have
1464         // a maximum of one stuffing per two bytes)
1465         vlc_val = rev_fetch(&vlc);
1466
1467         //decode VLC using the context c_q and the head of the VLC bitstream
1468         qinf[0] = vlc_tbl0[(c_q << 7) | (vlc_val & 0x7F) ];
1469
1470         if (c_q == 0) { // if zero context, we need to use one MEL event
1471             run -= 2; //the number of 0 events is multiplied by 2, so subtract 2
1472
1473             // Is the run terminated in 1? if so, use decoded VLC code,
1474             // otherwise, discard decoded data, since we will decoded again
1475             // using a different context
1476             qinf[0] = (run == -1) ? qinf[0] : 0;
1477
1478             // is run -1 or -2? this means a run has been consumed
1479             if (run < 0) {
1480                 run = mel_get_run(&mel);    // get another run
1481             }
1482         }
1483
1484         // prepare context for the next quad; eqn. 1 in ITU T.814
1485         c_q = ((qinf[0] & 0x10) >> 4) | ((qinf[0] & 0xE0) >> 5);
1486
1487         //remove data from vlc stream (0 bits are removed if qinf is not used)
1488         vlc_val = rev_advance(&vlc, qinf[0] & 0x7);
1489
1490         //update sigma
1491         // The update depends on the value of x; consider one OPJ_UINT32
1492         // if x is 0, 8, 16 and so on, then this line update c locations
1493         //      nibble (4 bits) number   0 1 2 3 4 5 6 7
1494         //                         LSB   c c 0 0 0 0 0 0
1495         //                               c c 0 0 0 0 0 0
1496         //                               0 0 0 0 0 0 0 0
1497         //                               0 0 0 0 0 0 0 0
1498         // if x is 4, 12, 20, then this line update locations c
1499         //      nibble (4 bits) number   0 1 2 3 4 5 6 7
1500         //                         LSB   0 0 0 0 c c 0 0
1501         //                               0 0 0 0 c c 0 0
1502         //                               0 0 0 0 0 0 0 0
1503         //                               0 0 0 0 0 0 0 0
1504         *sip |= (((qinf[0] & 0x30) >> 4) | ((qinf[0] & 0xC0) >> 2)) << sip_shift;
1505
1506         //second quad
1507         qinf[1] = 0;
1508         if (x + 2 < width) { // do not run if codeblock is narrower
1509             //decode VLC using the context c_q and the head of the VLC bitstream
1510             qinf[1] = vlc_tbl0[(c_q << 7) | (vlc_val & 0x7F)];
1511
1512             // if context is zero, use one MEL event
1513             if (c_q == 0) { //zero context
1514                 run -= 2; //subtract 2, since events number if multiplied by 2
1515
1516                 // if event is 0, discard decoded qinf
1517                 qinf[1] = (run == -1) ? qinf[1] : 0;
1518
1519                 if (run < 0) { // have we consumed all events in a run
1520                     run = mel_get_run(&mel);    // if yes, then get another run
1521                 }
1522             }
1523
1524             //prepare context for the next quad, eqn. 1 in ITU T.814
1525             c_q = ((qinf[1] & 0x10) >> 4) | ((qinf[1] & 0xE0) >> 5);
1526
1527             //remove data from vlc stream, if qinf is not used, cwdlen is 0
1528             vlc_val = rev_advance(&vlc, qinf[1] & 0x7);
1529         }
1530
1531         //update sigma
1532         // The update depends on the value of x; consider one OPJ_UINT32
1533         // if x is 0, 8, 16 and so on, then this line update c locations
1534         //      nibble (4 bits) number   0 1 2 3 4 5 6 7
1535         //                         LSB   0 0 c c 0 0 0 0
1536         //                               0 0 c c 0 0 0 0
1537         //                               0 0 0 0 0 0 0 0
1538         //                               0 0 0 0 0 0 0 0
1539         // if x is 4, 12, 20, then this line update locations c
1540         //      nibble (4 bits) number   0 1 2 3 4 5 6 7
1541         //                         LSB   0 0 0 0 0 0 c c
1542         //                               0 0 0 0 0 0 c c
1543         //                               0 0 0 0 0 0 0 0
1544         //                               0 0 0 0 0 0 0 0
1545         *sip |= (((qinf[1] & 0x30) | ((qinf[1] & 0xC0) << 2))) << (4 + sip_shift);
1546
1547         sip += x & 0x7 ? 1 : 0; // move sigma pointer to next entry
1548         sip_shift ^= 0x10;      // increment/decrement sip_shift by 16
1549
1550         // retrieve u
1551         /////////////
1552
1553         // uvlc_mode is made up of u_offset bits from the quad pair
1554         uvlc_mode = ((qinf[0] & 0x8) >> 3) | ((qinf[1] & 0x8) >> 2);
1555         if (uvlc_mode == 3) { // if both u_offset are set, get an event from
1556             // the MEL run of events
1557             run -= 2; //subtract 2, since events number if multiplied by 2
1558             uvlc_mode += (run == -1) ? 1 : 0; //increment uvlc_mode if event is 1
1559             if (run < 0) { // if run is consumed (run is -1 or -2), get another run
1560                 run = mel_get_run(&mel);
1561             }
1562         }
1563         //decode uvlc_mode to get u for both quads
1564         consumed_bits = decode_init_uvlc(vlc_val, uvlc_mode, U_q);
1565         if (U_q[0] > zero_bplanes_p1 || U_q[1] > zero_bplanes_p1) {
1566             if (p_manager_mutex) {
1567                 opj_mutex_lock(p_manager_mutex);
1568             }
1569             opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. Decoding "
1570                           "this codeblock is stopped. U_q is larger than zero "
1571                           "bitplanes + 1 \n");
1572             if (p_manager_mutex) {
1573                 opj_mutex_unlock(p_manager_mutex);
1574             }
1575             return OPJ_FALSE;
1576         }
1577
1578         //consume u bits in the VLC code
1579         vlc_val = rev_advance(&vlc, consumed_bits);
1580
1581         //decode magsgn and update line_state
1582         /////////////////////////////////////
1583
1584         //We obtain a mask for the samples locations that needs evaluation
1585         locs = 0xFF;
1586         if (x + 4 > width) {
1587             locs >>= (x + 4 - width) << 1;    // limits width
1588         }
1589         locs = height > 1 ? locs : (locs & 0x55);         // limits height
1590
1591         if ((((qinf[0] & 0xF0) >> 4) | (qinf[1] & 0xF0)) & ~locs) {
1592             if (p_manager_mutex) {
1593                 opj_mutex_lock(p_manager_mutex);
1594             }
1595             opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1596                           "VLC code produces significant samples outside "
1597                           "the codeblock area.\n");
1598             if (p_manager_mutex) {
1599                 opj_mutex_unlock(p_manager_mutex);
1600             }
1601             return OPJ_FALSE;
1602         }
1603
1604         //first quad, starting at first sample in quad and moving on
1605         if (qinf[0] & 0x10) { //is it significant? (sigma_n)
1606             OPJ_UINT32 val;
1607
1608             ms_val = frwd_fetch(&magsgn);         //get 32 bits of magsgn data
1609             m_n = U_q[0] - ((qinf[0] >> 12) & 1); //evaluate m_n (number of bits
1610             // to read from bitstream), using EMB e_k
1611             frwd_advance(&magsgn, m_n);         //consume m_n
1612             val = ms_val << 31;                 //get sign bit
1613             v_n = ms_val & ((1U << m_n) - 1);   //keep only m_n bits
1614             v_n |= ((qinf[0] & 0x100) >> 8) << m_n;  //add EMB e_1 as MSB
1615             v_n |= 1;                                //add center of bin
1616             //v_n now has 2 * (\mu - 1) + 0.5 with correct sign bit
1617             //add 2 to make it 2*\mu+0.5, shift it up to missing MSBs
1618             sp[0] = val | ((v_n + 2) << (p - 1));
1619         } else if (locs & 0x1) { // if this is inside the codeblock, set the
1620             sp[0] = 0;           // sample to zero
1621         }
1622
1623         if (qinf[0] & 0x20) { //sigma_n
1624             OPJ_UINT32 val, t;
1625
1626             ms_val = frwd_fetch(&magsgn);         //get 32 bits
1627             m_n = U_q[0] - ((qinf[0] >> 13) & 1); //m_n, uses EMB e_k
1628             frwd_advance(&magsgn, m_n);           //consume m_n
1629             val = ms_val << 31;                   //get sign bit
1630             v_n = ms_val & ((1U << m_n) - 1);     //keep only m_n bits
1631             v_n |= ((qinf[0] & 0x200) >> 9) << m_n; //add EMB e_1
1632             v_n |= 1;                               //bin center
1633             //v_n now has 2 * (\mu - 1) + 0.5 with correct sign bit
1634             //add 2 to make it 2*\mu+0.5, shift it up to missing MSBs
1635             sp[stride] = val | ((v_n + 2) << (p - 1));
1636
1637             //update line_state: bit 7 (\sigma^N), and E^N
1638             t = lsp[0] & 0x7F;       // keep E^NW
1639             v_n = 32 - count_leading_zeros(v_n);
1640             lsp[0] = (OPJ_UINT8)(0x80 | (t > v_n ? t : v_n)); //max(E^NW, E^N) | s
1641         } else if (locs & 0x2) { // if this is inside the codeblock, set the
1642             sp[stride] = 0;      // sample to zero
1643         }
1644
1645         ++lsp; // move to next quad information
1646         ++sp;  // move to next column of samples
1647
1648         //this is similar to the above two samples
1649         if (qinf[0] & 0x40) {
1650             OPJ_UINT32 val;
1651
1652             ms_val = frwd_fetch(&magsgn);
1653             m_n = U_q[0] - ((qinf[0] >> 14) & 1);
1654             frwd_advance(&magsgn, m_n);
1655             val = ms_val << 31;
1656             v_n = ms_val & ((1U << m_n) - 1);
1657             v_n |= (((qinf[0] & 0x400) >> 10) << m_n);
1658             v_n |= 1;
1659             sp[0] = val | ((v_n + 2) << (p - 1));
1660         } else if (locs & 0x4) {
1661             sp[0] = 0;
1662         }
1663
1664         lsp[0] = 0;
1665         if (qinf[0] & 0x80) {
1666             OPJ_UINT32 val;
1667             ms_val = frwd_fetch(&magsgn);
1668             m_n = U_q[0] - ((qinf[0] >> 15) & 1); //m_n
1669             frwd_advance(&magsgn, m_n);
1670             val = ms_val << 31;
1671             v_n = ms_val & ((1U << m_n) - 1);
1672             v_n |= ((qinf[0] & 0x800) >> 11) << m_n;
1673             v_n |= 1; //center of bin
1674             sp[stride] = val | ((v_n + 2) << (p - 1));
1675
1676             //line_state: bit 7 (\sigma^NW), and E^NW for next quad
1677             lsp[0] = (OPJ_UINT8)(0x80 | (32 - count_leading_zeros(v_n)));
1678         } else if (locs & 0x8) { //if outside set to 0
1679             sp[stride] = 0;
1680         }
1681
1682         ++sp; //move to next column
1683
1684         //second quad
1685         if (qinf[1] & 0x10) {
1686             OPJ_UINT32 val;
1687
1688             ms_val = frwd_fetch(&magsgn);
1689             m_n = U_q[1] - ((qinf[1] >> 12) & 1); //m_n
1690             frwd_advance(&magsgn, m_n);
1691             val = ms_val << 31;
1692             v_n = ms_val & ((1U << m_n) - 1);
1693             v_n |= (((qinf[1] & 0x100) >> 8) << m_n);
1694             v_n |= 1;
1695             sp[0] = val | ((v_n + 2) << (p - 1));
1696         } else if (locs & 0x10) {
1697             sp[0] = 0;
1698         }
1699
1700         if (qinf[1] & 0x20) {
1701             OPJ_UINT32 val, t;
1702
1703             ms_val = frwd_fetch(&magsgn);
1704             m_n = U_q[1] - ((qinf[1] >> 13) & 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] & 0x200) >> 9) << m_n);
1709             v_n |= 1;
1710             sp[stride] = val | ((v_n + 2) << (p - 1));
1711
1712             //update line_state: bit 7 (\sigma^N), and E^N
1713             t = lsp[0] & 0x7F;            //E^NW
1714             v_n = 32 - count_leading_zeros(v_n);     //E^N
1715             lsp[0] = (OPJ_UINT8)(0x80 | (t > v_n ? t : v_n)); //max(E^NW, E^N) | s
1716         } else if (locs & 0x20) {
1717             sp[stride] = 0;    //no need to update line_state
1718         }
1719
1720         ++lsp; //move line state to next quad
1721         ++sp;  //move to next sample
1722
1723         if (qinf[1] & 0x40) {
1724             OPJ_UINT32 val;
1725
1726             ms_val = frwd_fetch(&magsgn);
1727             m_n = U_q[1] - ((qinf[1] >> 14) & 1); //m_n
1728             frwd_advance(&magsgn, m_n);
1729             val = ms_val << 31;
1730             v_n = ms_val & ((1U << m_n) - 1);
1731             v_n |= (((qinf[1] & 0x400) >> 10) << m_n);
1732             v_n |= 1;
1733             sp[0] = val | ((v_n + 2) << (p - 1));
1734         } else if (locs & 0x40) {
1735             sp[0] = 0;
1736         }
1737
1738         lsp[0] = 0;
1739         if (qinf[1] & 0x80) {
1740             OPJ_UINT32 val;
1741
1742             ms_val = frwd_fetch(&magsgn);
1743             m_n = U_q[1] - ((qinf[1] >> 15) & 1); //m_n
1744             frwd_advance(&magsgn, m_n);
1745             val = ms_val << 31;
1746             v_n = ms_val & ((1U << m_n) - 1);
1747             v_n |= (((qinf[1] & 0x800) >> 11) << m_n);
1748             v_n |= 1; //center of bin
1749             sp[stride] = val | ((v_n + 2) << (p - 1));
1750
1751             //line_state: bit 7 (\sigma^NW), and E^NW for next quad
1752             lsp[0] = (OPJ_UINT8)(0x80 | (32 - count_leading_zeros(v_n)));
1753         } else if (locs & 0x80) {
1754             sp[stride] = 0;
1755         }
1756
1757         ++sp;
1758     }
1759
1760     //non-initial lines
1761     //////////////////////////
1762     for (y = 2; y < height; /*done at the end of loop*/) {
1763         OPJ_UINT32 *sip;
1764         OPJ_UINT8 ls0;
1765         OPJ_INT32 x;
1766
1767         sip_shift ^= 0x2;  // shift sigma to the upper half od the nibble
1768         sip_shift &= 0xFFFFFFEFU; //move back to 0 (it might have been at 0x10)
1769         sip = y & 0x4 ? sigma2 : sigma1; //choose sigma array
1770
1771         lsp = line_state;
1772         ls0 = lsp[0];                   // read the line state value
1773         lsp[0] = 0;                     // and set it to zero
1774         sp = decoded_data + y * stride; // generated samples
1775         c_q = 0;                        // context
1776         for (x = 0; x < width; x += 4) {
1777             OPJ_UINT32 U_q[2];
1778             OPJ_UINT32 uvlc_mode, consumed_bits;
1779             OPJ_UINT32 m_n, v_n;
1780             OPJ_UINT32 ms_val;
1781             OPJ_UINT32 locs;
1782
1783             // decode vlc
1784             /////////////
1785
1786             //first quad
1787             // get context, eqn. 2 ITU T.814
1788             // c_q has \sigma^W | \sigma^SW
1789             c_q |= (ls0 >> 7);          //\sigma^NW | \sigma^N
1790             c_q |= (lsp[1] >> 5) & 0x4; //\sigma^NE | \sigma^NF
1791
1792             //the following is very similar to previous code, so please refer to
1793             // that
1794             vlc_val = rev_fetch(&vlc);
1795             qinf[0] = vlc_tbl1[(c_q << 7) | (vlc_val & 0x7F)];
1796             if (c_q == 0) { //zero context
1797                 run -= 2;
1798                 qinf[0] = (run == -1) ? qinf[0] : 0;
1799                 if (run < 0) {
1800                     run = mel_get_run(&mel);
1801                 }
1802             }
1803             //prepare context for the next quad, \sigma^W | \sigma^SW
1804             c_q = ((qinf[0] & 0x40) >> 5) | ((qinf[0] & 0x80) >> 6);
1805
1806             //remove data from vlc stream
1807             vlc_val = rev_advance(&vlc, qinf[0] & 0x7);
1808
1809             //update sigma
1810             // The update depends on the value of x and y; consider one OPJ_UINT32
1811             // if x is 0, 8, 16 and so on, and y is 2, 6, etc., then this
1812             // line update c locations
1813             //      nibble (4 bits) number   0 1 2 3 4 5 6 7
1814             //                         LSB   0 0 0 0 0 0 0 0
1815             //                               0 0 0 0 0 0 0 0
1816             //                               c c 0 0 0 0 0 0
1817             //                               c c 0 0 0 0 0 0
1818             *sip |= (((qinf[0] & 0x30) >> 4) | ((qinf[0] & 0xC0) >> 2)) << sip_shift;
1819
1820             //second quad
1821             qinf[1] = 0;
1822             if (x + 2 < width) {
1823                 c_q |= (lsp[1] >> 7);
1824                 c_q |= (lsp[2] >> 5) & 0x4;
1825                 qinf[1] = vlc_tbl1[(c_q << 7) | (vlc_val & 0x7F)];
1826                 if (c_q == 0) { //zero context
1827                     run -= 2;
1828                     qinf[1] = (run == -1) ? qinf[1] : 0;
1829                     if (run < 0) {
1830                         run = mel_get_run(&mel);
1831                     }
1832                 }
1833                 //prepare context for the next quad
1834                 c_q = ((qinf[1] & 0x40) >> 5) | ((qinf[1] & 0x80) >> 6);
1835                 //remove data from vlc stream
1836                 vlc_val = rev_advance(&vlc, qinf[1] & 0x7);
1837             }
1838
1839             //update sigma
1840             *sip |= (((qinf[1] & 0x30) | ((qinf[1] & 0xC0) << 2))) << (4 + sip_shift);
1841
1842             sip += x & 0x7 ? 1 : 0;
1843             sip_shift ^= 0x10;
1844
1845             //retrieve u
1846             ////////////
1847             uvlc_mode = ((qinf[0] & 0x8) >> 3) | ((qinf[1] & 0x8) >> 2);
1848             consumed_bits = decode_noninit_uvlc(vlc_val, uvlc_mode, U_q);
1849             vlc_val = rev_advance(&vlc, consumed_bits);
1850
1851             //calculate E^max and add it to U_q, eqns 5 and 6 in ITU T.814
1852             if ((qinf[0] & 0xF0) & ((qinf[0] & 0xF0) - 1)) { // is \gamma_q 1?
1853                 OPJ_UINT32 E = (ls0 & 0x7Fu);
1854                 E = E > (lsp[1] & 0x7Fu) ? E : (lsp[1] & 0x7Fu); //max(E, E^NE, E^NF)
1855                 //since U_q already has u_q + 1, we subtract 2 instead of 1
1856                 U_q[0] += E > 2 ? E - 2 : 0;
1857             }
1858
1859             if ((qinf[1] & 0xF0) & ((qinf[1] & 0xF0) - 1)) { //is \gamma_q 1?
1860                 OPJ_UINT32 E = (lsp[1] & 0x7Fu);
1861                 E = E > (lsp[2] & 0x7Fu) ? E : (lsp[2] & 0x7Fu); //max(E, E^NE, E^NF)
1862                 //since U_q already has u_q + 1, we subtract 2 instead of 1
1863                 U_q[1] += E > 2 ? E - 2 : 0;
1864             }
1865
1866             if (U_q[0] > zero_bplanes_p1 || U_q[1] > zero_bplanes_p1) {
1867                 if (p_manager_mutex) {
1868                     opj_mutex_lock(p_manager_mutex);
1869                 }
1870                 opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1871                               "Decoding this codeblock is stopped. U_q is"
1872                               "larger than bitplanes + 1 \n");
1873                 if (p_manager_mutex) {
1874                     opj_mutex_unlock(p_manager_mutex);
1875                 }
1876                 return OPJ_FALSE;
1877             }
1878
1879             ls0 = lsp[2]; //for next double quad
1880             lsp[1] = lsp[2] = 0;
1881
1882             //decode magsgn and update line_state
1883             /////////////////////////////////////
1884
1885             //locations where samples need update
1886             locs = 0xFF;
1887             if (x + 4 > width) {
1888                 locs >>= (x + 4 - width) << 1;
1889             }
1890             locs = y + 2 <= height ? locs : (locs & 0x55);
1891
1892             if ((((qinf[0] & 0xF0) >> 4) | (qinf[1] & 0xF0)) & ~locs) {
1893                 if (p_manager_mutex) {
1894                     opj_mutex_lock(p_manager_mutex);
1895                 }
1896                 opj_event_msg(p_manager, EVT_ERROR, "Malformed HT codeblock. "
1897                               "VLC code produces significant samples outside "
1898                               "the codeblock area.\n");
1899                 if (p_manager_mutex) {
1900                     opj_mutex_unlock(p_manager_mutex);
1901                 }
1902                 return OPJ_FALSE;
1903             }
1904
1905
1906
1907             if (qinf[0] & 0x10) { //sigma_n
1908                 OPJ_UINT32 val;
1909
1910                 ms_val = frwd_fetch(&magsgn);
1911                 m_n = U_q[0] - ((qinf[0] >> 12) & 1); //m_n
1912                 frwd_advance(&magsgn, m_n);
1913                 val = ms_val << 31;
1914                 v_n = ms_val & ((1U << m_n) - 1);
1915                 v_n |= ((qinf[0] & 0x100) >> 8) << m_n;
1916                 v_n |= 1; //center of bin
1917                 sp[0] = val | ((v_n + 2) << (p - 1));
1918             } else if (locs & 0x1) {
1919                 sp[0] = 0;
1920             }
1921
1922             if (qinf[0] & 0x20) { //sigma_n
1923                 OPJ_UINT32 val, t;
1924
1925                 ms_val = frwd_fetch(&magsgn);
1926                 m_n = U_q[0] - ((qinf[0] >> 13) & 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] & 0x200) >> 9) << m_n;
1931                 v_n |= 1; //center of bin
1932                 sp[stride] = val | ((v_n + 2) << (p - 1));
1933
1934                 //update line_state: bit 7 (\sigma^N), and E^N
1935                 t = lsp[0] & 0x7F;          //E^NW
1936                 v_n = 32 - count_leading_zeros(v_n);
1937                 lsp[0] = (OPJ_UINT8)(0x80 | (t > v_n ? t : v_n));
1938             } else if (locs & 0x2) {
1939                 sp[stride] = 0;    //no need to update line_state
1940             }
1941
1942             ++lsp;
1943             ++sp;
1944
1945             if (qinf[0] & 0x40) { //sigma_n
1946                 OPJ_UINT32 val;
1947
1948                 ms_val = frwd_fetch(&magsgn);
1949                 m_n = U_q[0] - ((qinf[0] >> 14) & 1); //m_n
1950                 frwd_advance(&magsgn, m_n);
1951                 val = ms_val << 31;
1952                 v_n = ms_val & ((1U << m_n) - 1);
1953                 v_n |= (((qinf[0] & 0x400) >> 10) << m_n);
1954                 v_n |= 1;                            //center of bin
1955                 sp[0] = val | ((v_n + 2) << (p - 1));
1956             } else if (locs & 0x4) {
1957                 sp[0] = 0;
1958             }
1959
1960             if (qinf[0] & 0x80) { //sigma_n
1961                 OPJ_UINT32 val;
1962
1963                 ms_val = frwd_fetch(&magsgn);
1964                 m_n = U_q[0] - ((qinf[0] >> 15) & 1); //m_n
1965                 frwd_advance(&magsgn, m_n);
1966                 val = ms_val << 31;
1967                 v_n = ms_val & ((1U << m_n) - 1);
1968                 v_n |= ((qinf[0] & 0x800) >> 11) << m_n;
1969                 v_n |= 1; //center of bin
1970                 sp[stride] = val | ((v_n + 2) << (p - 1));
1971
1972                 //update line_state: bit 7 (\sigma^NW), and E^NW for next quad
1973                 lsp[0] = (OPJ_UINT8)(0x80 | (32 - count_leading_zeros(v_n)));
1974             } else if (locs & 0x8) {
1975                 sp[stride] = 0;
1976             }
1977
1978             ++sp;
1979
1980             if (qinf[1] & 0x10) { //sigma_n
1981                 OPJ_UINT32 val;
1982
1983                 ms_val = frwd_fetch(&magsgn);
1984                 m_n = U_q[1] - ((qinf[1] >> 12) & 1); //m_n
1985                 frwd_advance(&magsgn, m_n);
1986                 val = ms_val << 31;
1987                 v_n = ms_val & ((1U << m_n) - 1);
1988                 v_n |= (((qinf[1] & 0x100) >> 8) << m_n);
1989                 v_n |= 1;                            //center of bin
1990                 sp[0] = val | ((v_n + 2) << (p - 1));
1991             } else if (locs & 0x10) {
1992                 sp[0] = 0;
1993             }
1994
1995             if (qinf[1] & 0x20) { //sigma_n
1996                 OPJ_UINT32 val, t;
1997
1998                 ms_val = frwd_fetch(&magsgn);
1999                 m_n = U_q[1] - ((qinf[1] >> 13) & 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] & 0x200) >> 9) << m_n);
2004                 v_n |= 1; //center of bin
2005                 sp[stride] = val | ((v_n + 2) << (p - 1));
2006
2007                 //update line_state: bit 7 (\sigma^N), and E^N
2008                 t = lsp[0] & 0x7F;          //E^NW
2009                 v_n = 32 - count_leading_zeros(v_n);
2010                 lsp[0] = (OPJ_UINT8)(0x80 | (t > v_n ? t : v_n));
2011             } else if (locs & 0x20) {
2012                 sp[stride] = 0;    //no need to update line_state
2013             }
2014
2015             ++lsp;
2016             ++sp;
2017
2018             if (qinf[1] & 0x40) { //sigma_n
2019                 OPJ_UINT32 val;
2020
2021                 ms_val = frwd_fetch(&magsgn);
2022                 m_n = U_q[1] - ((qinf[1] >> 14) & 1); //m_n
2023                 frwd_advance(&magsgn, m_n);
2024                 val = ms_val << 31;
2025                 v_n = ms_val & ((1U << m_n) - 1);
2026                 v_n |= (((qinf[1] & 0x400) >> 10) << m_n);
2027                 v_n |= 1;                            //center of bin
2028                 sp[0] = val | ((v_n + 2) << (p - 1));
2029             } else if (locs & 0x40) {
2030                 sp[0] = 0;
2031             }
2032
2033             if (qinf[1] & 0x80) { //sigma_n
2034                 OPJ_UINT32 val;
2035
2036                 ms_val = frwd_fetch(&magsgn);
2037                 m_n = U_q[1] - ((qinf[1] >> 15) & 1); //m_n
2038                 frwd_advance(&magsgn, m_n);
2039                 val = ms_val << 31;
2040                 v_n = ms_val & ((1U << m_n) - 1);
2041                 v_n |= (((qinf[1] & 0x800) >> 11) << m_n);
2042                 v_n |= 1; //center of bin
2043                 sp[stride] = val | ((v_n + 2) << (p - 1));
2044
2045                 //update line_state: bit 7 (\sigma^NW), and E^NW for next quad
2046                 lsp[0] = (OPJ_UINT8)(0x80 | (32 - count_leading_zeros(v_n)));
2047             } else if (locs & 0x80) {
2048                 sp[stride] = 0;
2049             }
2050
2051             ++sp;
2052         }
2053
2054         y += 2;
2055         if (num_passes > 1 && (y & 3) == 0) { //executed at multiples of 4
2056             // This is for SPP and potentially MRP
2057
2058             if (num_passes > 2) { //do MRP
2059                 // select the current stripe
2060                 OPJ_UINT32 *cur_sig = y & 0x4 ? sigma1 : sigma2;
2061                 // the address of the data that needs updating
2062                 OPJ_UINT32 *dpp = decoded_data + (y - 4) * stride;
2063                 OPJ_UINT32 half = 1u << (p - 2); // half the center of the bin
2064                 OPJ_INT32 i;
2065                 for (i = 0; i < width; i += 8) {
2066                     //Process one entry from sigma array at a time
2067                     // Each nibble (4 bits) in the sigma array represents 4 rows,
2068                     // and the 32 bits contain 8 columns
2069                     OPJ_UINT32 cwd = rev_fetch_mrp(&magref); // get 32 bit data
2070                     OPJ_UINT32 sig = *cur_sig++; // 32 bit that will be processed now
2071                     OPJ_UINT32 col_mask = 0xFu;  // a mask for a column in sig
2072                     OPJ_UINT32 *dp = dpp + i;    // next column in decode samples
2073                     if (sig) { // if any of the 32 bits are set
2074                         int j;
2075                         for (j = 0; j < 8; ++j, dp++) { //one column at a time
2076                             if (sig & col_mask) { // lowest nibble
2077                                 OPJ_UINT32 sample_mask = 0x11111111u & col_mask; //LSB
2078
2079                                 if (sig & sample_mask) { //if LSB is set
2080                                     OPJ_UINT32 sym;
2081
2082                                     assert(dp[0] != 0); // decoded value cannot be zero
2083                                     sym = cwd & 1; // get it value
2084                                     // remove center of bin if sym is 0
2085                                     dp[0] ^= (1 - sym) << (p - 1);
2086                                     dp[0] |= half;      // put half the center of bin
2087                                     cwd >>= 1;          //consume word
2088                                 }
2089                                 sample_mask += sample_mask; //next row
2090
2091                                 if (sig & sample_mask) {
2092                                     OPJ_UINT32 sym;
2093
2094                                     assert(dp[stride] != 0);
2095                                     sym = cwd & 1;
2096                                     dp[stride] ^= (1 - sym) << (p - 1);
2097                                     dp[stride] |= half;
2098                                     cwd >>= 1;
2099                                 }
2100                                 sample_mask += sample_mask;
2101
2102                                 if (sig & sample_mask) {
2103                                     OPJ_UINT32 sym;
2104
2105                                     assert(dp[2 * stride] != 0);
2106                                     sym = cwd & 1;
2107                                     dp[2 * stride] ^= (1 - sym) << (p - 1);
2108                                     dp[2 * stride] |= half;
2109                                     cwd >>= 1;
2110                                 }
2111                                 sample_mask += sample_mask;
2112
2113                                 if (sig & sample_mask) {
2114                                     OPJ_UINT32 sym;
2115
2116                                     assert(dp[3 * stride] != 0);
2117                                     sym = cwd & 1;
2118                                     dp[3 * stride] ^= (1 - sym) << (p - 1);
2119                                     dp[3 * stride] |= half;
2120                                     cwd >>= 1;
2121                                 }
2122                                 sample_mask += sample_mask;
2123                             }
2124                             col_mask <<= 4; //next column
2125                         }
2126                     }
2127                     // consume data according to the number of bits set
2128                     rev_advance_mrp(&magref, population_count(sig));
2129                 }
2130             }
2131
2132             if (y >= 4) { // update mbr array at the end of each stripe
2133                 //generate mbr corresponding to a stripe
2134                 OPJ_UINT32 *sig = y & 0x4 ? sigma1 : sigma2;
2135                 OPJ_UINT32 *mbr = y & 0x4 ? mbr1 : mbr2;
2136
2137                 //data is processed in patches of 8 columns, each
2138                 // each 32 bits in sigma1 or mbr1 represent 4 rows
2139
2140                 //integrate horizontally
2141                 OPJ_UINT32 prev = 0; // previous columns
2142                 OPJ_INT32 i;
2143                 for (i = 0; i < width; i += 8, mbr++, sig++) {
2144                     OPJ_UINT32 t, z;
2145
2146                     mbr[0] = sig[0];         //start with significant samples
2147                     mbr[0] |= prev >> 28;    //for first column, left neighbors
2148                     mbr[0] |= sig[0] << 4;   //left neighbors
2149                     mbr[0] |= sig[0] >> 4;   //right neighbors
2150                     mbr[0] |= sig[1] << 28;  //for last column, right neighbors
2151                     prev = sig[0];           // for next group of columns
2152
2153                     //integrate vertically
2154                     t = mbr[0], z = mbr[0];
2155                     z |= (t & 0x77777777) << 1; //above neighbors
2156                     z |= (t & 0xEEEEEEEE) >> 1; //below neighbors
2157                     mbr[0] = z & ~sig[0]; //remove already significance samples
2158                 }
2159             }
2160
2161             if (y >= 8) { //wait until 8 rows has been processed
2162                 OPJ_UINT32 *cur_sig, *cur_mbr, *nxt_sig, *nxt_mbr;
2163                 OPJ_UINT32 prev;
2164                 OPJ_UINT32 val;
2165                 OPJ_INT32 i;
2166
2167                 // add membership from the next stripe, obtained above
2168                 cur_sig = y & 0x4 ? sigma2 : sigma1;
2169                 cur_mbr = y & 0x4 ? mbr2 : mbr1;
2170                 nxt_sig = y & 0x4 ? sigma1 : sigma2;  //future samples
2171                 prev = 0; // the columns before these group of 8 columns
2172                 for (i = 0; i < width; i += 8, cur_mbr++, cur_sig++, nxt_sig++) {
2173                     OPJ_UINT32 t = nxt_sig[0];
2174                     t |= prev >> 28;        //for first column, left neighbors
2175                     t |= nxt_sig[0] << 4;   //left neighbors
2176                     t |= nxt_sig[0] >> 4;   //right neighbors
2177                     t |= nxt_sig[1] << 28;  //for last column, right neighbors
2178                     prev = nxt_sig[0];      // for next group of columns
2179
2180                     if (!stripe_causal) {
2181                         cur_mbr[0] |= (t & 0x11111111u) << 3; //propagate up to cur_mbr
2182                     }
2183                     cur_mbr[0] &= ~cur_sig[0]; //remove already significance samples
2184                 }
2185
2186                 //find new locations and get signs
2187                 cur_sig = y & 0x4 ? sigma2 : sigma1;
2188                 cur_mbr = y & 0x4 ? mbr2 : mbr1;
2189                 nxt_sig = y & 0x4 ? sigma1 : sigma2; //future samples
2190                 nxt_mbr = y & 0x4 ? mbr1 : mbr2;     //future samples
2191                 val = 3u << (p - 2); // sample values for newly discovered
2192                 // significant samples including the bin center
2193                 for (i = 0; i < width;
2194                         i += 8, cur_sig++, cur_mbr++, nxt_sig++, nxt_mbr++) {
2195                     OPJ_UINT32 ux, tx;
2196                     OPJ_UINT32 mbr = *cur_mbr;
2197                     OPJ_UINT32 new_sig = 0;
2198                     if (mbr) { //are there any samples that might be significant
2199                         OPJ_INT32 n;
2200                         for (n = 0; n < 8; n += 4) {
2201                             OPJ_UINT32 col_mask;
2202                             OPJ_UINT32 inv_sig;
2203                             OPJ_INT32 end;
2204                             OPJ_INT32 j;
2205
2206                             OPJ_UINT32 cwd = frwd_fetch(&sigprop); //get 32 bits
2207                             OPJ_UINT32 cnt = 0;
2208
2209                             OPJ_UINT32 *dp = decoded_data + (y - 8) * stride;
2210                             dp += i + n; //address for decoded samples
2211
2212                             col_mask = 0xFu << (4 * n); //a mask to select a column
2213
2214                             inv_sig = ~cur_sig[0]; // insignificant samples
2215
2216                             //find the last sample we operate on
2217                             end = n + 4 + i < width ? n + 4 : width - i;
2218
2219                             for (j = n; j < end; ++j, ++dp, col_mask <<= 4) {
2220                                 OPJ_UINT32 sample_mask;
2221
2222                                 if ((col_mask & mbr) == 0) { //no samples need checking
2223                                     continue;
2224                                 }
2225
2226                                 //scan mbr to find a new significant sample
2227                                 sample_mask = 0x11111111u & col_mask; // LSB
2228                                 if (mbr & sample_mask) {
2229                                     assert(dp[0] == 0); // the sample must have been 0
2230                                     if (cwd & 1) { //if this sample has become significant
2231                                         // must propagate it to nearby samples
2232                                         OPJ_UINT32 t;
2233                                         new_sig |= sample_mask;  // new significant samples
2234                                         t = 0x32u << (j * 4);// propagation to neighbors
2235                                         mbr |= t & inv_sig; //remove already significant samples
2236                                     }
2237                                     cwd >>= 1;
2238                                     ++cnt; //consume bit and increment number of
2239                                     //consumed bits
2240                                 }
2241
2242                                 sample_mask += sample_mask;  // next row
2243                                 if (mbr & sample_mask) {
2244                                     assert(dp[stride] == 0);
2245                                     if (cwd & 1) {
2246                                         OPJ_UINT32 t;
2247                                         new_sig |= sample_mask;
2248                                         t = 0x74u << (j * 4);
2249                                         mbr |= t & inv_sig;
2250                                     }
2251                                     cwd >>= 1;
2252                                     ++cnt;
2253                                 }
2254
2255                                 sample_mask += sample_mask;
2256                                 if (mbr & sample_mask) {
2257                                     assert(dp[2 * stride] == 0);
2258                                     if (cwd & 1) {
2259                                         OPJ_UINT32 t;
2260                                         new_sig |= sample_mask;
2261                                         t = 0xE8u << (j * 4);
2262                                         mbr |= t & inv_sig;
2263                                     }
2264                                     cwd >>= 1;
2265                                     ++cnt;
2266                                 }
2267
2268                                 sample_mask += sample_mask;
2269                                 if (mbr & sample_mask) {
2270                                     assert(dp[3 * stride] == 0);
2271                                     if (cwd & 1) {
2272                                         OPJ_UINT32 t;
2273                                         new_sig |= sample_mask;
2274                                         t = 0xC0u << (j * 4);
2275                                         mbr |= t & inv_sig;
2276                                     }
2277                                     cwd >>= 1;
2278                                     ++cnt;
2279                                 }
2280                             }
2281
2282                             //obtain signs here
2283                             if (new_sig & (0xFFFFu << (4 * n))) { //if any
2284                                 OPJ_UINT32 col_mask;
2285                                 OPJ_INT32 j;
2286                                 OPJ_UINT32 *dp = decoded_data + (y - 8) * stride;
2287                                 dp += i + n; // decoded samples address
2288                                 col_mask = 0xFu << (4 * n); //mask to select a column
2289
2290                                 for (j = n; j < end; ++j, ++dp, col_mask <<= 4) {
2291                                     OPJ_UINT32 sample_mask;
2292
2293                                     if ((col_mask & new_sig) == 0) { //if non is significant
2294                                         continue;
2295                                     }
2296
2297                                     //scan 4 signs
2298                                     sample_mask = 0x11111111u & col_mask;
2299                                     if (new_sig & sample_mask) {
2300                                         assert(dp[0] == 0);
2301                                         dp[0] |= ((cwd & 1) << 31) | val; //put value and sign
2302                                         cwd >>= 1;
2303                                         ++cnt; //consume bit and increment number
2304                                         //of consumed bits
2305                                     }
2306
2307                                     sample_mask += sample_mask;
2308                                     if (new_sig & sample_mask) {
2309                                         assert(dp[stride] == 0);
2310                                         dp[stride] |= ((cwd & 1) << 31) | val;
2311                                         cwd >>= 1;
2312                                         ++cnt;
2313                                     }
2314
2315                                     sample_mask += sample_mask;
2316                                     if (new_sig & sample_mask) {
2317                                         assert(dp[2 * stride] == 0);
2318                                         dp[2 * stride] |= ((cwd & 1) << 31) | val;
2319                                         cwd >>= 1;
2320                                         ++cnt;
2321                                     }
2322
2323                                     sample_mask += sample_mask;
2324                                     if (new_sig & sample_mask) {
2325                                         assert(dp[3 * stride] == 0);
2326                                         dp[3 * stride] |= ((cwd & 1) << 31) | val;
2327                                         cwd >>= 1;
2328                                         ++cnt;
2329                                     }
2330                                 }
2331
2332                             }
2333                             frwd_advance(&sigprop, cnt); //consume the bits from bitstrm
2334                             cnt = 0;
2335
2336                             //update the next 8 columns
2337                             if (n == 4) {
2338                                 //horizontally
2339                                 OPJ_UINT32 t = new_sig >> 28;
2340                                 t |= ((t & 0xE) >> 1) | ((t & 7) << 1);
2341                                 cur_mbr[1] |= t & ~cur_sig[1];
2342                             }
2343                         }
2344                     }
2345                     //update the next stripe (vertically propagation)
2346                     new_sig |= cur_sig[0];
2347                     ux = (new_sig & 0x88888888) >> 3;
2348                     tx = ux | (ux << 4) | (ux >> 4); //left and right neighbors
2349                     if (i > 0) {
2350                         nxt_mbr[-1] |= (ux << 28) & ~nxt_sig[-1];
2351                     }
2352                     nxt_mbr[0] |= tx & ~nxt_sig[0];
2353                     nxt_mbr[1] |= (ux >> 28) & ~nxt_sig[1];
2354                 }
2355
2356                 //clear current sigma
2357                 //mbr need not be cleared because it is overwritten
2358                 cur_sig = y & 0x4 ? sigma2 : sigma1;
2359                 memset(cur_sig, 0, ((((OPJ_UINT32)width + 7u) >> 3) + 1u) << 2);
2360             }
2361         }
2362     }
2363
2364     //terminating
2365     if (num_passes > 1) {
2366         OPJ_INT32 st, y;
2367
2368         if (num_passes > 2 && ((height & 3) == 1 || (height & 3) == 2)) {
2369             //do magref
2370             OPJ_UINT32 *cur_sig = height & 0x4 ? sigma2 : sigma1; //reversed
2371             OPJ_UINT32 *dpp = decoded_data + (height & 0xFFFFFC) * stride;
2372             OPJ_UINT32 half = 1u << (p - 2);
2373             OPJ_INT32 i;
2374             for (i = 0; i < width; i += 8) {
2375                 OPJ_UINT32 cwd = rev_fetch_mrp(&magref);
2376                 OPJ_UINT32 sig = *cur_sig++;
2377                 OPJ_UINT32 col_mask = 0xF;
2378                 OPJ_UINT32 *dp = dpp + i;
2379                 if (sig) {
2380                     int j;
2381                     for (j = 0; j < 8; ++j, dp++) {
2382                         if (sig & col_mask) {
2383                             OPJ_UINT32 sample_mask = 0x11111111 & col_mask;
2384
2385                             if (sig & sample_mask) {
2386                                 OPJ_UINT32 sym;
2387                                 assert(dp[0] != 0);
2388                                 sym = cwd & 1;
2389                                 dp[0] ^= (1 - sym) << (p - 1);
2390                                 dp[0] |= half;
2391                                 cwd >>= 1;
2392                             }
2393                             sample_mask += sample_mask;
2394
2395                             if (sig & sample_mask) {
2396                                 OPJ_UINT32 sym;
2397                                 assert(dp[stride] != 0);
2398                                 sym = cwd & 1;
2399                                 dp[stride] ^= (1 - sym) << (p - 1);
2400                                 dp[stride] |= half;
2401                                 cwd >>= 1;
2402                             }
2403                             sample_mask += sample_mask;
2404
2405                             if (sig & sample_mask) {
2406                                 OPJ_UINT32 sym;
2407                                 assert(dp[2 * stride] != 0);
2408                                 sym = cwd & 1;
2409                                 dp[2 * stride] ^= (1 - sym) << (p - 1);
2410                                 dp[2 * stride] |= half;
2411                                 cwd >>= 1;
2412                             }
2413                             sample_mask += sample_mask;
2414
2415                             if (sig & sample_mask) {
2416                                 OPJ_UINT32 sym;
2417                                 assert(dp[3 * stride] != 0);
2418                                 sym = cwd & 1;
2419                                 dp[3 * stride] ^= (1 - sym) << (p - 1);
2420                                 dp[3 * stride] |= half;
2421                                 cwd >>= 1;
2422                             }
2423                             sample_mask += sample_mask;
2424                         }
2425                         col_mask <<= 4;
2426                     }
2427                 }
2428                 rev_advance_mrp(&magref, population_count(sig));
2429             }
2430         }
2431
2432         //do the last incomplete stripe
2433         // for cases of (height & 3) == 0 and 3
2434         // the should have been processed previously
2435         if ((height & 3) == 1 || (height & 3) == 2) {
2436             //generate mbr of first stripe
2437             OPJ_UINT32 *sig = height & 0x4 ? sigma2 : sigma1;
2438             OPJ_UINT32 *mbr = height & 0x4 ? mbr2 : mbr1;
2439             //integrate horizontally
2440             OPJ_UINT32 prev = 0;
2441             OPJ_INT32 i;
2442             for (i = 0; i < width; i += 8, mbr++, sig++) {
2443                 OPJ_UINT32 t, z;
2444
2445                 mbr[0] = sig[0];
2446                 mbr[0] |= prev >> 28;    //for first column, left neighbors
2447                 mbr[0] |= sig[0] << 4;   //left neighbors
2448                 mbr[0] |= sig[0] >> 4;   //left neighbors
2449                 mbr[0] |= sig[1] << 28;  //for last column, right neighbors
2450                 prev = sig[0];
2451
2452                 //integrate vertically
2453                 t = mbr[0], z = mbr[0];
2454                 z |= (t & 0x77777777) << 1; //above neighbors
2455                 z |= (t & 0xEEEEEEEE) >> 1; //below neighbors
2456                 mbr[0] = z & ~sig[0]; //remove already significance samples
2457             }
2458         }
2459
2460         st = height;
2461         st -= height > 6 ? (((height + 1) & 3) + 3) : height;
2462         for (y = st; y < height; y += 4) {
2463             OPJ_UINT32 *cur_sig, *cur_mbr, *nxt_sig, *nxt_mbr;
2464             OPJ_UINT32 val;
2465             OPJ_INT32 i;
2466
2467             OPJ_UINT32 pattern = 0xFFFFFFFFu; // a pattern needed samples
2468             if (height - y == 3) {
2469                 pattern = 0x77777777u;
2470             } else if (height - y == 2) {
2471                 pattern = 0x33333333u;
2472             } else if (height - y == 1) {
2473                 pattern = 0x11111111u;
2474             }
2475
2476             //add membership from the next stripe, obtained above
2477             if (height - y > 4) {
2478                 OPJ_UINT32 prev = 0;
2479                 OPJ_INT32 i;
2480                 cur_sig = y & 0x4 ? sigma2 : sigma1;
2481                 cur_mbr = y & 0x4 ? mbr2 : mbr1;
2482                 nxt_sig = y & 0x4 ? sigma1 : sigma2;
2483                 for (i = 0; i < width; i += 8, cur_mbr++, cur_sig++, nxt_sig++) {
2484                     OPJ_UINT32 t = nxt_sig[0];
2485                     t |= prev >> 28;     //for first column, left neighbors
2486                     t |= nxt_sig[0] << 4;   //left neighbors
2487                     t |= nxt_sig[0] >> 4;   //left neighbors
2488                     t |= nxt_sig[1] << 28;  //for last column, right neighbors
2489                     prev = nxt_sig[0];
2490
2491                     if (!stripe_causal) {
2492                         cur_mbr[0] |= (t & 0x11111111u) << 3;
2493                     }
2494                     //remove already significance samples
2495                     cur_mbr[0] &= ~cur_sig[0];
2496                 }
2497             }
2498
2499             //find new locations and get signs
2500             cur_sig = y & 0x4 ? sigma2 : sigma1;
2501             cur_mbr = y & 0x4 ? mbr2 : mbr1;
2502             nxt_sig = y & 0x4 ? sigma1 : sigma2;
2503             nxt_mbr = y & 0x4 ? mbr1 : mbr2;
2504             val = 3u << (p - 2);
2505             for (i = 0; i < width; i += 8,
2506                     cur_sig++, cur_mbr++, nxt_sig++, nxt_mbr++) {
2507                 OPJ_UINT32 mbr = *cur_mbr & pattern; //skip unneeded samples
2508                 OPJ_UINT32 new_sig = 0;
2509                 OPJ_UINT32 ux, tx;
2510                 if (mbr) {
2511                     OPJ_INT32 n;
2512                     for (n = 0; n < 8; n += 4) {
2513                         OPJ_UINT32 col_mask;
2514                         OPJ_UINT32 inv_sig;
2515                         OPJ_INT32 end;
2516                         OPJ_INT32 j;
2517
2518                         OPJ_UINT32 cwd = frwd_fetch(&sigprop);
2519                         OPJ_UINT32 cnt = 0;
2520
2521                         OPJ_UINT32 *dp = decoded_data + y * stride;
2522                         dp += i + n;
2523
2524                         col_mask = 0xFu << (4 * n);
2525
2526                         inv_sig = ~cur_sig[0] & pattern;
2527
2528                         end = n + 4 + i < width ? n + 4 : width - i;
2529                         for (j = n; j < end; ++j, ++dp, col_mask <<= 4) {
2530                             OPJ_UINT32 sample_mask;
2531
2532                             if ((col_mask & mbr) == 0) {
2533                                 continue;
2534                             }
2535
2536                             //scan 4 mbr
2537                             sample_mask = 0x11111111u & col_mask;
2538                             if (mbr & sample_mask) {
2539                                 assert(dp[0] == 0);
2540                                 if (cwd & 1) {
2541                                     OPJ_UINT32 t;
2542                                     new_sig |= sample_mask;
2543                                     t = 0x32u << (j * 4);
2544                                     mbr |= t & inv_sig;
2545                                 }
2546                                 cwd >>= 1;
2547                                 ++cnt;
2548                             }
2549
2550                             sample_mask += sample_mask;
2551                             if (mbr & sample_mask) {
2552                                 assert(dp[stride] == 0);
2553                                 if (cwd & 1) {
2554                                     OPJ_UINT32 t;
2555                                     new_sig |= sample_mask;
2556                                     t = 0x74u << (j * 4);
2557                                     mbr |= t & inv_sig;
2558                                 }
2559                                 cwd >>= 1;
2560                                 ++cnt;
2561                             }
2562
2563                             sample_mask += sample_mask;
2564                             if (mbr & sample_mask) {
2565                                 assert(dp[2 * stride] == 0);
2566                                 if (cwd & 1) {
2567                                     OPJ_UINT32 t;
2568                                     new_sig |= sample_mask;
2569                                     t = 0xE8u << (j * 4);
2570                                     mbr |= t & inv_sig;
2571                                 }
2572                                 cwd >>= 1;
2573                                 ++cnt;
2574                             }
2575
2576                             sample_mask += sample_mask;
2577                             if (mbr & sample_mask) {
2578                                 assert(dp[3 * stride] == 0);
2579                                 if (cwd & 1) {
2580                                     OPJ_UINT32 t;
2581                                     new_sig |= sample_mask;
2582                                     t = 0xC0u << (j * 4);
2583                                     mbr |= t & inv_sig;
2584                                 }
2585                                 cwd >>= 1;
2586                                 ++cnt;
2587                             }
2588                         }
2589
2590                         //signs here
2591                         if (new_sig & (0xFFFFu << (4 * n))) {
2592                             OPJ_UINT32 col_mask;
2593                             OPJ_INT32 j;
2594                             OPJ_UINT32 *dp = decoded_data + y * stride;
2595                             dp += i + n;
2596                             col_mask = 0xFu << (4 * n);
2597
2598                             for (j = n; j < end; ++j, ++dp, col_mask <<= 4) {
2599                                 OPJ_UINT32 sample_mask;
2600                                 if ((col_mask & new_sig) == 0) {
2601                                     continue;
2602                                 }
2603
2604                                 //scan 4 signs
2605                                 sample_mask = 0x11111111u & col_mask;
2606                                 if (new_sig & sample_mask) {
2607                                     assert(dp[0] == 0);
2608                                     dp[0] |= ((cwd & 1) << 31) | val;
2609                                     cwd >>= 1;
2610                                     ++cnt;
2611                                 }
2612
2613                                 sample_mask += sample_mask;
2614                                 if (new_sig & sample_mask) {
2615                                     assert(dp[stride] == 0);
2616                                     dp[stride] |= ((cwd & 1) << 31) | val;
2617                                     cwd >>= 1;
2618                                     ++cnt;
2619                                 }
2620
2621                                 sample_mask += sample_mask;
2622                                 if (new_sig & sample_mask) {
2623                                     assert(dp[2 * stride] == 0);
2624                                     dp[2 * stride] |= ((cwd & 1) << 31) | val;
2625                                     cwd >>= 1;
2626                                     ++cnt;
2627                                 }
2628
2629                                 sample_mask += sample_mask;
2630                                 if (new_sig & sample_mask) {
2631                                     assert(dp[3 * stride] == 0);
2632                                     dp[3 * stride] |= ((cwd & 1) << 31) | val;
2633                                     cwd >>= 1;
2634                                     ++cnt;
2635                                 }
2636                             }
2637
2638                         }
2639                         frwd_advance(&sigprop, cnt);
2640                         cnt = 0;
2641
2642                         //update next columns
2643                         if (n == 4) {
2644                             //horizontally
2645                             OPJ_UINT32 t = new_sig >> 28;
2646                             t |= ((t & 0xE) >> 1) | ((t & 7) << 1);
2647                             cur_mbr[1] |= t & ~cur_sig[1];
2648                         }
2649                     }
2650                 }
2651                 //propagate down (vertically propagation)
2652                 new_sig |= cur_sig[0];
2653                 ux = (new_sig & 0x88888888) >> 3;
2654                 tx = ux | (ux << 4) | (ux >> 4);
2655                 if (i > 0) {
2656                     nxt_mbr[-1] |= (ux << 28) & ~nxt_sig[-1];
2657                 }
2658                 nxt_mbr[0] |= tx & ~nxt_sig[0];
2659                 nxt_mbr[1] |= (ux >> 28) & ~nxt_sig[1];
2660             }
2661         }
2662     }
2663
2664     {
2665         OPJ_INT32 x, y;
2666         for (y = 0; y < height; ++y) {
2667             OPJ_INT32* sp = (OPJ_INT32*)decoded_data + y * stride;
2668             for (x = 0; x < width; ++x, ++sp) {
2669                 OPJ_INT32 val = (*sp & 0x7FFFFFFF);
2670                 *sp = ((OPJ_UINT32) * sp & 0x80000000) ? -val : val;
2671             }
2672         }
2673     }
2674
2675     return OPJ_TRUE;
2676 }