Beispiel #1
0
HRESULT CCoder::ReadPTable(int numBits)
{
  int n = ReadBits(numBits);
  if (n == 0)
  {
    m_PHuffmanDecoder.Symbol = ReadBits(numBits);
    if (m_PHuffmanDecoder.Symbol >= kNumDistanceSymbols)
      return S_FALSE;
  }
  else
  {
    if (n > kNumDistanceSymbols)
      return S_FALSE;
    m_PHuffmanDecoder.Symbol = -1;
    Byte lens[kNumDistanceSymbols];
    int i = 0;
    while (i < n)
    {
      int c = m_InBitStream.ReadBits(3);
      if (c == 7)
        while (ReadBits(1))
        {
          if (c > kMaxHuffmanLen)
            return S_FALSE;
          c++;
        }
      lens[i++] = (Byte)c;
    }
    while (i < kNumDistanceSymbols)
      lens[i++] = 0;
    m_PHuffmanDecoder.SetCodeLengths(lens);
  }
  return S_OK;
}
Beispiel #2
0
bool CDecoder::ReadTables(void)
{
  Byte newLevels[kMaxTableSize];
  {
    if (_skipByte)
      m_InBitStream.DirectReadByte();
    m_InBitStream.Normalize();

    int blockType = (int)ReadBits(kNumBlockTypeBits);
    if (blockType > kBlockTypeUncompressed)
      return false;
    if (_wimMode)
      if (ReadBits(1) == 1)
        m_UnCompressedBlockSize = (1 << 15);
      else
        m_UnCompressedBlockSize = ReadBits(16);
    else
      m_UnCompressedBlockSize = m_InBitStream.ReadBitsBig(kUncompressedBlockSizeNumBits);

    m_IsUncompressedBlock = (blockType == kBlockTypeUncompressed);

    _skipByte = (m_IsUncompressedBlock && ((m_UnCompressedBlockSize & 1) != 0));

    if (m_IsUncompressedBlock)
    {
      ReadBits(16 - m_InBitStream.GetBitPosition());
      if (!m_InBitStream.ReadUInt32(m_RepDistances[0]))
        return false;
      m_RepDistances[0]--;
      for (int i = 1; i < kNumRepDistances; i++)
      {
        UInt32 rep = 0;
        for (int j = 0; j < 4; j++)
          rep |= (UInt32)m_InBitStream.DirectReadByte() << (8 * j);
        m_RepDistances[i] = rep - 1;
      }
      return true;
    }
    m_AlignIsUsed = (blockType == kBlockTypeAligned);
    if (m_AlignIsUsed)
    {
      for(int i = 0; i < kAlignTableSize; i++)
        newLevels[i] = (Byte)ReadBits(kNumBitsForAlignLevel);
      RIF(m_AlignDecoder.SetCodeLengths(newLevels));
    }
  }

  RIF(ReadTable(m_LastMainLevels, newLevels, 256));
  RIF(ReadTable(m_LastMainLevels + 256, newLevels + 256, m_NumPosLenSlots));
  for (UInt32 i = 256 + m_NumPosLenSlots; i < kMainTableSize; i++)
    newLevels[i] = 0;
  RIF(m_MainDecoder.SetCodeLengths(newLevels));

  RIF(ReadTable(m_LastLenLevels, newLevels, kNumLenSymbols));
  return m_LenDecoder.SetCodeLengths(newLevels);
}
Beispiel #3
0
Soy264::TError::Type Soy264::TNalPacket::InitHeader()
{
	int ForbiddenZero = ReadBits(1);
	int RefIDC = ReadBits(2);
	int UnitType = ReadBits(5);
	//nalu->last_rbsp_byte=&nal_buf[nalu_size-1];

	mHeader.mType = TNalUnitType::GetType( UnitType );

	return TError::Success;
}
uint16 PanelDataRead(StdAirDataBase *DataBase, uint16 index)
{
   uint08 tmptype =   PanelDataStr[index][0];
   uint08 tmpindex = PanelDataStr[index][1];

   if (tmpindex == DEF_INDEX)
   {
      return (0);
   }
   //对齐
   tmpindex--;
   if (tmptype == BITTYPE)
   {
      if (tmpindex < BIT_LEN_MAX)
      {
         return (ReadBits(DataBase->Solo.Bits.All, tmpindex));
      }
   }
   if (tmptype == BYTETYPE)
   {
      if (tmpindex < BYTE_LEN_MAX)
      {
         return DataBase->Solo.Bytes.All[tmpindex];
      }
   }
   if (tmptype == WORDTYPE)
   {
      if (tmpindex < WORD_LEN_MAX)
      {
         return DataBase->Solo.Words.All[tmpindex];
      }
   }
   return (0);
}
Beispiel #5
0
XBOOL XStream::ReadBits(XS32&data,XU8 size)
{
	if(!ReadBits((XU32&)data,size)) return XFALSE;
	XU32 sign=data&(1<<(size-1));
	if(sign!=0)
	{
		data|=((0xffffffff>>size)<<size);
	}
Beispiel #6
0
void         LoadFollowers(void)
   { 
      int      x;
      int      i;
      int      b;

      for (x = 255; x >= 0; x--) 
      { 
         ReadBits(6,&b); 
         Slen[x] = b;

         for (i = 0; i < Slen[x]; i++)
         { 
            ReadBits(8,&b); 
            followers[x][i] = b;
         } 
      } 
   } 
Beispiel #7
0
HRESULT CCoder::ReadCTable()
{
  int n = ReadBits(kNumCBits);
  if (n == 0)
  {
    m_CHuffmanDecoder.Symbol = ReadBits(kNumCBits);
    if (m_CHuffmanDecoder.Symbol >= kNumCSymbols)
      return S_FALSE;
  }
  else
  {
    if (n > kNumCSymbols)
      return S_FALSE;
    m_CHuffmanDecoder.Symbol = -1;
    Byte lens[kNumCSymbols];
    int i = 0;
    while (i < n)
    {
      int c = m_LevelHuffman.Decode(&m_InBitStream);
      if (c < kNumSpecLevelSymbols)
      {
        if (c == 0)
          c = 1;
        else if (c == 1)
          c = ReadBits(4) + 3;
        else
          c = ReadBits(kNumCBits) + 20;
        while (--c >= 0)
        {
          if (i > kNumCSymbols)
            return S_FALSE;
          lens[i++] = 0;
        }
      }
      else
        lens[i++] = (Byte)(c - 2);
    }
    while (i < kNumCSymbols)
      lens[i++] = 0;
    m_CHuffmanDecoder.SetCodeLengths(lens);
  }
  return S_OK;
}
Beispiel #8
0
void         unReduce(void)
     /* expand probablisticly reduced data */ 

   { 

   int    lchar;
   int    lout;
   int    I;

   factor = cmethod - 1; 
   if ((factor < 1) || (factor > 4)) 
   { 
      skip_csize(); 
      return;
   } 

   ExState = 0; 
   LoadFollowers(); 
   lchar =  0;

   while ((!zipeof) && (outpos < cusize))
   { 

      if (Slen[lchar] == 0)
         ReadBits(8,&lout);
      else 

      { 
         ReadBits(1,&lout); 
         if (lout != 0) 
            ReadBits(8,&lout);
         else 
         { 
            ReadBits(reduce_B(Slen[lchar]),&I);
            lout = followers[lchar][I];
         } 
      } 

      Expand(lout); 
      lchar = lout; 
   } 
} 
Beispiel #9
0
uint32_t HuffmanDec::BitStream::ReadBitsChecked(int bits) {
  // Check that we don't read past the end.
  int new_bit_pos = m_bit_pos + bits;
  const uint8_t *new_byte_ptr = m_byte_ptr + (new_bit_pos >> 3);
  if (UNLIKELY(new_byte_ptr > m_end_ptr ||
               (new_byte_ptr == m_end_ptr && ((new_bit_pos & 7) > 0)))) {
    m_read_failed = true;
    return 0;
  }

  // Ok, read...
  return ReadBits(bits);
}
Beispiel #10
0
HRESULT CCoder::ReadLevelTable()
{
  int n = ReadBits(kNumLevelBits);
  if (n == 0)
  {
    m_LevelHuffman.Symbol = ReadBits(kNumLevelBits);
    if (m_LevelHuffman.Symbol >= kNumLevelSymbols)
      return S_FALSE;
  }
  else
  {
    if (n > kNumLevelSymbols)
      return S_FALSE;
    m_LevelHuffman.Symbol = -1;
    Byte lens[kNumLevelSymbols];
    int i = 0;
    while (i < n)
    {
      int c = m_InBitStream.ReadBits(3);
      if (c == 7)
        while (ReadBits(1))
          if (c++ > kMaxHuffmanLen)
            return S_FALSE;
      lens[i++] = (Byte)c;
      if (i == kNumSpecLevelSymbols)
      {
        c = ReadBits(2);
        while (--c >= 0)
          lens[i++] = 0;
      }
    }
    while (i < kNumLevelSymbols)
      lens[i++] = 0;
    m_LevelHuffman.SetCodeLengths(lens);
  }
  return S_OK;
}
Beispiel #11
0
void ExpandFile ( BFILE *input, FILE *output)
{
	int i;
	int current_pos;
	int c;
	int match_len;
	int match_pos;
	
	current_pos = 1;
	
	for (;;)
	{
		if (ReadBit (input))
		{
			c = (int) ReadBits ( input, 8);
			putc ( c, output);
			window [current_pos] = (uchar) c;
			current_pos = MODULO (current_pos + 1);
		}
		else
		{
			match_pos = (int) ReadBits ( input, INDEX_BITS);
			if (match_pos == END_OF_STREAM)
				break;
			match_len = (int) ReadBits ( input, LENGTH_BITS);
			match_len += BREAK_EVEN;
			for ( i = 0; i <= match_len; i++)
			{
				c = window [MODULO (match_pos + i)];
				putc ( c, output);
				window [current_pos] = (uchar) c;
				current_pos = MODULO (current_pos + 1);
			}
		}
	}
}
OSCL_EXPORT_REF uint8 BitStreamParser::ReadUInt8(void)
{
    //If bitpos is not on a byte boundary, have to use ReadBits...
    if (bitpos != MOST_SIG_BIT) return ReadBits(BITS_PER_UINT8);

    // Make sure the current bytepos doesn't exceed the size of the buffer
    if (bytepos >= (start + size))
    {
        OSCL_LEAVE(OsclErrOverflow);
    }
    uint8 read = *bytepos;
    bytepos++;

    return read;
}
Beispiel #13
0
  // Read unsigned integer Exp-Golomb-coded.
  uint32_t ReadUE()
  {
    uint32_t i = 0;

    while (ReadBit() == 0 && i < 32) {
      i++;
    }
    if (i == 32) {
      MOZ_ASSERT(false);
      return 0;
    }
    uint32_t r = ReadBits(i);
    r += (1 << i) - 1;
    return r;
  }
/*
========================
idLZWCompressor::DecompressBlock
========================
*/
void idLZWCompressor::DecompressBlock()
{
	assert( blockIndex == blockSize );		// Make sure we've read all we can
	
	blockIndex = 0;
	blockSize = 0;
	
	int firstChar = -1;
	while( blockSize < LZW_BLOCK_SIZE - lzwCompressionData_t::LZW_DICT_SIZE )
	{
		assert( lzwData->codeBits <= lzwCompressionData_t::LZW_DICT_BITS );
		
		int code = ReadBits( lzwData->codeBits );
		if( code == -1 )
		{
			break;
		}
		
		if( oldCode == -1 )
		{
			assert( code < 256 );
			block[blockSize++] = ( uint8 )code;
			oldCode = code;
			firstChar = code;
			continue;
		}
		
		if( code >= lzwData->nextCode )
		{
			assert( code == lzwData->nextCode );
			firstChar = WriteChain( oldCode );
			block[blockSize++] = ( uint8 )firstChar;
		}
		else
		{
			firstChar = WriteChain( code );
		}
		AddToDict( oldCode, firstChar );
		if( BumpBits() )
		{
			oldCode = -1;
		}
		else
		{
			oldCode = code;
		}
	}
}
Beispiel #15
0
  // Read unsigned integer Exp-Golomb-coded.
  uint32_t ReadUE()
  {
    uint32_t i = 0;

    while (ReadBit() == 0 && i < 32) {
      i++;
    }
    if (i == 32) {
      // This can happen if the data is invalid, or if it's
      // short, since ReadBit() will return 0 when it runs
      // off the end of the buffer.
      NS_WARNING("Invalid H.264 data");
      return 0;
    }
    uint32_t r = ReadBits(i);
    r += (1 << i) - 1;
    return r;
  }
Beispiel #16
0
int main(int argc, char* argv[]) {
	printf("Example1: BitIO\n");

#ifdef OnOSX
	signal(SIGINT, Quit);		// Trap Control+C function Quit on Mac
#endif

	if (!InitializeForBitIO()) {
		printf("\nFT232R cable found\nLED is ");
		while (1) {
			WriteBits(LED_Off);
			printf("Off\b\b\b");
			Idle(10);
			while (ReadBits() & Button) {
				WriteBits(LED_On);
				printf("On \b\b\b");
				Idle(10);
				}
			}
		}
	Quit();
	}
Beispiel #17
0
static int
appendBitstream( HANDLE_BIT_BUF hBitBufWrite,
                 HANDLE_BIT_BUF hBitBufRead,
                 int nBits )
{
  int i;
  unsigned b;

  COUNT_sub_start("appendBitstream");

  LOOP(1);
  for (i=0; i< nBits; i++)
  {
    FUNC(2);
    b = ReadBits (hBitBufRead, 1);

    FUNC(3);
    WriteBits (hBitBufWrite, b, 1);
  }

  COUNT_sub_end();

  return nBits;
}
void FFRaacplus_checkForPayload(HANDLE_BIT_BUF bs,
                                SBRBITSTREAM *streamSBR,
                                int prev_element)
{
  int i;
  int count=0;
  int esc_count=0;

  FLC_sub_start("FFRaacplus_checkForPayload");

  MOVE(2); /* counting previous operations */


  FUNC(2);
  count = ReadBits(bs,4);

  ADD(1); BRANCH(1);
  if (count == 15)
  {
    FUNC(2);
    esc_count = ReadBits(bs,8);

    ADD(1);
    count =  esc_count + 14;
  }

  BRANCH(1);
  if (count)
  {
     unsigned char extension_type;

    FUNC(2);
    extension_type = (unsigned char) ReadBits(bs,4);


    ADD(8); LOGIC(7); BRANCH(1);
    if (   (prev_element == SBR_ID_SCE || prev_element == SBR_ID_CPE)
        && ((extension_type == SBR_EXTENSION) || (extension_type == SBR_EXTENSION_CRC) || (extension_type == SBR_EXTENSION_MPEG) || (extension_type == SBR_EXTENSION_CRC_MPEG))
        && (count < MAXSBRBYTES) && (streamSBR->NrElements < MAXNRELEMENTS)    )
    {
      FUNC(2); INDIRECT(1); STORE(1);
      streamSBR->sbrElement [streamSBR->NrElements].Data[0] = (unsigned char) ReadBits(bs,4);

      PTR_INIT(1); /* streamSBR->sbrElement [streamSBR->NrElements].Data[i] */
      LOOP(1);
      for (i=1; i<count; i++)
      {
        FUNC(2); STORE(1);
        streamSBR->sbrElement [streamSBR->NrElements].Data[i] = (unsigned char) ReadBits(bs,8);
      }

      MOVE(2);
      streamSBR->sbrElement[streamSBR->NrElements].ExtensionType = extension_type;
      streamSBR->sbrElement[streamSBR->NrElements].Payload = count;

      ADD(1); INDIRECT(1); STORE(1);
      streamSBR->NrElements += 1;
    }
    else
    {
      FUNC(2);
      ReadBits(bs,4);

      LOOP(1);
      for (i=1; i<count; i++)
      {
        FUNC(2);
        ReadBits(bs,8);
      }
    }
  }

  FLC_sub_end();
}
// name: iDecodeVOLHeader
// Purpose: decode VOL header
// return:  error code
OSCL_EXPORT_REF int16 iDecodeVOLHeader(mp4StreamType *psBits, int32 *width, int32 *height, int32 *display_width, int32 *display_height, int32 *profilelevel, uint32 *interlaced)
{
    int16 iErrorStat;
    uint32 codeword;
    int32 time_increment_resolution, nbits_time_increment;
    int32 i, j;

    *profilelevel = 0x0000FFFF; // init to some invalid value. When this value is returned, then no profilelevel info is available

    ShowBits(psBits, 32, &codeword);

    if (codeword == VISUAL_OBJECT_SEQUENCE_START_CODE)
    {
        //DV: this is the wrong way to skip bits, use FLush or Read psBits->dataBitPos += 32;
        ReadBits(psBits, 32, &codeword); // skip 32 bits of the Start code

        ReadBits(psBits, 8, &codeword);

        // record profile and level
        *profilelevel = (int) codeword;

        ShowBits(psBits, 32, &codeword);
        if (codeword == USER_DATA_START_CODE)
        {
            iErrorStat = DecodeUserData(psBits);
            if (iErrorStat) return MP4_INVALID_VOL_PARAM;
        }


        ReadBits(psBits, 32, &codeword);
        if (codeword != VISUAL_OBJECT_START_CODE) return MP4_INVALID_VOL_PARAM;

        /*  is_visual_object_identifier            */
        ReadBits(psBits, 1, &codeword);

        if (codeword)
        {
            /* visual_object_verid                            */
            ReadBits(psBits, 4, &codeword);
            /* visual_object_priority                         */
            ReadBits(psBits, 3, &codeword);
        }
        /* visual_object_type                                 */
        ReadBits(psBits, 4, &codeword);

        if (codeword == 1)
        {   /* video_signal_type */
            ReadBits(psBits, 1, &codeword);
            if (codeword == 1)
            {
                /* video_format */
                ReadBits(psBits, 3, &codeword);
                /* video_range  */
                ReadBits(psBits, 1, &codeword);
                /* color_description */
                ReadBits(psBits, 1, &codeword);
                if (codeword == 1)
                {
                    /* color_primaries */
                    ReadBits(psBits, 8, &codeword);;
                    /* transfer_characteristics */
                    ReadBits(psBits, 8, &codeword);
                    /* matrix_coefficients */
                    ReadBits(psBits, 8, &codeword);
                }
            }
        }
        else
        {
            int16 status = 0;
            do
            {
                /* Search for VOL_HEADER */
                status = SearchNextM4VFrame(psBits); /* search 0x00 0x00 0x01 */
                if (status != 0)
                    return MP4_INVALID_VOL_PARAM;

                status = ReadBits(psBits, VOL_START_CODE_LENGTH, &codeword);
            }
            while ((codeword != VOL_START_CODE) && (status == 0));
            goto decode_vol;
        }
        /* next_start_code() */
        ByteAlign(psBits);

        ShowBits(psBits, 32, &codeword);
        if (codeword == USER_DATA_START_CODE)
        {
            iErrorStat = DecodeUserData(psBits);
            if (iErrorStat) return MP4_INVALID_VOL_PARAM;
        }
        ShowBits(psBits, 27, &codeword);
    }
    else
    {
        ShowBits(psBits, 27, &codeword);
    }

    if (codeword == VO_START_CODE)
    {

        ReadBits(psBits, 32, &codeword);

        /* video_object_layer_start_code                   */
        ReadBits(psBits, 28, &codeword);
        if (codeword != VOL_START_CODE)
        {
            if (psBits->dataBitPos >= (psBits->numBytes << 3))
            {
                return SHORT_HEADER_MODE; /* SH */
            }
            else
            {
                int16 status = 0;
                do
                {
                    /* Search for VOL_HEADER */
                    status = SearchNextM4VFrame(psBits); /* search 0x00 0x00 0x01 */
                    if (status != 0)
                        return MP4_INVALID_VOL_PARAM;

                    status = ReadBits(psBits, VOL_START_CODE_LENGTH, &codeword);
                }
                while ((codeword != VOL_START_CODE) && (status == 0));
                goto decode_vol;
            }
        }
decode_vol:

        uint32 vol_id;

        /* vol_id (4 bits) */
        ReadBits(psBits, 4, & vol_id);

        // RandomAccessibleVOLFlag
        ReadBits(psBits, 1, &codeword);

        //Video Object Type Indication
        ReadBits(psBits, 8, &codeword);
        if (codeword != 1)
        {
            //return MP4_INVALID_VOL_PARAM; //TI supports this feature
        }

        // is_object_layer_identifier
        ReadBits(psBits, 1, &codeword);

        if (codeword)
        {
            ReadBits(psBits, 4, &codeword);
            ReadBits(psBits, 3, &codeword);
        }

        // aspect ratio
        ReadBits(psBits, 4, &codeword);

        if (codeword == 0xF)
        {
            // Extended Parameter
            /* width */
            ReadBits(psBits, 8, &codeword);
            /* height */
            ReadBits(psBits, 8, &codeword);
        }

        ReadBits(psBits, 1, &codeword);

        if (codeword)
        {
            ReadBits(psBits, 2, &codeword);
            if (codeword != 1)
            {
                return MP4_INVALID_VOL_PARAM;
            }

            ReadBits(psBits, 1, &codeword);

            if (!codeword)
            {
                //return MP4_INVALID_VOL_PARAM; //TI supports this feature
            }

            ReadBits(psBits, 1, &codeword);
            if (codeword)   /* if (vbv_parameters) {}, page 36 */
            {
                ReadBits(psBits, 15, &codeword);
                ReadBits(psBits, 1, &codeword);
                if (codeword != 1)
                {
                    return MP4_INVALID_VOL_PARAM;
                }

                ReadBits(psBits, 15, &codeword);
                ReadBits(psBits, 1, &codeword);
                if (codeword != 1)
                {
                    return MP4_INVALID_VOL_PARAM;
                }


                ReadBits(psBits, 19, &codeword);
                if (!(codeword & 0x8))
                {
                    return MP4_INVALID_VOL_PARAM;
                }

                ReadBits(psBits, 11, &codeword);
                ReadBits(psBits, 1, &codeword);
                if (codeword != 1)
                {
                    return MP4_INVALID_VOL_PARAM;
                }

                ReadBits(psBits, 15, &codeword);
                ReadBits(psBits, 1, &codeword);
                if (codeword != 1)
                {
                    return MP4_INVALID_VOL_PARAM;
                }
            }

        }

        ReadBits(psBits, 2, &codeword);

        if (codeword != 0)
        {
            return MP4_INVALID_VOL_PARAM;
        }

        ReadBits(psBits, 1, &codeword);
        if (codeword != 1)
        {
            return MP4_INVALID_VOL_PARAM;
        }

        ReadBits(psBits, 16, &codeword);
        time_increment_resolution = codeword;


        ReadBits(psBits, 1, &codeword);
        if (codeword != 1)
        {
            return MP4_INVALID_VOL_PARAM;
        }



        ReadBits(psBits, 1, &codeword);

        if (codeword && time_increment_resolution > 2)
        {
            i = time_increment_resolution - 1;
            j = 1;
            while (i >>= 1)
            {
                j++;
            }
            nbits_time_increment = j;

            ReadBits(psBits, nbits_time_increment, &codeword);
        }
Beispiel #20
0
bool CDecoder::ReadTables(void)
{
  Byte levelLevels[kLevelTableSize];
  Byte newLevels[kMaxTableSize];
  m_AudioMode = (ReadBits(1) == 1);

  if (ReadBits(1) == 0)
    memset(m_LastLevels, 0, kMaxTableSize);
  
  unsigned numLevels;
  
  if (m_AudioMode)
  {
    m_NumChannels = ReadBits(2) + 1;
    if (m_MmFilter.CurrentChannel >= m_NumChannels)
      m_MmFilter.CurrentChannel = 0;
    numLevels = m_NumChannels * kMMTableSize;
  }
  else
    numLevels = kHeapTablesSizesSum;
 
  unsigned i;
  for (i = 0; i < kLevelTableSize; i++)
    levelLevels[i] = (Byte)ReadBits(4);
  RIF(m_LevelDecoder.SetCodeLengths(levelLevels));
  
  i = 0;
  
  while (i < numLevels)
  {
    UInt32 number = m_LevelDecoder.DecodeSymbol(&m_InBitStream);
    if (number < kTableDirectLevels)
    {
      newLevels[i] = (Byte)((number + m_LastLevels[i]) & kLevelMask);
      i++;
    }
    else
    {
      if (number == kTableLevelRepNumber)
      {
        unsigned t = ReadBits(2) + 3;
        for (unsigned reps = t; reps > 0 && i < numLevels; reps--, i++)
          newLevels[i] = newLevels[i - 1];
      }
      else
      {
        unsigned num;
        if (number == kTableLevel0Number)
          num = ReadBits(3) + 3;
        else if (number == kTableLevel0Number2)
          num = ReadBits(7) + 11;
        else
          return false;
        for (; num > 0 && i < numLevels; num--)
          newLevels[i++] = 0;
      }
    }
  }

  if (m_AudioMode)
    for (i = 0; i < m_NumChannels; i++)
    {
      RIF(m_MMDecoders[i].SetCodeLengths(&newLevels[i * kMMTableSize]));
    }
  else
  {
    RIF(m_MainDecoder.SetCodeLengths(&newLevels[0]));
    RIF(m_DistDecoder.SetCodeLengths(&newLevels[kMainTableSize]));
    RIF(m_LenDecoder.SetCodeLengths(&newLevels[kMainTableSize + kDistTableSize]));
  }
  
  memcpy(m_LastLevels, newLevels, kMaxTableSize);
  return true;
}
Beispiel #21
0
HRESULT CDecoder::CodeSpec(UInt32 curSize)
{
  if (_remainLen == kLenIdNeedInit)
  {
    _remainLen = 0;
    m_InBitStream.Init();
    if (!_keepHistory || !m_IsUncompressedBlock)
      m_InBitStream.Normalize();
    if (!_keepHistory)
    {
      _skipByte = false;
      m_UnCompressedBlockSize = 0;
      ClearPrevLevels();
      UInt32 i86TranslationSize = 12000000;
      bool translationMode = true;
      if (!_wimMode)
      {
        translationMode = (ReadBits(1) != 0);
        if (translationMode)
        {
          i86TranslationSize = ReadBits(16) << 16;
          i86TranslationSize |= ReadBits(16);
        }
      }
      m_x86ConvertOutStreamSpec->Init(translationMode, i86TranslationSize);
      
      for(int i = 0 ; i < kNumRepDistances; i++)
        m_RepDistances[i] = 0;
    }
  }

  while(_remainLen > 0 && curSize > 0)
  {
    m_OutWindowStream.PutByte(m_OutWindowStream.GetByte(m_RepDistances[0]));
    _remainLen--;
    curSize--;
  }

  while(curSize > 0)
  {
    if (m_UnCompressedBlockSize == 0)
      if (!ReadTables())
        return S_FALSE;
    UInt32 next = (Int32)MyMin(m_UnCompressedBlockSize, curSize);
    curSize -= next;
    m_UnCompressedBlockSize -= next;
    if (m_IsUncompressedBlock)
    {
      while(next > 0)
      {
        m_OutWindowStream.PutByte(m_InBitStream.DirectReadByte());
        next--;
      }
    }
    else while(next > 0)
    {
      UInt32 number = m_MainDecoder.DecodeSymbol(&m_InBitStream);
      if (number < 256)
      {
        m_OutWindowStream.PutByte((Byte)number);
        next--;
      }
      else
      {
        UInt32 posLenSlot = number - 256;
        if (posLenSlot >= m_NumPosLenSlots)
          return S_FALSE;
        UInt32 posSlot = posLenSlot / kNumLenSlots;
        UInt32 lenSlot = posLenSlot % kNumLenSlots;
        UInt32 len = kMatchMinLen + lenSlot;
        if (lenSlot == kNumLenSlots - 1)
        {
          UInt32 lenTemp = m_LenDecoder.DecodeSymbol(&m_InBitStream);
          if (lenTemp >= kNumLenSymbols)
            return S_FALSE;
          len += lenTemp;
        }
        
        if (posSlot < kNumRepDistances)
        {
          UInt32 distance = m_RepDistances[posSlot];
          m_RepDistances[posSlot] = m_RepDistances[0];
          m_RepDistances[0] = distance;
        }
        else
        {
          UInt32 distance;
          int numDirectBits;
          if (posSlot < kNumPowerPosSlots)
          {
            numDirectBits = (int)(posSlot >> 1) - 1;
            distance = ((2 | (posSlot & 1)) << numDirectBits);
          }
          else
          {
            numDirectBits = kNumLinearPosSlotBits;
            distance = ((posSlot - 0x22) << kNumLinearPosSlotBits);
          }

          if (m_AlignIsUsed && numDirectBits >= kNumAlignBits)
          {
            distance += (m_InBitStream.ReadBits(numDirectBits - kNumAlignBits) << kNumAlignBits);
            UInt32 alignTemp = m_AlignDecoder.DecodeSymbol(&m_InBitStream);
            if (alignTemp >= kAlignTableSize)
              return S_FALSE;
            distance += alignTemp;
          }
          else
            distance += m_InBitStream.ReadBits(numDirectBits);
          m_RepDistances[2] = m_RepDistances[1];
          m_RepDistances[1] = m_RepDistances[0];
          m_RepDistances[0] = distance - kNumRepDistances;
        }

        UInt32 locLen = len;
        if (locLen > next)
          locLen = next;

        if (!m_OutWindowStream.CopyBlock(m_RepDistances[0], locLen))
          return S_FALSE;

        len -= locLen;
        next -= locLen;
        if (len != 0)
        {
          _remainLen = (int)len;
          return S_OK;
        }
      }
    }
Beispiel #22
0
/** Get full-scale accelerometer range.
 * The FS_SEL parameter allows setting the full-scale range of the accelerometer
 * sensors, as described in the table below.
 *
 * <pre>
 * 0 = +/- 2g
 * 1 = +/- 4g
 * 2 = +/- 8g
 * 3 = +/- 16g
 * </pre>
 *
 * @return Current full-scale accelerometer range setting
 * @see MPU6050_ACCEL_FS_2
 * @see MPU6050_RA_ACCEL_CONFIG
 * @see MPU6050_ACONFIG_AFS_SEL_BIT
 * @see MPU6050_ACONFIG_AFS_SEL_LENGTH
 */
uint8_t clMPU6050::GetFullScaleAccelRange()
{
	uint8_t tmp;
	ReadBits(MPU6050_DEFAULT_ADDRESS, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_AFS_SEL_BIT, MPU6050_ACONFIG_AFS_SEL_LENGTH, &tmp);
	return tmp;
}
Beispiel #23
0
/** Get full-scale gyroscope range.
 * The FS_SEL parameter allows setting the full-scale range of the gyro sensors,
 * as described in the table below.
 *
 * <pre>
 * 0 = +/- 250 degrees/sec
 * 1 = +/- 500 degrees/sec
 * 2 = +/- 1000 degrees/sec
 * 3 = +/- 2000 degrees/sec
 * </pre>
 *
 * @return Current full-scale gyroscope range setting
 * @see MPU6050_GYRO_FS_250
 * @see MPU6050_RA_GYRO_CONFIG
 * @see MPU6050_GCONFIG_FS_SEL_BIT
 * @see MPU6050_GCONFIG_FS_SEL_LENGTH
 */
uint8_t clMPU6050::GetFullScaleGyroRange()
{
	uint8_t tmp;
	ReadBits(MPU6050_DEFAULT_ADDRESS, MPU6050_RA_GYRO_CONFIG, MPU6050_GCONFIG_FS_SEL_BIT, MPU6050_GCONFIG_FS_SEL_LENGTH, &tmp);
	return tmp;
}
Beispiel #24
0
/** Get Device ID.
 * This register is used to verify the identity of the device (0b110100).
 * @return Device ID (should be 0x68, 104 dec, 150 oct)
 * @see MPU6050_RA_WHO_AM_I
 * @see MPU6050_WHO_AM_I_BIT
 * @see MPU6050_WHO_AM_I_LENGTH
 */
uint8_t clMPU6050::GetDeviceID()
{
	uint8_t tmp;
	ReadBits(MPU6050_DEFAULT_ADDRESS, MPU6050_RA_WHO_AM_I, MPU6050_WHO_AM_I_BIT, MPU6050_WHO_AM_I_LENGTH, &tmp);
	return tmp;
}
Beispiel #25
0
void DisplaySignature(HDC MyDC, int x, int y)
{
    static DWORD *Signature=NULL; //This holds the DIBSection signature

    if(!MyDC) //This is called when window is destroyed, so delete signature data
    {
        delete[] Signature;
        Signature=NULL;
        return;
    }
    else if(Signature==NULL) //Signature data has not yet been extracted, so do so
    {
        //Prepare to decode signature
        //const UCHAR BytesPerPixel=4, TranspMask=255; //32 bits per pixel (for quicker copies and such - variable not used due to changing BYTE*s to DWORD*s), and white=transparent background color - also not used anymore since we directly write in the background color
        //Load data from executable
        HGLOBAL GetData=LoadResource(NULL, FindResource(NULL, "DakSig", "Sig")); //Load the resource from the executable
        BYTE *Input=(BYTE*)LockResource(GetData); //Get the resource data

        //Prepare header and decoding data
        UINT BitOn=0; //Bit we are currently on in reading
        EncodedFileHeader H=*(EncodedFileHeader*)Input; //Save header locally so we have quick memory lookups
        DWORD *Output=Signature=new DWORD[H.Width*H.Height]; //Allocate signature memory

        //Prepare the index colors
        DWORD Indexes[17], IndexSize=NumBitsRequired(H.NumIndexes); //Save full color indexes locally so we have quick lookups, use 17 index array so we don't have to allocate memory (since we already know how many there will be), #16=transparent color
        DWORD BackgroundColor=GetSysColor(COLOR_BTNFACE), FontColor=0x067906;
        BYTE *BGC=(BYTE*)&BackgroundColor, *FC=(BYTE*)&FontColor;
        for(UINT i=0; i<16; i++) //Alpha blend the indexes
        {
            float Alpha=((EncodedFileHeader*)Input)->Indexes[i] / 255.0f;
            BYTE IndexColor[4];
            for(int n=0; n<3; n++)
                IndexColor[n]=(BYTE)(BGC[n]*Alpha + FC[n]*(1-Alpha));
            //IndexColor[3]=0; //Don't really need to worry about the last byte as it is unused
            Indexes[i]=*(DWORD*)IndexColor;
        }
        Indexes[16]=BackgroundColor; //Translucent background = window background color

        //Unroll/unencode all the pixels
        Input+=(sizeof(EncodedFileHeader)+H.NumIndexes); //Start reading input past the header
        do
        {
            UINT l; //Length (transparent and then index)
            //Transparent pixels
            memsetd(Output, Indexes[16], l=ReadBits(Input, BitOn, H.TranspSize));
            Output+=l;

            //Translucent pixels
            l=ReadBits(Input, BitOn+=H.TranspSize, H.TranslSize);
            BitOn+=H.TranslSize;
            for(i=0; i<l; i++) //Write the gray scale out to the 3 pixels, this should technically be done in a for loop, which would unroll itself anyways, but this way ReadBits+index lookup is only done once - ** Would need to be in a for loop if not using gray-scale or 24 bit output
                Output[i]=Indexes[ReadBits(Input, BitOn+i*IndexSize, IndexSize)];
            Output+=l;
            BitOn+=l*IndexSize;
        } while(BitOn<H.DataSize);
    }

    //Output the signature
    const BITMAPINFOHEADER MyBitmapInfo= {sizeof(BITMAPINFOHEADER), 207, 42, 1, 32, BI_RGB, 0, 0, 0, 0, 0};
    SetDIBitsToDevice(MyDC, x, y, MyBitmapInfo.biWidth, MyBitmapInfo.biHeight, 0, 0, 0, MyBitmapInfo.biHeight, Signature, (BITMAPINFO*)&MyBitmapInfo, DIB_RGB_COLORS);
}
Beispiel #26
0
void         unShrink(void)

{ 
   int      stackp;
   int      finchar;
   int      code;
   int      oldcode;
   int      incode;


   /* decompress the file */ 
   maxcodemax = 1 << max_bits; 
   cbits = init_bits; 
   maxcode = (1 << cbits) - 1; 
   free_ent = first_ent; 
   offset = 0; 
   sizex = 0; 

   for (code = maxcodemax; code > 255; code--)
      prefix_of[code] = -1;

   for (code = 255; code >= 0; code--) 
   { 
      prefix_of[code] = 0;
      suffix_of[code] = code;
   } 

   ReadBits(cbits,&oldcode); 
   if (zipeof) return;
   finchar = oldcode; 

   OutByte(finchar); 

   stackp = 0; 

   while ((!zipeof)) 
   { 
      ReadBits(cbits,&code); 
      if (zipeof) return;

      while (code == clear)
      { 
         ReadBits(cbits,&code); 

         switch (code) {
            
            case 1:   { 
                  cbits++; 
                  if (cbits == max_bits) 
                     maxcode = maxcodemax;
                  else 
                     maxcode = (1 << cbits) - 1; 
               } 
            break;

            case 2:
                  partial_clear();
            break;
         } 

         ReadBits(cbits,&code); 
         if (zipeof) return;
      } 

   
      /* special case for KwKwK string */
      incode = code;
      if (prefix_of[code] == -1)
      { 
         stack[stackp] = finchar;
         stackp++; 
         code = oldcode; 
      } 


      /* generate output characters in reverse order */
      while (code >= first_ent)
      { 
         stack[stackp] = suffix_of[code];
         stackp++; 
         code = prefix_of[code];
      } 

      finchar = suffix_of[code];
      stack[stackp] = finchar;
      stackp++; 


      /* and put them out in forward order */
      while (stackp > 0)
      { 
         stackp--; 
         OutByte(stack[stackp]);
      } 


      /* generate new entry */
      code = free_ent;
      if (code < maxcodemax) 
      { 
         prefix_of[code] = oldcode;
         suffix_of[code] = finchar;
         while ((free_ent < maxcodemax) && (prefix_of[free_ent] != -1))
            free_ent++;
      } 


      /* remember previous code */
      oldcode = incode; 
   } 

} 
/*--------------------------------------------------------------------------------------------------

  Name         :  AvcReadMessage

  Description  :  Read incoming messages on the AVC LAN bus.

  Argument(s)  :  None.

  Return value :  (AvcActionID) -> Action ID associated with this message.

--------------------------------------------------------------------------------------------------*/
AvcActionID AvcReadMessage ( void )
{
    ReadBits( 1 ); // Start bit.

    LedOn();

    Broadcast = ReadBits( 1 );

    MasterAddress = ReadBits( 12 );
    bool p = ParityBit;
    if ( p != ReadBits( 1 ) )
    {
        UsartPutCStr( PSTR("AvcReadMessage: Parity error @ MasterAddress!\r\n") );
        return (AvcActionID)FALSE;
    }

    SlaveAddress = ReadBits( 12 );
    p = ParityBit;
    if ( p != ReadBits( 1 ) )
    {
        UsartPutCStr( PSTR("AvcReadMessage: Parity error @ SlaveAddress!\r\n") );
        return (AvcActionID)FALSE;
    }

    bool forMe = ( SlaveAddress == MY_ADDRESS );

    // In point-to-point communication, sender issues an ack bit with value '1' (20us). Receiver
    // upon acking will extend the bit until it looks like a '0' (32us) on the bus. In broadcast
    // mode, receiver disregards the bit.

    if ( forMe )
    {
        // Send ACK.
        Send1BitWord( 0 );
    }
    else
    {
        ReadBits( 1 );
    }

    Control = ReadBits( 4 );
    p = ParityBit;
    if ( p != ReadBits( 1 ) )
    {
        UsartPutCStr( PSTR("AvcReadMessage: Parity error @ Control!\r\n") );
        return (AvcActionID)FALSE;
    }

    if ( forMe )
    {
        // Send ACK.
        Send1BitWord( 0 );
    }
    else
    {
        ReadBits( 1 );
    }

    DataSize = ReadBits( 8 );
    p = ParityBit;
    if ( p != ReadBits( 1 ) )
    {
        UsartPutCStr( PSTR("AvcReadMessage: Parity error @ DataSize!\r\n") );
        return (AvcActionID)FALSE;
    }

    if ( forMe )
    {
        // Send ACK.
        Send1BitWord( 0 );
    }
    else
    {
        ReadBits( 1 );
    }

    byte i;

    for ( i = 0; i < DataSize; i++ )
    {
        Data[i] = ReadBits( 8 );
        p = ParityBit;
        if ( p != ReadBits( 1 ) )
        {
            sprintf( UsartMsgBuffer, "AvcReadMessage: Parity error @ Data[%d]\r\n", i );
            UsartPutStr( UsartMsgBuffer );
            return (AvcActionID)FALSE;
        }

        if ( forMe )
        {
            // Send ACK.
            Send1BitWord( 0 );
        }
        else
        {
            ReadBits( 1 );
        }
    }

    // Dump message on terminal.
    if ( forMe ) UsartPutCStr( PSTR("AvcReadMessage: This message is for me!\r\n") );

    AvcActionID actionID = GetActionID();

    // switch ( actionID ) {
    //   case /* value */:
    // }
    DumpRawMessage( FALSE );

    LedOff();

    return actionID;
}
Beispiel #28
0
   bool ReadStack(){

                              //reset output stack
      stack_top = 0;
                              //get next code
      word code;
      assert(code_size <= 12);
      if(!ReadBits(code_size, code))
         return false;

                              //index of first free entry in table
      const word first_entry = clear_code + 2;

                              //switch, different posibilities for code:
      if(code == clear_code+1)
         return true;         //exit LZW decompression loop
      if(code == clear_code){
         code_size = init_code_size + 1;  //reset code size
         next_entry_index = first_entry;        //reset Translation Table
         prev_code = code;                //Prevent next to be added to table.
                              //restart, to get another code
         return ReadStack();
      }
      word out_code;          //0 - 4096
      if(code < next_entry_index){
                           //code is in table
                           //set code to output
         out_code = code;
      }else{
                           //code is not in table
                           //keep first character of previous output
         ++stack_top;
                           //set prev_code to be output
         out_code = prev_code;
      }
                           //expand outcode in out_stack

                           // - Elements up to first_entry are Raw-Codes and are not expanded
                           // - Table Prefices contain indexes to other codes
                           // - Table Suffices contain the raw codes to be output
      while(out_code >= first_entry){
         if(stack_top > 4096)
            return false;
                           //add suffix to output stack
         out_stack[stack_top++] = suffix[out_code];
                           //loop with preffix
         out_code = prefix[out_code];
                              //watch for corruption
         if(out_code >= 4096)
            out_code = 0;
      }

                           //now outcode is a raw code, add it to output stack
      if(stack_top > 4096)
         return false;
      out_stack[stack_top++] = byte(out_code);

                           //add new entry to table (prev_code + outcode)
                           // (except if previous code was a clearcode)
      if(prev_code!=clear_code){
                           //prevent translation table overflow
         if(next_entry_index>=4096)
            //return false;
            next_entry_index = 4095;

         prefix[next_entry_index] = prev_code;
         suffix[next_entry_index] = byte(out_code);
         ++next_entry_index;
                           //increase codesize if next_entry_index is invalid with current codesize
         if(next_entry_index >= dword(1<<code_size)){
            if(code_size < 12)
               ++code_size;
         }
      }
      prev_code = code;
      return true;
   }
Beispiel #29
0
/* main decoder */
void Decode (void)
{

	register unsigned int i, j, k;
	unsigned long bytesdecompressed;

	i = 0;
	bytesdecompressed = 0;

	for ( ; ; )
	{
		if (ReadBits(1) == 0)   /* character or match? */
		{
			dict[i++] = ReadBits(CHARBITS);
			if (i == DICTSIZE)
			{
				if (fwrite(&dict, sizeof (char), DICTSIZE, outfile) == EOF)
				{
					printf("\nerror writing to output file");
					exit(EXIT_FAILURE);
				}
				i = 0;
				bytesdecompressed += DICTSIZE;
				printf("\r%ld", bytesdecompressed);
			}
		}
		else
		{
			/* get match length from input stream */
			k = (THRESHOLD + 1) + ReadBits(MATCHBITS);

			if (k == (MAXMATCH + 1))      /* Check for EOF flag */
			{
				if (fwrite(&dict, sizeof (char), i, outfile) == EOF)
				{
					printf("\nerror writing to output file");
					exit(EXIT_FAILURE);
				}
				bytesdecompressed += i;
				printf("\r%ld", bytesdecompressed);
				return;
			}

			/* get match position from input stream */
			j = ((i - ReadBits(DICTBITS)) & (DICTSIZE - 1));

			if ((i + k) >= DICTSIZE)
			{
				do
				{
					dict[i++] = dict[j++];
					j &= (DICTSIZE - 1);
					if (i == DICTSIZE)
					{
						if (fwrite(&dict, sizeof (char), DICTSIZE, outfile) == EOF)
						{
							printf("\nerror writing to output file");
							exit(EXIT_FAILURE);
						}
						i = 0;
						bytesdecompressed += DICTSIZE;
						printf("\r%ld", bytesdecompressed);
					}
				}
				while (--k);
			}
			else
			{
				if ((j + k) >= DICTSIZE)
				{
					do
					{
						dict[i++] = dict[j++];
						j &= (DICTSIZE - 1);
					}
					while (--k);
				}
				else
				{
					do
					{
						dict[i++] = dict[j++];
					}
					while (--k);
				}
			}
		}
	}

}
Beispiel #30
0
STDMETHODIMP CCoder::CodeReal(ISequentialInStream *inStream,
    ISequentialOutStream *outStream, const UInt64 * /* inSize */, const UInt64 *outSize,
    ICompressProgressInfo *progress)
{
  if (outSize == NULL)
    return E_INVALIDARG;

  if (!m_OutWindowStream.Create(kHistorySize))
    return E_OUTOFMEMORY;
  if (!m_InBitStream.Create(1 << 20))
    return E_OUTOFMEMORY;

  UInt64 pos = 0;
  m_OutWindowStream.SetStream(outStream);
  m_OutWindowStream.Init(false);
  m_InBitStream.SetStream(inStream);
  m_InBitStream.Init();
  
  CCoderReleaser coderReleaser(this);

  int pbit;
  if (m_NumDictBits <= 13)
    pbit = 4;
  else
    pbit = 5;

  UInt32 blockSize = 0;

  while (pos < *outSize)
  {
    // for (i = 0; i < dictSize; i++) dtext[i] = 0x20;
    
    if (blockSize == 0)
    {
      if (progress != NULL)
      {
        UInt64 packSize = m_InBitStream.GetProcessedSize();
        RINOK(progress->SetRatioInfo(&packSize, &pos));
      }
      blockSize = ReadBits(kBlockSizeBits);
      ReadLevelTable();
      ReadCTable();
      RINOK(ReadPTable(pbit));
    }
    blockSize--;
    UInt32 c = m_CHuffmanDecoder.Decode(&m_InBitStream);
    if (c < 256)
    {
      m_OutWindowStream.PutByte((Byte)c);
      pos++;
    }
    else if (c >= kNumCSymbols)
      return S_FALSE;
    else
    {
      // offset = (interface->method == LARC_METHOD_NUM) ? 0x100 - 2 : 0x100 - 3;
      UInt32 len = c - 256 + kMinMatch;
      UInt32 distance = m_PHuffmanDecoder.Decode(&m_InBitStream);
      if (distance != 0)
        distance = (1 << (distance - 1)) + ReadBits(distance - 1);
      if (distance >= pos)
        return S_FALSE;
      if (pos + len > *outSize)
        len = (UInt32)(*outSize - pos);
      pos += len;
      m_OutWindowStream.CopyBlock(distance, len);
    }
  }
  coderReleaser.NeedFlush = false;
  return m_OutWindowStream.Flush();
}