Пример #1
0
UInt64 GetRamSize()
{
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  return 0;
#else
  #ifndef UNDER_CE
  MY_MEMORYSTATUSEX stat;
  stat.dwLength = sizeof(stat);
  #endif
  #ifdef _WIN64
  if (!::GlobalMemoryStatusEx(&stat))
    return 0;
  return MyMin(stat.ullTotalVirtual, stat.ullTotalPhys);
  #else
  #ifndef UNDER_CE
  GlobalMemoryStatusExP globalMemoryStatusEx = (GlobalMemoryStatusExP)
      ::GetProcAddress(::GetModuleHandle(TEXT("kernel32.dll")), "GlobalMemoryStatusEx");
  if (globalMemoryStatusEx != 0 && globalMemoryStatusEx(&stat))
    return MyMin(stat.ullTotalVirtual, stat.ullTotalPhys);
  #endif
  {
    MEMORYSTATUS stat;
    stat.dwLength = sizeof(stat);
    ::GlobalMemoryStatus(&stat);
    return MyMin(stat.dwTotalVirtual, stat.dwTotalPhys);
  }
  #endif
#endif
}
Пример #2
0
STDMETHODIMP CFilterCoder::Write(const void *data, UInt32 size, UInt32 *processedSize)
{
  if (processedSize != NULL)
    *processedSize = 0;
  while (size > 0)
  {
    UInt32 sizeTemp = MyMin(size, kBufferSize - _bufferPos);
    memcpy(_buffer + _bufferPos, data, sizeTemp);
    size -= sizeTemp;
    if (processedSize != NULL)
      *processedSize += sizeTemp;
    data = (const Byte *)data + sizeTemp;
    UInt32 endPos = _bufferPos + sizeTemp;
    _bufferPos = Filter->Filter(_buffer, endPos);
    if (_bufferPos == 0)
    {
      _bufferPos = endPos;
      break;
    }
    if (_bufferPos > endPos)
    {
      if (size != 0)
        return E_FAIL;
      break;
    }
    RINOK(WriteWithLimit(_outStream, _bufferPos));
    UInt32 i = 0;
    while (_bufferPos < endPos)
      _buffer[i++] = _buffer[_bufferPos++];
    _bufferPos = i;
  }
  return S_OK;
}
Пример #3
0
void CPanel::OnShiftSelectMessage()
{
  if (!_mySelectMode)
    return;
  int focusedItem = _listView.GetFocusedItem();
  if (focusedItem < 0)
    return;
  if (!_selectionIsDefined)
    return;
  int startItem = MyMin(focusedItem, _prevFocusedItem);
  int finishItem = MyMax(focusedItem, _prevFocusedItem);
    
  int numItems = _listView.GetItemCount();
  for (int i = 0; i < numItems; i++)
  {
    int realIndex = GetRealItemIndex(i);
    if (realIndex == kParentIndex)
      continue;
    if (i >= startItem && i <= finishItem)
      if (_selectedStatusVector[realIndex] != _selectMark)
      {
        _selectedStatusVector[realIndex] = _selectMark;
        _listView.RedrawItem(i);
      }
  }

  _prevFocusedItem = focusedItem;
}
Пример #4
0
int Widget::getConnectedComponentLabeling()
{
    int i, j;
    int currlabel = 1;
    int label;
    int a[4];
    for(j=1; j<rsltImg.height()-1; j++){
        for(i=1; i<rsltImg.width()-1; i++){
            // 8 connected
            if( qGray(rsltImg.pixel(i,j)) != 0 )
            {
                a[0] = qGray(rsltImg.pixel(i-1,j-1));
                a[1] = qGray(rsltImg.pixel(i,j-1));
                a[2] = qGray(rsltImg.pixel(i+1,j-1));
                a[3] = qGray(rsltImg.pixel(i-1,j));

                label = MyMin(a);

                if(label != 0 && label != 255){
                    rsltImg.setPixel(i, j, qRgb(label, label, label));
                }
                else{
                    rsltImg.setPixel(i, j, qRgb(currlabel, currlabel, currlabel));
                    currlabel++;
                }
            }
        }
    }
    return (currlabel-1);
}
Пример #5
0
void CInArchive::ReadName(CItemEx &item, int nameSize)
{
  item.UnicodeName.Empty();
  if (nameSize > 0)
  {
    m_NameBuffer.EnsureCapacity(nameSize + 1);
    char *buffer = (char *)m_NameBuffer;

    for (int i = 0; i < nameSize; i++)
      buffer[i] = ReadByte();

    int mainLen;
    for (mainLen = 0; mainLen < nameSize; mainLen++)
      if (buffer[mainLen] == '\0')
        break;
    buffer[mainLen] = '\0';
    item.Name = buffer;

    if(item.HasUnicodeName())
    {
      if(mainLen < nameSize)
      {
        int unicodeNameSizeMax = MyMin(nameSize, (0x400));
        _unicodeNameBuffer.EnsureCapacity(unicodeNameSizeMax + 1);
        DecodeUnicodeFileName(buffer, (const Byte *)buffer + mainLen + 1,
            nameSize - (mainLen + 1), _unicodeNameBuffer, unicodeNameSizeMax);
        item.UnicodeName = _unicodeNameBuffer;
      }
      else if (!ConvertUTF8ToUnicode(item.Name, item.UnicodeName))
        item.UnicodeName.Empty();
    }
  }
  else
    item.Name.Empty();
}
Пример #6
0
STDMETHODIMP CSequentialInStreamImp::Read(void *data, UInt32 size, UInt32 *processedSize)
{
  UInt32 numBytesToRead = (UInt32)(MyMin(_pos + size, _size) - _pos);
  memmove(data, _dataPointer + _pos, numBytesToRead);
  _pos += numBytesToRead;
  if(processedSize != NULL)
    *processedSize = numBytesToRead;
  return S_OK;
}
Пример #7
0
void wavwrite(double *x, int x_length, int fs, int nbit, char *filename) {
  FILE *fp = fopen(filename, "wb");
  if (fp == NULL) {
    printf("File cannot be opened.\n");
    return;
  }

  char text[4] = {'R', 'I', 'F', 'F'};
  uint32_t long_number = 36 + x_length * 2;
  fwrite(text, 1, 4, fp);
  fwrite(&long_number, 4, 1, fp);

  text[0] = 'W';
  text[1] = 'A';
  text[2] = 'V';
  text[3] = 'E';
  fwrite(text, 1, 4, fp);
  text[0] = 'f';
  text[1] = 'm';
  text[2] = 't';
  text[3] = ' ';
  fwrite(text, 1, 4, fp);

  long_number = 16;
  fwrite(&long_number, 4, 1, fp);
  int16_t short_number = 1;
  fwrite(&short_number, 2, 1, fp);
  short_number = 1;
  fwrite(&short_number, 2, 1, fp);
  long_number = fs;
  fwrite(&long_number, 4, 1, fp);
  long_number = fs * 2;
  fwrite(&long_number, 4, 1, fp);
  short_number = 2;
  fwrite(&short_number, 2, 1, fp);
  short_number = 16;
  fwrite(&short_number, 2, 1, fp);

  text[0] = 'd';
  text[1] = 'a';
  text[2] = 't';
  text[3] = 'a';
  fwrite(text, 1, 4, fp);
  long_number = x_length * 2;
  fwrite(&long_number, 4, 1, fp);

  int16_t tmp_signal;
  for (int i = 0; i < x_length; ++i) {
    tmp_signal = (int16_t)(MyMax(-32768,
        MyMin(32767, (int)(x[i] * 32767))));
    fwrite(&tmp_signal, 2, 1, fp);
  }

  fclose(fp);
}
STDMETHODIMP CFolderOutStream::Write(const void *data, 
    UInt32 size, UInt32 *processedSize)
{
  UInt32 realProcessedSize = 0;
  while(_currentIndex < _extractStatuses->Size())
  {
    if (_fileIsOpen)
    {
      UInt32 index = _startIndex + _currentIndex;
      const CFileItem &fileInfo = _archiveDatabase->Files[index];
      UInt64 fileSize = fileInfo.UnPackSize;
      
      UInt32 numBytesToWrite = (UInt32)MyMin(fileSize - _filePos, 
          UInt64(size - realProcessedSize));
      
      UInt32 processedSizeLocal;
      RINOK(_outStreamWithHash->Write((const Byte *)data + realProcessedSize, 
            numBytesToWrite, &processedSizeLocal));

      _filePos += processedSizeLocal;
      realProcessedSize += processedSizeLocal;
      if (_filePos == fileSize)
      {
        bool digestsAreEqual;
        if (fileInfo.IsFileCRCDefined && _checkCrc)
          digestsAreEqual = fileInfo.FileCRC == _outStreamWithHashSpec->GetCRC();
        else
          digestsAreEqual = true;

        RINOK(_extractCallback->SetOperationResult(
            digestsAreEqual ? 
            NArchive::NExtract::NOperationResult::kOK :
            NArchive::NExtract::NOperationResult::kCRCError));
        _outStreamWithHashSpec->ReleaseStream();
        _fileIsOpen = false;
        _currentIndex++;
      }
      if (realProcessedSize == size)
      {
        if (processedSize != NULL)
          *processedSize = realProcessedSize;
        return WriteEmptyFiles();
      }
    }
    else
    {
      RINOK(OpenFile());
      _fileIsOpen = true;
      _filePos = 0;
    }
  }
  if (processedSize != NULL)
    *processedSize = size;
  return S_OK;
}
Пример #9
0
 CFilePool::CFilePool(int _blockNum, int _threadNum, void* _context)
     : m_threadPool(MyMin(_threadNum, 20))
     , m_IOContextPool(MyMax(_blockNum, 1024))
 {
     m_readCallback = boost::bind(&CFilePool::onDataRead, this, _1, _2, _3);
     m_writeCallback = boost::bind(&CFilePool::onDataWritten, this, _1, _2, _3);
     m_errorCallback = boost::bind(&CFilePool::onError, this, _1, _2, _3);
     m_context = _context;
     m_isStop = false;
     m_aioCallback = NULL;
 }
Пример #10
0
Файл: d4c.cpp Проект: r9y9/WORLD
DLLEXPORT void D4C(double *x, int x_length, int fs, double *time_axis, double *f0,
    int f0_length, int fft_size, D4COption *option, double **aperiodicity) {
  int fft_size_d4c = static_cast<int>(pow(2.0, 1.0 +
      static_cast<int>(log(4.0 * fs / world::kFloorF0 + 1) / world::kLog2)));

  ForwardRealFFT forward_real_fft = {0};
  InitializeForwardRealFFT(fft_size_d4c, &forward_real_fft);

  int number_of_aperiodicities =
    static_cast<int>(MyMin(world::kUpperLimit, fs / 2.0 -
      world::kFrequencyInterval) / world::kFrequencyInterval);
  // Since the window function is common in D4CGeneralBody(),
  // it is designed here to speed up.
  int window_length =
    static_cast<int>(world::kFrequencyInterval * fft_size_d4c / fs) * 2 + 1;
  double *window =  new double[window_length];
  NuttallWindow(window_length, window);

  double *coarse_aperiodicity = new double[number_of_aperiodicities + 2];
  coarse_aperiodicity[0] = -60.0;
  coarse_aperiodicity[number_of_aperiodicities + 1] = 0.0;
  double *coarse_frequency_axis = new double[number_of_aperiodicities + 2];
  for (int i = 0; i <= number_of_aperiodicities; ++i)
    coarse_frequency_axis[i] =
      static_cast<double>(i) * world::kFrequencyInterval;
  coarse_frequency_axis[number_of_aperiodicities + 1] = fs / 2.0;

  double *frequency_axis = new double[fft_size / 2 + 1];
  for (int i = 0; i <= fft_size / 2; ++i)
    frequency_axis[i] = static_cast<double>(i) * fs / fft_size;
  for (int i = 0; i < f0_length; ++i) {
    if (f0[i] == 0) {
      for (int j = 0; j <= fft_size / 2; ++j) aperiodicity[i][j] = 0.0;
      continue;
    }
    D4CGeneralBody(x, x_length, fs, MyMax(f0[i], world::kFloorF0),
        fft_size_d4c, time_axis[i], number_of_aperiodicities, window,
        window_length, &forward_real_fft, &coarse_aperiodicity[1]);
    // Linear interpolation to convert the coarse aperiodicity into its
    // spectral representation.
    interp1(coarse_frequency_axis, coarse_aperiodicity,
        number_of_aperiodicities + 2, frequency_axis, fft_size / 2 + 1,
        aperiodicity[i]);
    for (int j = 0; j <= fft_size / 2; ++j)
      aperiodicity[i][j] = pow(10.0, aperiodicity[i][j] / 20.0);
  }

  DestroyForwardRealFFT(&forward_real_fft);
  delete[] coarse_frequency_axis;
  delete[] coarse_aperiodicity;
  delete[] window;
  delete[] frequency_axis;
}
Пример #11
0
static HRESULT WriteBytes(ISequentialOutStream *stream, const void *data, size_t size)
{
  while (size > 0)
  {
    UInt32 curSize = (UInt32)MyMin(size, (size_t)0xFFFFFFFF);
    UInt32 processedSize;
    RINOK(stream->Write(data, curSize, &processedSize));
    if (processedSize == 0)
      return E_FAIL;
    data = (const void *)((const Byte *)data + processedSize);
    size -= processedSize;
  }
  return S_OK;
}
STDMETHODIMP CLimitedSequentialInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
{
  UInt32 realProcessedSize = 0;
  UInt32 sizeToRead = (UInt32)MyMin((_size - _pos), (UInt64)size);
  HRESULT result = S_OK;
  if (sizeToRead > 0)
  {
    result = _stream->Read(data, sizeToRead, &realProcessedSize);
    _pos += realProcessedSize;
    if (realProcessedSize == 0)
      _wasFinished = true;
  }
  if (processedSize)
    *processedSize = realProcessedSize;
  return result;
}
Пример #13
0
STDMETHODIMP CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize)
{
  UInt32 processedSizeTotal = 0;
  while(size > 0)
  {
    if (_convertedPosBegin != _convertedPosEnd)
    {
      UInt32 sizeTemp = MyMin(size, _convertedPosEnd - _convertedPosBegin);
      memmove(data, _buffer + _convertedPosBegin, sizeTemp);
      _convertedPosBegin += sizeTemp;
      data = (void *)((Byte *)data + sizeTemp);
      size -= sizeTemp;
      processedSizeTotal += sizeTemp;
      break;
    }
    int i;
    for (i = 0; _convertedPosEnd + i < _bufferPos; i++)
      _buffer[i] = _buffer[i + _convertedPosEnd];
    _bufferPos = i;
    _convertedPosBegin = _convertedPosEnd = 0;
    UInt32 processedSizeTemp;
    UInt32 size0 = kBufferSize - _bufferPos;
    // Optimize it:
    RINOK(ReadStream(_inStream, _buffer + _bufferPos, size0, &processedSizeTemp));
    _bufferPos = _bufferPos + processedSizeTemp;
    _convertedPosEnd = Filter->Filter(_buffer, _bufferPos);
    if (_convertedPosEnd == 0)
    {
      if (_bufferPos == 0)
        break;
      else
      {
        _convertedPosEnd = _bufferPos; // check it
        continue;
      }
    }
    if (_convertedPosEnd > _bufferPos)
    {
      for (; _bufferPos < _convertedPosEnd; _bufferPos++)
        _buffer[_bufferPos] = 0;
      _convertedPosEnd = Filter->Filter(_buffer, _bufferPos);
    }
  }
  if (processedSize != NULL)
    *processedSize = processedSizeTotal;
  return S_OK;
}
Пример #14
0
STDMETHODIMP CCabBlockInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
{
  if (processedSize != 0)
    *processedSize = 0;
  if (size == 0)
    return S_OK;
  if (_size != 0)
  {
    size = MyMin(_size, size);
    memmove(data, _buffer + _pos, size);
    _pos += size;
    _size -= size;
    if (processedSize != 0)
      *processedSize = size;
    return S_OK;
  }
  return S_OK; // no blocks data
}
Пример #15
0
STDMETHODIMP CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize)
{
  if (processedSize != NULL)
    *processedSize = 0;
  while (size > 0)
  {
    if (_convertedPosBegin != _convertedPosEnd)
    {
      UInt32 sizeTemp = MyMin(size, _convertedPosEnd - _convertedPosBegin);
      memcpy(data, _buffer + _convertedPosBegin, sizeTemp);
      _convertedPosBegin += sizeTemp;
      data = (void *)((Byte *)data + sizeTemp);
      size -= sizeTemp;
      if (processedSize != NULL)
        *processedSize += sizeTemp;
      break;
    }
    UInt32 i;
    for (i = 0; _convertedPosEnd + i < _bufferPos; i++)
      _buffer[i] = _buffer[_convertedPosEnd + i];
    _bufferPos = i;
    _convertedPosBegin = _convertedPosEnd = 0;
    size_t processedSizeTemp = kBufferSize - _bufferPos;
    RINOK(ReadStream(_inStream, _buffer + _bufferPos, &processedSizeTemp));
    _bufferPos += (UInt32)processedSizeTemp;
    _convertedPosEnd = Filter->Filter(_buffer, _bufferPos);
    if (_convertedPosEnd == 0)
    {
      if (_bufferPos == 0)
        break;
      _convertedPosEnd = _bufferPos; // check it
      continue;
    }
    if (_convertedPosEnd > _bufferPos)
    {
      for (; _bufferPos < _convertedPosEnd; _bufferPos++)
        _buffer[_bufferPos] = 0;
      _convertedPosEnd = Filter->Filter(_buffer, _bufferPos);
    }
  }
  return S_OK;
}
Пример #16
0
HRESULT CDecoder::SetToPos(UInt64 pos, ICompressProgressInfo *progress)
{
  if (StreamPos > pos)
    return E_FAIL;
  const UInt64 inSizeStart = GetInputProcessedSize();
  UInt64 offset = 0;
  while (StreamPos < pos)
  {
    size_t size = (size_t)MyMin(pos - StreamPos, (UInt64)Buffer.Size());
    RINOK(Read(Buffer, &size));
    if (size == 0)
      return S_FALSE;
    StreamPos += size;
    offset += size;

    const UInt64 inSize = GetInputProcessedSize() - inSizeStart;
    RINOK(progress->SetRatioInfo(&inSize, &offset));
  }
  return S_OK;
}
Пример #17
0
STDMETHODIMP CCachedInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
{
  if (processedSize)
    *processedSize = 0;
  if (size == 0)
    return S_OK;
  if (_pos > _size)
    return E_FAIL;

  {
    UInt64 rem = _size - _pos;
    if (size > rem)
      size = (UInt32)rem;
  }

  while (size != 0)
  {
    UInt64 cacheTag = _pos >> _blockSizeLog;
    size_t cacheIndex = (size_t)cacheTag & (((size_t)1 << _numBlocksLog) - 1);
    Byte *p = _data + (cacheIndex << _blockSizeLog);
    if (_tags[cacheIndex] != cacheTag)
    {
      UInt64 remInBlock = _size - (cacheTag << _blockSizeLog);
      size_t blockSize = (size_t)1 << _blockSizeLog;
      if (blockSize > remInBlock)
        blockSize = (size_t)remInBlock;
      RINOK(ReadBlock(cacheTag, p, blockSize));
      _tags[cacheIndex] = cacheTag;
    }
    size_t offset = (size_t)_pos & (((size_t)1 << _blockSizeLog) - 1);
    UInt32 cur = (UInt32)MyMin(((size_t)1 << _blockSizeLog) - offset, (size_t)size);
    memcpy(data, p + offset, cur);
    if (processedSize)
      *processedSize += cur;
    data = (void *)((const Byte *)data + cur);
    _pos += cur;
    size -= cur;
  }

  return S_OK;
}
STDMETHODIMP Cx86ConvertOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)
{
  if (processedSize)
    *processedSize = 0;
  if (!_translationMode)
    return _stream->Write(data, size, processedSize);
  UInt32 realProcessedSize = 0;
  while (realProcessedSize < size)
  {
    UInt32 writeSize = MyMin(size - realProcessedSize, kUncompressedBlockSize - _pos);
    memcpy(_buf + _pos, (const Byte *)data + realProcessedSize, writeSize);
    _pos += writeSize;
    realProcessedSize += writeSize;
    if (_pos == kUncompressedBlockSize)
    {
      RINOK(Flush());
    }
  }
  if (processedSize)
    *processedSize = realProcessedSize;
  return S_OK;
}
Пример #19
0
STDMETHODIMP COutVolumeStream::Write(const void *data, UInt32 size, UInt32 *processedSize)
{
  if(processedSize != NULL)
    *processedSize = 0;
  while(size > 0)
  {
    if (!_volumeStream)
    {
      RINOK(VolumeCallback->GetVolumeSize(_volIndex, &_volSize));
      RINOK(VolumeCallback->GetVolumeStream(_volIndex, &_volumeStream));
      _volIndex++;
      _curPos = 0;
      RINOK(_archive.Create(_volumeStream, true));
      RINOK(_archive.SkeepPrefixArchiveHeader());
      _crc.Init();
      continue;
    }
    UInt64 pureSize = COutArchive::GetVolPureSize(_volSize, _file.Name.Length());
    UInt32 curSize = (UInt32)MyMin(UInt64(size), pureSize - _curPos);

    _crc.Update(data, curSize);
    UInt32 realProcessed;
    RINOK(_volumeStream->Write(data, curSize, &realProcessed))
    data = (void *)((Byte *)data + realProcessed);
    size -= realProcessed;
    if(processedSize != NULL)
      *processedSize += realProcessed;
    _curPos += realProcessed;
    if (realProcessed != curSize && realProcessed == 0)
      return E_FAIL;
    if (_curPos == pureSize)
    {
      RINOK(Flush());
    }
  }
  return S_OK;
}
Пример #20
0
void Synthesis(const double *f0, int f0_length, const double *const*spectrogram,
    const double *const*residual_spectrogram, int fft_size, double frame_period,
    int fs, int y_length, double *y) {
  double *impulse_response = new double[fft_size];

  MinimumPhaseAnalysis minimum_phase = {0};
  InitializeMinimumPhaseAnalysis(fft_size, &minimum_phase);
  InverseRealFFT inverse_real_fft = {0};
  InitializeInverseRealFFT(fft_size, &inverse_real_fft);

  double current_time = 0.0;
  int current_position = 0;
  int current_frame = 0;
  // Length used for the synthesis is unclear.
  const int kFrameLength = 3 * fft_size / 4;

  while (1) {
    GetOneFrameSegment(f0, spectrogram, residual_spectrogram, fft_size,
        current_frame, &minimum_phase, &inverse_real_fft, impulse_response);

    for (int i = current_position;
        i < MyMin(current_position + kFrameLength, y_length - 1); ++i)
      y[i] += impulse_response[i - current_position];

    // update
    current_time +=
      1.0 / (f0[current_frame] == 0.0 ? world::kDefaultF0 : f0[current_frame]);
    current_frame = matlab_round(current_time / (frame_period / 1000.0));
    current_position = static_cast<int>(current_time * fs);
    if (current_frame >= f0_length) break;
  }

  DestroyMinimumPhaseAnalysis(&minimum_phase);
  DestroyInverseRealFFT(&inverse_real_fft);
  delete[] impulse_response;
}
Пример #21
0
HRESULT CDecoder::CodeReal(ISequentialInStream *anInStream,
    ISequentialOutStream *anOutStream,
    const UINT64 *, const UINT64 *anOutSize)
{
  if (anOutSize == NULL)
    return E_INVALIDARG;

  Init(anInStream, anOutStream);

  CState aState;
  aState.Init();
  bool aPeviousIsMatch = false;
  BYTE aPreviousByte = 0;
  UINT32 aRepDistances[kNumRepDistances];
  for(UINT32 i = 0 ; i < kNumRepDistances; i++)
    aRepDistances[i] = 0;

  UINT64 aNowPos64 = 0;
  UINT64 aSize = *anOutSize;
  while(aNowPos64 < aSize)
  {
    UINT64 aNext = MyMin(aNowPos64 + (1 << 18), aSize);
    while(aNowPos64 < aNext)
    {
      UINT32 aPosState = UINT32(aNowPos64) & m_PosStateMask;
      if (m_MainChoiceDecoders[aState.m_Index][aPosState].Decode(&m_RangeDecoder) == (UINT32) kMainChoiceLiteralIndex)
      {
        // aCounts[0]++;
        aState.UpdateChar();
        if(aPeviousIsMatch)
        {
          BYTE aMatchByte = m_OutWindowStream.GetOneByte(0 - aRepDistances[0] - 1);
          aPreviousByte = m_LiteralDecoder.DecodeWithMatchByte(&m_RangeDecoder,
              UINT32(aNowPos64), aPreviousByte, aMatchByte);
          aPeviousIsMatch = false;
        }
        else
          aPreviousByte = m_LiteralDecoder.DecodeNormal(&m_RangeDecoder,
              UINT32(aNowPos64), aPreviousByte);
        m_OutWindowStream.PutOneByte(aPreviousByte);
        aNowPos64++;
      }
      else
      {
        aPeviousIsMatch = true;
        UINT32 aDistance, aLen;
        if(m_MatchChoiceDecoders[aState.m_Index].Decode(&m_RangeDecoder) ==
            (UINT32) kMatchChoiceRepetitionIndex)
        {
          if(m_MatchRepChoiceDecoders[aState.m_Index].Decode(&m_RangeDecoder) == 0)
          {
            if(m_MatchRepShortChoiceDecoders[aState.m_Index][aPosState].Decode(&m_RangeDecoder) == 0)
            {
              aState.UpdateShortRep();
              aPreviousByte = m_OutWindowStream.GetOneByte(0 - aRepDistances[0] - 1);
              m_OutWindowStream.PutOneByte(aPreviousByte);
              aNowPos64++;
              // aCounts[3 + 4]++;
              continue;
            }
            // aCounts[3 + 0]++;
            aDistance = aRepDistances[0];
          }
          else
          {
            if(m_MatchRep1ChoiceDecoders[aState.m_Index].Decode(&m_RangeDecoder) == 0)
            {
              aDistance = aRepDistances[1];
              aRepDistances[1] = aRepDistances[0];
              // aCounts[3 + 1]++;
            }
            else
            {
              if (m_MatchRep2ChoiceDecoders[aState.m_Index].Decode(&m_RangeDecoder) == 0)
              {
                // aCounts[3 + 2]++;
                aDistance = aRepDistances[2];
              }
              else
              {
                // aCounts[3 + 3]++;
                aDistance = aRepDistances[3];
                aRepDistances[3] = aRepDistances[2];
              }
              aRepDistances[2] = aRepDistances[1];
              aRepDistances[1] = aRepDistances[0];
            }
            aRepDistances[0] = aDistance;
          }
          aLen = m_RepMatchLenDecoder.Decode(&m_RangeDecoder, aPosState) + kMatchMinLen;
          // aCounts[aLen]++;
          aState.UpdateRep();
        }
        else
        {
          aLen = kMatchMinLen + m_LenDecoder.Decode(&m_RangeDecoder, aPosState);
          aState.UpdateMatch();
          UINT32 aPosSlot = m_PosSlotDecoder[GetLenToPosState(aLen)].Decode(&m_RangeDecoder);
          // aCounts[aPosSlot]++;
          if (aPosSlot >= (UINT32) kStartPosModelIndex)
          {
            aDistance = kDistStart[aPosSlot];
            if (aPosSlot < (UINT32) kEndPosModelIndex)
              aDistance += m_PosDecoders[aPosSlot - kStartPosModelIndex].Decode(&m_RangeDecoder);
            else
            {
              aDistance += (m_RangeDecoder.DecodeDirectBits(kDistDirectBits[aPosSlot] -
                  kNumAlignBits) << kNumAlignBits);
              aDistance += m_PosAlignDecoder.Decode(&m_RangeDecoder);
            }
          }
          else
            aDistance = aPosSlot;


          aRepDistances[3] = aRepDistances[2];
          aRepDistances[2] = aRepDistances[1];
          aRepDistances[1] = aRepDistances[0];

          aRepDistances[0] = aDistance;
          // UpdateStat(aLen, aPosSlot);
        }
        if (aDistance >= aNowPos64)
          throw E_INVALIDDATA;
        m_OutWindowStream.CopyBackBlock(aDistance, aLen);
        aNowPos64 += aLen;
        aPreviousByte = m_OutWindowStream.GetOneByte(0 - 1);
      }
    }
  }
  return Flush();
}
Пример #22
0
UString CDString128::GetString() const
{
  unsigned size = Data[sizeof(Data) - 1];
  return ParseDString(Data, MyMin(size, (unsigned)(sizeof(Data) - 1)));
}
Пример #23
0
HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unpackSize,
    ISequentialOutStream *realOutStream, ICompressProgressInfo *progress,
    UInt32 &packSizeRes, UInt32 &unpackSizeRes)
{
  CLimitedSequentialInStream *limitedStreamSpec = NULL;
  CMyComPtr<ISequentialInStream> limitedStream;
  packSizeRes = 0;
  unpackSizeRes = 0;

  if (Solid)
  {
    Byte temp[4];
    size_t processedSize = 4;
    RINOK(Read(temp, &processedSize));
    StreamPos += processedSize;
    if (processedSize != 4)
      return S_FALSE;
    UInt32 size = Get32(temp);
    if (unpackSizeDefined && size != unpackSize)
      return S_FALSE;
    unpackSize = size;
    unpackSizeDefined = true;
  }
  else
  {
    Byte temp[4];
    {
      size_t processedSize = 4;
      RINOK(ReadStream(InputStream, temp, &processedSize));
      StreamPos += processedSize;
      if (processedSize != 4)
        return S_FALSE;
    }
    UInt32 size = Get32(temp);

    if ((size & kMask_IsCompressed) == 0)
    {
      if (unpackSizeDefined && size != unpackSize)
        return S_FALSE;
      packSizeRes = size;
      if (outBuf)
        outBuf->Alloc(size);

      UInt64 offset = 0;
      
      while (size > 0)
      {
        UInt32 curSize = (UInt32)MyMin((size_t)size, Buffer.Size());
        UInt32 processedSize;
        RINOK(InputStream->Read(Buffer, curSize, &processedSize));
        if (processedSize == 0)
          return S_FALSE;
        if (outBuf)
          memcpy((Byte *)*outBuf + (size_t)offset, Buffer, processedSize);
        offset += processedSize;
        size -= processedSize;
        StreamPos += processedSize;
        unpackSizeRes += processedSize;
        if (realOutStream)
          RINOK(WriteStream(realOutStream, Buffer, processedSize));
        RINOK(progress->SetRatioInfo(&offset, &offset));
      }

      return S_OK;
    }
    
    size &= ~kMask_IsCompressed;
    packSizeRes = size;
    limitedStreamSpec = new CLimitedSequentialInStream;
    limitedStream = limitedStreamSpec;
    limitedStreamSpec->SetStream(InputStream);
    limitedStreamSpec->Init(size);
    {
      bool useFilter;
      RINOK(Init(limitedStream, useFilter));
    }
  }
  
  if (outBuf)
  {
    if (unpackSizeDefined)
      outBuf->Alloc(unpackSize);
  }

  const UInt64 inSizeStart = GetInputProcessedSize();

  // we don't allow files larger than 4 GB;
  if (!unpackSizeDefined)
    unpackSize = 0xFFFFFFFF;
  UInt32 offset = 0;

  HRESULT res = S_OK;

  for (;;)
  {
    size_t rem = unpackSize - offset;
    if (rem == 0)
      break;
    size_t size = Buffer.Size();
    if (size > rem)
      size = rem;
    RINOK(Read(Buffer, &size));
    if (size == 0)
    {
      if (unpackSizeDefined)
        res = S_FALSE;
      break;
    }
    
    if (outBuf)
    {
      size_t nextSize = offset + size;
      if (outBuf->Size() < nextSize)
      {
        {
          const size_t nextSize2 = outBuf->Size() * 2;
          if (nextSize < nextSize2)
            nextSize = nextSize2;
        }
        outBuf->ChangeSize_KeepData(nextSize, offset);
      }
      memcpy((Byte *)*outBuf + (size_t)offset, Buffer, size);
    }
    
    StreamPos += size;
    offset += (UInt32)size;

    const UInt64 inSize = GetInputProcessedSize() - inSizeStart;

    if (Solid)
      packSizeRes = (UInt32)inSize;
    unpackSizeRes += (UInt32)size;
    
    UInt64 outSize = offset;
    RINOK(progress->SetRatioInfo(&inSize, &outSize));
    if (realOutStream)
    {
      res = WriteStream(realOutStream, Buffer, size);
      if (res != S_OK)
        break;
    }
  }

  if (outBuf && offset != outBuf->Size())
    outBuf->ChangeSize_KeepData(offset, offset);
  
  return res;
}
Пример #24
0
STDMETHODIMP CInFileStream::Read(void *data, UInt32 size, UInt32 *processedSize)
{
  #ifdef USE_WIN_FILE
  
  #ifdef SUPPORT_DEVICE_FILE
  if (processedSize)
    *processedSize = 0;
  if (size == 0)
    return S_OK;
  if (File.IsDeviceFile)
  {
    if (File.SizeDefined)
    {
      if (VirtPos >= File.Size)
        return VirtPos == File.Size ? S_OK : E_FAIL;
      UInt64 rem = File.Size - VirtPos;
      if (size > rem)
        size = (UInt32)rem;
    }
    for (;;)
    {
      const UInt32 mask = kClusterSize - 1;
      const UInt64 mask2 = ~(UInt64)mask;
      UInt64 alignedPos = VirtPos & mask2;
      if (BufSize > 0 && BufStartPos == alignedPos)
      {
        UInt32 pos = (UInt32)VirtPos & mask;
        if (pos >= BufSize)
          return S_OK;
        UInt32 rem = MyMin(BufSize - pos, size);
        memcpy(data, Buf + pos, rem);
        VirtPos += rem;
        if (processedSize)
          *processedSize += rem;
        return S_OK;
      }
      
      bool useBuf = false;
      if ((VirtPos & mask) != 0 || ((ptrdiff_t)data & mask) != 0 )
        useBuf = true;
      else
      {
        UInt64 end = VirtPos + size;
        if ((end & mask) != 0)
        {
          end &= mask2;
          if (end <= VirtPos)
            useBuf = true;
          else
            size = (UInt32)(end - VirtPos);
        }
      }
      if (!useBuf)
        break;
      if (alignedPos != PhyPos)
      {
        UInt64 realNewPosition;
        bool result = File.Seek(alignedPos, FILE_BEGIN, realNewPosition);
        if (!result)
          return ConvertBoolToHRESULT(result);
        PhyPos = realNewPosition;
      }

      BufStartPos = alignedPos;
      UInt32 readSize = kClusterSize;
      if (File.SizeDefined)
        readSize = (UInt32)MyMin(File.Size - PhyPos, (UInt64)kClusterSize);

      if (!Buf)
      {
        Buf = (Byte *)MidAlloc(kClusterSize);
        if (!Buf)
          return E_OUTOFMEMORY;
      }
      bool result = File.Read1(Buf, readSize, BufSize);
      if (!result)
        return ConvertBoolToHRESULT(result);

      if (BufSize == 0)
        return S_OK;
      PhyPos += BufSize;
    }

    if (VirtPos != PhyPos)
    {
      UInt64 realNewPosition;
      bool result = File.Seek(VirtPos, FILE_BEGIN, realNewPosition);
      if (!result)
        return ConvertBoolToHRESULT(result);
      PhyPos = VirtPos = realNewPosition;
    }
  }
  #endif

  UInt32 realProcessedSize;
  bool result = File.ReadPart(data, size, realProcessedSize);
  if (processedSize)
    *processedSize = realProcessedSize;

  #ifdef SUPPORT_DEVICE_FILE
  VirtPos += realProcessedSize;
  PhyPos += realProcessedSize;
  #endif

  if (result)
    return S_OK;

  {
    DWORD error = ::GetLastError();

    if (Callback)
      return Callback->InFileStream_On_Error(CallbackRef, error);
    if (error == 0)
      return E_FAIL;

    return HRESULT_FROM_WIN32(error);
  }

  #else
  
  if (processedSize)
    *processedSize = 0;
  ssize_t res = File.Read(data, (size_t)size);
  if (res == -1)
  {
    if (Callback)
      return Callback->InFileStream_On_Error(CallbackRef, E_FAIL);
    return E_FAIL;
  }
  if (processedSize)
    *processedSize = (UInt32)res;
  return S_OK;

  #endif
}
Пример #25
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;
        }
      }
    }
Пример #26
0
HRESULT LzmaDecoderCodeReal(
    LzmaDecoder     *lzmaDecoder,
    UINT64          *anInSize,
    UINT64          *anOutSize)
{
    BOOL                  aPeviousIsMatch         = FALSE;
    BYTE                  aPreviousByte           = 0;
    UINT32                aRepDistances[kNumRepDistances];
    int                   i;
    UINT64                aNowPos64               = 0;
    UINT64                aSize                   = *anOutSize;
    ISequentialInStream   my_in_stream;
//  WindowOut             out_window;
    CState                aState;

    CStateInit(&aState);

    if (anOutSize == NULL)
    {
        printf("CodeReal: invalid argument %x\n", (UINT32) anOutSize );
        return E_INVALIDARG;
    }


    LzmaDecoderInit(lzmaDecoder);

    my_in_stream.data           = in_stream.data;
    my_in_stream.remainingBytes = in_stream.remainingBytes;

    for(i = 0 ; i < (int) kNumRepDistances; i++)
        aRepDistances[i] = 0;

    //while(aNowPos64 < aSize)
    while(my_in_stream.remainingBytes > 0)
    {
        UINT64 aNext = MyMin(aNowPos64 + (1 << 18), aSize);
        while(aNowPos64 < aNext)
        {
            UINT32 aPosState = (UINT32)(aNowPos64) & lzmaDecoder->m_PosStateMask;
            if (BitDecode(&my_in_stream,
                          &lzmaDecoder->m_MainChoiceDecoders[aState][aPosState],
                          &lzmaDecoder->m_RangeDecoder) == (UINT32) kMainChoiceLiteralIndex)
            {
                CStateUpdateChar(&aState);
                if(aPeviousIsMatch)
                {
                    BYTE aMatchByte = OutWindowGetOneByte(0 - aRepDistances[0] - 1);
                    aPreviousByte = LitDecodeWithMatchByte(&my_in_stream,
                                                           &lzmaDecoder->m_LiteralDecoder,
                                                           &lzmaDecoder->m_RangeDecoder,
                                                           (UINT32)(aNowPos64),
                                                           aPreviousByte,
                                                           aMatchByte);
                    aPeviousIsMatch = FALSE;
                }
                else
                    aPreviousByte = LitDecodeNormal(&my_in_stream,
                                                    &lzmaDecoder->m_LiteralDecoder,
                                                    &lzmaDecoder->m_RangeDecoder,
                                                    (UINT32)(aNowPos64),
                                                    aPreviousByte);
                OutWindowPutOneByte(aPreviousByte);
                aNowPos64++;
            }
            else
            {
                UINT32 aDistance, aLen;
                aPeviousIsMatch = TRUE;
                if(BitDecode(&my_in_stream,
                             &lzmaDecoder->m_MatchChoiceDecoders[aState],
                             &lzmaDecoder->m_RangeDecoder) == (UINT32) kMatchChoiceRepetitionIndex)
                {
                    if(BitDecode(&my_in_stream,
                                 &lzmaDecoder->m_MatchRepChoiceDecoders[aState],
                                 &lzmaDecoder->m_RangeDecoder) == 0)
                    {
                        if(BitDecode(&my_in_stream,
                                     &lzmaDecoder->m_MatchRepShortChoiceDecoders[aState][aPosState],
                                     &lzmaDecoder->m_RangeDecoder) == 0)
                        {
                            CStateUpdateShortRep(&aState);
                            aPreviousByte = OutWindowGetOneByte(0 - aRepDistances[0] - 1);
                            OutWindowPutOneByte(aPreviousByte);
                            aNowPos64++;
                            continue;
                        }
                        aDistance = aRepDistances[0];
                    }
                    else
                    {
                        if(BitDecode(&my_in_stream,
                                     &lzmaDecoder->m_MatchRep1ChoiceDecoders[aState],
                                     &lzmaDecoder->m_RangeDecoder) == 0)
                        {
                            aDistance = aRepDistances[1];
                            aRepDistances[1] = aRepDistances[0];
                        }
                        else
                        {
                            if (BitDecode(&my_in_stream,
                                          &lzmaDecoder->m_MatchRep2ChoiceDecoders[aState],
                                          &lzmaDecoder->m_RangeDecoder) == 0)
                            {
                                aDistance = aRepDistances[2];
                            }
                            else
                            {
                                aDistance = aRepDistances[3];
                                aRepDistances[3] = aRepDistances[2];
                            }
                            aRepDistances[2] = aRepDistances[1];
                            aRepDistances[1] = aRepDistances[0];
                        }
                        aRepDistances[0] = aDistance;
                    }
                    aLen = LenDecode(&my_in_stream,
                                     &lzmaDecoder->m_RepMatchLenDecoder,
                                     &lzmaDecoder->m_RangeDecoder,
                                     aPosState) + kMatchMinLen;
                    CStateUpdateRep(&aState);
                }
                else
                {
                    UINT32 aPosSlot;
                    aLen = kMatchMinLen + LenDecode(&my_in_stream,
                                                    &lzmaDecoder->m_LenDecoder,
                                                    &lzmaDecoder->m_RangeDecoder,
                                                    aPosState);
                    CStateUpdateMatch(&aState);
                    aPosSlot = BitTreeDecode(&my_in_stream,
                                             &lzmaDecoder->m_PosSlotDecoder[GetLenToPosState(aLen)],
                                             &lzmaDecoder->m_RangeDecoder);
                    if (aPosSlot >= (UINT32) kStartPosModelIndex)
                    {
                        aDistance = kDistStart[aPosSlot];
                        if (aPosSlot < (UINT32) kEndPosModelIndex)
                            aDistance += ReverseBitTreeDecoder2Decode(&my_in_stream,
                                         &lzmaDecoder->m_PosDecoders[aPosSlot - kStartPosModelIndex],
                                         &lzmaDecoder->m_RangeDecoder);
                        else
                        {
                            aDistance += (RangeDecodeDirectBits(&my_in_stream,
                                                                &lzmaDecoder->m_RangeDecoder,
                                                                kDistDirectBits[aPosSlot] - kNumAlignBits) << kNumAlignBits);
                            aDistance += ReverseBitTreeDecoderDecode(&my_in_stream,
                                         &lzmaDecoder->m_PosAlignDecoder,
                                         &lzmaDecoder->m_RangeDecoder);
                        }
                    }
                    else
                        aDistance = aPosSlot;


                    aRepDistances[3] = aRepDistances[2];
                    aRepDistances[2] = aRepDistances[1];
                    aRepDistances[1] = aRepDistances[0];

                    aRepDistances[0] = aDistance;
                }
                if (aDistance >= aNowPos64)
                {
                    printf("CodeReal: invalid data\n" );
                    return E_INVALIDDATA;
                }
                OutWindowCopyBackBlock(aDistance, aLen);
                aNowPos64 += aLen;
                aPreviousByte = OutWindowGetOneByte(0 - 1);
            }
        }
    }

    //BRCM modification
    LzmaDecoderFreeBuffer(lzmaDecoder);

    OutWindowFlush();
    return S_OK;
}
Пример #27
0
int Kravatte_WBC_Decipher(Kravatte_Instance *kv, const BitSequence *ciphertext, BitSequence *plaintext, BitLength dataBitLen,
                        const BitSequence *W, BitLength WBitLen)
{
    size_t nL = Kravatte_WBC_Split(dataBitLen);
    size_t nR = dataBitLen - nL;
    size_t nL0 = MyMin(width, nL);
    size_t nR0 = MyMin(width, nR);
    unsigned char L0[SnP_widthInBytes];
    unsigned char HkW[SnP_widthInBytes];
    unsigned char kRollAfterHkW[Kravatte_RollcSizeInBytes];
    unsigned int numberOfBitsInLastByte;
    BitSequence lastByte[1];

    /* L0 = L0 + Hk(R || 1) */
    numberOfBitsInLastByte = nR & 7;
    if (Kra(kv, Rc, nR - numberOfBitsInLastByte, KRAVATTE_FLAG_INIT) != 0) /* Do all except last byte if incomplete */
        return 1;
    lastByte[0] = (numberOfBitsInLastByte != 0) ? Rc[nR/8] : 0;
    lastByte[0] &= (1 << numberOfBitsInLastByte) - 1;
    lastByte[0] |= 1 << numberOfBitsInLastByte;
    if (Kravatte(kv, lastByte, numberOfBitsInLastByte + 1, L0, nL0, KRAVATTE_FLAG_SHORT) != 0)
        return 1;
    memxoris( L0, Lc, nL0);

    /* R = R + Fk(L || 0 . W) */
    if (Kra(kv, W, WBitLen, KRAVATTE_FLAG_INIT | KRAVATTE_FLAG_LAST_PART) != 0)
        return 1;
    memcpy(HkW, kv->xAccu.a, SnP_widthInBytes);
    memcpy(kRollAfterHkW, kv->kRoll.a+Kravatte_RollcOffset, Kravatte_RollcSizeInBytes);
    if (Kra(kv, L0, nL0, KRAVATTE_FLAG_NONE) != 0) /* compress L0 */
        return 1;
    if (Kra(kv, Lc + nL0 / 8, nL - nL0, KRAVATTE_FLAG_NONE) != 0)  /* compress rest of L */
        return 1;
    lastByte[0] = 0;
    if (Kravatte(kv, lastByte, 1, Rp, nR, KRAVATTE_FLAG_NONE) != 0)  /* last zero bit */
        return 1;
    memxoris(Rp, Rc, nR);

    /* L = L + Fk(R || 1 . W) */
    memcpy(kv->kRoll.a+Kravatte_RollcOffset, kRollAfterHkW, Kravatte_RollcSizeInBytes);
    memcpy(kv->xAccu.a, HkW, SnP_widthInBytes);
    if (Kra(kv, Rp, nR - numberOfBitsInLastByte, KRAVATTE_FLAG_NONE) != 0)
        return 1;
    lastByte[0] = (numberOfBitsInLastByte != 0) ? Rp[nR/8] : 0;
    lastByte[0] &= (1 << numberOfBitsInLastByte) - 1;
    lastByte[0] |= 1 << numberOfBitsInLastByte;
    if (Kravatte(kv, lastByte, numberOfBitsInLastByte + 1, Lp, nL, KRAVATTE_FLAG_NONE) != 0)
        return 1;
    memxoris(Lp, L0, nL0);
    memxoris(Lp + nL0 / 8, Lc + nL0 / 8, nL - nL0);

    /* R0 = R0 + Hk(L || 0) */
    if (Kra(kv, Lp, nL, KRAVATTE_FLAG_INIT) != 0) /* Do all, L is always a multiple of 8 bits */
        return 1;
    lastByte[0] = 0;
    if (Kravatte(kv, lastByte, 1, L0, nR0, KRAVATTE_FLAG_SHORT) != 0)
        return 1;
    memxoris(Rp, L0, nR0);

    return 0;
}
Пример #28
0
HRESULT CDecoder::Decode(CByteBuffer *outBuf, bool unpackSizeDefined, UInt32 unpackSize,
                         ISequentialOutStream *realOutStream, ICompressProgressInfo *progress,
                         UInt32 &packSizeRes, UInt32 &unpackSizeRes)
{
    CLimitedSequentialInStream *limitedStreamSpec = NULL;
    CMyComPtr<ISequentialInStream> limitedStream;
    packSizeRes = 0;
    unpackSizeRes = 0;

    if (Solid)
    {
        Byte temp[4];
        size_t processedSize = 4;
        RINOK(Read(temp, &processedSize));
        if (processedSize != 4)
            return S_FALSE;
        StreamPos += processedSize;
        UInt32 size = Get32(temp);
        if (unpackSizeDefined && size != unpackSize)
            return S_FALSE;
        unpackSize = size;
        unpackSizeDefined = true;
    }
    else
    {
        Byte temp[4];
        RINOK(ReadStream_FALSE(InputStream, temp, 4));
        StreamPos += 4;
        UInt32 size = Get32(temp);

        if ((size & kMask_IsCompressed) == 0)
        {
            if (unpackSizeDefined && size != unpackSize)
                return S_FALSE;
            packSizeRes = size;
            if (outBuf)
                outBuf->Alloc(size);

            UInt64 offset = 0;

            while (size > 0)
            {
                UInt32 curSize = (UInt32)MyMin((size_t)size, Buffer.Size());
                UInt32 processedSize;
                RINOK(InputStream->Read(Buffer, curSize, &processedSize));
                if (processedSize == 0)
                    return S_FALSE;
                if (outBuf)
                    memcpy((Byte *)*outBuf + (size_t)offset, Buffer, processedSize);
                offset += processedSize;
                size -= processedSize;
                StreamPos += processedSize;
                unpackSizeRes += processedSize;
                if (realOutStream)
                    RINOK(WriteStream(realOutStream, Buffer, processedSize));
                RINOK(progress->SetRatioInfo(&offset, &offset));
            }

            return S_OK;
        }

        size &= ~kMask_IsCompressed;
        packSizeRes = size;
        limitedStreamSpec = new CLimitedSequentialInStream;
        limitedStream = limitedStreamSpec;
        limitedStreamSpec->SetStream(InputStream);
        limitedStreamSpec->Init(size);
        {
            bool useFilter;
            RINOK(Init(limitedStream, useFilter));
        }
    }

    if (outBuf)
    {
        if (!unpackSizeDefined)
            return S_FALSE;
        outBuf->Alloc(unpackSize);
    }

    UInt64 inSizeStart = 0;
    if (_lzmaDecoder)
        inSizeStart = _lzmaDecoder->GetInputProcessedSize();

    // we don't allow files larger than 4 GB;
    if (!unpackSizeDefined)
        unpackSize = 0xFFFFFFFF;
    UInt32 offset = 0;

    for (;;)
    {
        size_t rem = unpackSize - offset;
        if (rem == 0)
            break;
        size_t size = Buffer.Size();
        if (size > rem)
            size = rem;
        RINOK(Read(Buffer, &size));
        if (size == 0)
        {
            if (unpackSizeDefined)
                return S_FALSE;
            break;
        }
        if (outBuf)
            memcpy((Byte *)*outBuf + (size_t)offset, Buffer, size);
        StreamPos += size;
        offset += (UInt32)size;

        UInt64 inSize = 0; // it can be improved: we need inSize for Deflate and BZip2 too.
        if (_lzmaDecoder)
            inSize = _lzmaDecoder->GetInputProcessedSize() - inSizeStart;
        if (Solid)
            packSizeRes = (UInt32)inSize;
        unpackSizeRes += (UInt32)size;

        UInt64 outSize = offset;
        RINOK(progress->SetRatioInfo(&inSize, &outSize));
        if (realOutStream)
            RINOK(WriteStream(realOutStream, Buffer, size));
    }
    return S_OK;
}
Пример #29
0
int XoofffWBC_Encipher(Xoofff_Instance *xp, const BitSequence *plaintext, BitSequence *ciphertext, BitLength dataBitLen,
                        const BitSequence *W, BitLength WBitLen)
{
    size_t nL = XoofffWBC_Split(dataBitLen);
    size_t nR = dataBitLen - nL;
    size_t nL0 = MyMin(width, nL);
    size_t nR0 = MyMin(width, nR);
    unsigned char R0[SnP_widthInBytes];
    unsigned char HkW[SnP_widthInBytes];
    unsigned char kRollAfterHkW[Xoofff_RollSizeInBytes];
    unsigned int numberOfBitsInLastByte;
    BitSequence lastByte[1];

    /* R0 = R0 + Hk(L || 0) */
    if (Xoofff_Compress(xp, Lp, nL, Xoofff_FlagInit) != 0) /* Do complete L, is always a multiple of 8 bits */
        return 1;
    lastByte[0] = 0;
    if (Xoofff(xp, lastByte, 1, R0, nR0, Xoofff_FlagXoofffie) != 0)
        return 1;
    Xoofff_AddIs(R0, Rp, nR0);

    /* L = L + Fk(R || 1 . W) */
    if (Xoofff_Compress(xp, W, WBitLen, Xoofff_FlagInit | Xoofff_FlagLastPart) != 0)
        return 1;
    memcpy(HkW, xp->xAccu.a, SnP_widthInBytes);
    memcpy(kRollAfterHkW, xp->kRoll.a+Xoofff_RollOffset, Xoofff_RollSizeInBytes);
    numberOfBitsInLastByte = nR & 7;
    lastByte[0] = (numberOfBitsInLastByte != 0) ? Rp[nR/8] : 0;
    if (nR0 == nR) {
        if (Xoofff_Compress(xp, R0, nR0 - numberOfBitsInLastByte, Xoofff_FlagNone) != 0)  /* Compress R0 except last byte if incomplete */
            return 1;
        lastByte[0] = (numberOfBitsInLastByte != 0) ? R0[nR/8] : 0;
    }
    else {
        if (Xoofff_Compress(xp, R0, nR0, Xoofff_FlagNone) != 0) /* compress R0 */
            return 1;
        if (Xoofff_Compress(xp, Rp + nR0 / 8, nR - nR0 - numberOfBitsInLastByte, Xoofff_FlagNone) != 0)  /* rest of R except last byte if incomplete */
            return 1;
        lastByte[0] = (numberOfBitsInLastByte != 0) ? Rp[nR/8] : 0;
    }
    lastByte[0] &= (1 << numberOfBitsInLastByte) - 1;
    lastByte[0] |= 1 << numberOfBitsInLastByte;
    if (Xoofff(xp, lastByte, numberOfBitsInLastByte + 1, Lc, nL, Xoofff_FlagNone) != 0)
        return 1;
    Xoofff_AddIs(Lc, Lp, nL);

    /* R = R + Fk(L || 0 . W) */
    memcpy(xp->kRoll.a+Xoofff_RollOffset, kRollAfterHkW, Xoofff_RollSizeInBytes);
    memcpy(xp->xAccu.a, HkW, SnP_widthInBytes);
    if (Xoofff_Compress(xp, Lc, nL, Xoofff_FlagNone) != 0)
        return 1;
    lastByte[0] = 0;
    if (Xoofff(xp, lastByte, 1, Rc, nR, Xoofff_FlagNone) != 0)
        return 1;
    Xoofff_AddIs(Rc, R0, nR0);
    Xoofff_AddIs(Rc + nR0 / 8, Rp + nR0 / 8, nR - nR0);

    /* L0 = L0 + Hk(R || 1) */
    if (Xoofff_Compress(xp, Rc, nR - numberOfBitsInLastByte, Xoofff_FlagInit) != 0) /* Do all except last byte if incomplete */
        return 1;
    lastByte[0] = (numberOfBitsInLastByte != 0) ? Rc[nR/8] : 0;
    lastByte[0] &= (1 << numberOfBitsInLastByte) - 1;
    lastByte[0] |= 1 << numberOfBitsInLastByte;
    if (Xoofff(xp, lastByte, numberOfBitsInLastByte + 1, R0, nL0, Xoofff_FlagXoofffie) != 0)
        return 1;
    Xoofff_AddIs(Lc, R0, nL0);

    return 0;
}