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 int D; 76 const JBig2ArithQe * qe = &QeTable[pCX->I]; 77 A = A - qe->Qe; 78 if((C >> 16) < A) { 79 if(A & 0x8000) { 80 D = pCX->MPS; 81 } else { 82 if(A < qe->Qe) { 83 D = 1 - pCX->MPS; 84 if(qe->nSwitch == 1) { 85 pCX->MPS = 1 - pCX->MPS; 86 } 87 pCX->I = qe->NLPS; 88 } else { 89 D = pCX->MPS; 90 pCX->I = qe->NMPS; 91 } 92 do { 93 if (CT == 0) { 94 BYTEIN(); 95 } 96 A <<= 1; 97 C <<= 1; 98 CT--; 99 } while ((A & 0x8000) == 0); 100 } 101 } else { 102 C -= A << 16; 103 if(A < qe->Qe) { 104 A = qe->Qe; 105 D = pCX->MPS; 106 pCX->I = qe->NMPS; 107 } else { 108 A = qe->Qe; 109 D = 1 - pCX->MPS; 110 if(qe->nSwitch == 1) { 111 pCX->MPS = 1 - pCX->MPS; 112 } 113 pCX->I = qe->NLPS; 114 } 115 do { 116 if (CT == 0) { 117 BYTEIN(); 118 } 119 A <<= 1; 120 C <<= 1; 121 CT--; 122 } while ((A & 0x8000) == 0); 123 } 124 return D; 125 } 126 #endif 127