1 // Copyright 2014 PDFium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com 6 7 #ifndef _JBIG2_ARITHMETIC_DECODER_H_ 8 #define _JBIG2_ARITHMETIC_DECODER_H_ 9 #include "JBig2_Define.h" 10 #include "JBig2_BitStream.h" 11 #include "JBig2_ArithQe.h" 12 typedef struct { 13 unsigned int MPS; 14 unsigned int I; 15 } JBig2ArithCtx; 16 class CJBig2_ArithDecoder : public CJBig2_Object 17 { 18 public: 19 20 CJBig2_ArithDecoder(CJBig2_BitStream *pStream); 21 22 ~CJBig2_ArithDecoder(); 23 24 int DECODE(JBig2ArithCtx *pCX); 25 private: 26 27 void INITDEC(); 28 29 void BYTEIN(); 30 unsigned char B; 31 unsigned int C; 32 unsigned int A; 33 unsigned int CT; 34 CJBig2_BitStream *m_pStream; 35 }; CJBig2_ArithDecoder(CJBig2_BitStream * pStream)36inline CJBig2_ArithDecoder::CJBig2_ArithDecoder(CJBig2_BitStream *pStream) 37 { 38 m_pStream = pStream; 39 INITDEC(); 40 } ~CJBig2_ArithDecoder()41inline CJBig2_ArithDecoder::~CJBig2_ArithDecoder() 42 { 43 } INITDEC()44inline void CJBig2_ArithDecoder::INITDEC() 45 { 46 B = m_pStream->getCurByte_arith(); 47 C = (B ^ 0xff) << 16;; 48 BYTEIN(); 49 C = C << 7; 50 CT = CT - 7; 51 A = 0x8000; 52 } BYTEIN()53inline void CJBig2_ArithDecoder::BYTEIN() 54 { 55 unsigned char B1; 56 if(B == 0xff) { 57 B1 = m_pStream->getNextByte_arith(); 58 if(B1 > 0x8f) { 59 CT = 8; 60 } else { 61 m_pStream->incByteIdx(); 62 B = B1; 63 C = C + 0xfe00 - (B << 9); 64 CT = 7; 65 } 66 } else { 67 m_pStream->incByteIdx(); 68 B = m_pStream->getCurByte_arith(); 69 C = C + 0xff00 - (B << 8); 70 CT = 8; 71 } 72 } DECODE(JBig2ArithCtx * pCX)73inline int CJBig2_ArithDecoder::DECODE(JBig2ArithCtx *pCX) 74 { 75 if (!pCX || pCX->I >= JBIG2_QE_NUM) { 76 return 0; 77 } 78 79 int D; 80 const JBig2ArithQe * qe = &QeTable[pCX->I]; 81 A = A - qe->Qe; 82 if((C >> 16) < A) { 83 if(A & 0x8000) { 84 D = pCX->MPS; 85 } else { 86 if(A < qe->Qe) { 87 D = 1 - pCX->MPS; 88 if(qe->nSwitch == 1) { 89 pCX->MPS = 1 - pCX->MPS; 90 } 91 pCX->I = qe->NLPS; 92 } else { 93 D = pCX->MPS; 94 pCX->I = qe->NMPS; 95 } 96 do { 97 if (CT == 0) { 98 BYTEIN(); 99 } 100 A <<= 1; 101 C <<= 1; 102 CT--; 103 } while ((A & 0x8000) == 0); 104 } 105 } else { 106 C -= A << 16; 107 if(A < qe->Qe) { 108 A = qe->Qe; 109 D = pCX->MPS; 110 pCX->I = qe->NMPS; 111 } else { 112 A = qe->Qe; 113 D = 1 - pCX->MPS; 114 if(qe->nSwitch == 1) { 115 pCX->MPS = 1 - pCX->MPS; 116 } 117 pCX->I = qe->NLPS; 118 } 119 do { 120 if (CT == 0) { 121 BYTEIN(); 122 } 123 A <<= 1; 124 C <<= 1; 125 CT--; 126 } while ((A & 0x8000) == 0); 127 } 128 return D; 129 } 130 #endif 131