• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "core/fxcodec/jbig2/JBig2_HuffmanDecoder.h"
8 
9 #include "core/fxcodec/jbig2/JBig2_Define.h"
10 #include "core/fxcrt/fx_safe_types.h"
11 
CJBig2_HuffmanDecoder(CJBig2_BitStream * pStream)12 CJBig2_HuffmanDecoder::CJBig2_HuffmanDecoder(CJBig2_BitStream* pStream)
13     : m_pStream(pStream) {}
14 
~CJBig2_HuffmanDecoder()15 CJBig2_HuffmanDecoder::~CJBig2_HuffmanDecoder() {}
16 
DecodeAValue(const CJBig2_HuffmanTable * pTable,int * nResult)17 int CJBig2_HuffmanDecoder::DecodeAValue(const CJBig2_HuffmanTable* pTable,
18                                         int* nResult) {
19   FX_SAFE_INT32 nSafeVal = 0;
20   int nBits = 0;
21   while (1) {
22     uint32_t nTmp;
23     if (m_pStream->read1Bit(&nTmp) == -1)
24       break;
25 
26     nSafeVal <<= 1;
27     if (!nSafeVal.IsValid())
28       break;
29 
30     nSafeVal |= nTmp;
31     ++nBits;
32     const int32_t nVal = nSafeVal.ValueOrDie();
33     for (uint32_t i = 0; i < pTable->Size(); ++i) {
34       const JBig2HuffmanCode& code = pTable->GetCODES()[i];
35       if (code.codelen != nBits || code.code != nVal)
36         continue;
37 
38       if (pTable->IsHTOOB() && i == pTable->Size() - 1)
39         return JBIG2_OOB;
40 
41       if (m_pStream->readNBits(pTable->GetRANGELEN()[i], &nTmp) == -1)
42         return -1;
43 
44       uint32_t offset = pTable->IsHTOOB() ? 3 : 2;
45       if (i == pTable->Size() - offset)
46         *nResult = pTable->GetRANGELOW()[i] - nTmp;
47       else
48         *nResult = pTable->GetRANGELOW()[i] + nTmp;
49       return 0;
50     }
51   }
52   return -1;
53 }
54