コード例 #1
0
void convertToBigEndian(const void *src, const uint64_t size, void *result)
{
	uint8_t *ptr, *ptr2;
	uint64_t i;
	uint8_t temp;

	if ((src == NULL) || (size == 0) || (result == NULL))
		return;

	ptr = (uint8_t *)src;
	ptr2 = (uint8_t *)result;
	if (!isBigEndian())
	{
		if (src != result)
			for (i = 0; i < size; i++)
				ptr2[i] = ptr[size - 1 - i];
		else
			for (i = 0; i < size / 2; i++)
			{
				temp = ptr2[i];
				ptr2[i] = ptr[size - 1 - i];
				ptr[size - 1 - i] = temp;
			}
	}
	else
	{
		if (src != result)
			for (i = 0; i < size; i++)
				ptr2[i] = ptr[i];
	}
}
コード例 #2
0
ファイル: events.cpp プロジェクト: hernando/Livre
RemoteInformation deserializeDataSourceData( const ::zeq::Event& event )
{
    if( event.getType() != EVENT_DATASOURCE_DATA )
        return RemoteInformation();

    auto data = GetVolumeInformation( event.getData( ));
    RemoteInformation info;
    livre::VolumeInformation& vi = info.second;

    info.first.low() = data->eventLow();
    info.first.high() = data->eventHigh();
    vi.isBigEndian = data->isBigEndian();
    vi.compCount = data->compCount();
    vi.dataType = DataType( data->dataType( ));
    vi.overlap = _deserializeVector3< unsigned >( data->overlap( ));
    vi.maximumBlockSize = _deserializeVector3< unsigned >(
                                 data->maximumBlockSize( ));
    vi.minPos = _deserializeVector3< float >( data->minPos( ));
    vi.maxPos = _deserializeVector3< float >( data->maxPos( ));
    vi.voxels = _deserializeVector3< unsigned >( data->voxels( ));
    vi.worldSize = _deserializeVector3< float >( data->worldSize( ));
    vi.boundingBox.getMin() = _deserializeVector3< float >(
                                     data->boundingBoxMin( ));
    vi.boundingBox.getMax() = _deserializeVector3< float >(
                                     data->boundingBoxMax( ));
    vi.worldSpacePerVoxel = data->worldSpacePerVoxel();

    const Vector3ui& blockSize = vi.maximumBlockSize - vi.overlap * 2;
    Vector3ui blocksSize = vi.voxels / blockSize;
    blocksSize = blocksSize / ( 1u << data->depth( ));

    vi.rootNode = RootNode( data->depth(), blocksSize );
    return info;
}
コード例 #3
0
int main(void) {

    // 判断机器是大端存储还是小端存储
    if (isBigEndian()) {
        printf("BigEndian\n");
    } else {
        printf("LittleEndian\n");
    }


    char buf[32];

    sprintf(buf,"ciaoroma");
    memrev16(buf);
    printf("%s\n", buf);

    sprintf(buf,"ciaoroma");
    memrev32(buf);
    printf("%s\n", buf);

    sprintf(buf,"ciaoroma");
    memrev64(buf);
    printf("%s\n", buf);

    return 0;
}
コード例 #4
0
ファイル: signBit.c プロジェクト: kayceesrk/mlton-zmq
C_Int_t Real32_signBit (Real32_t f) {
  int R32_byte;
  if (isBigEndian()) {
    R32_byte = BIG_R32_byte;
  } else {
    R32_byte = LITTLE_R32_byte;
  }

  /* Using memcpy. 
   * Technically correct.
   */
  unsigned char chars[4];
  memcpy(chars, &f, sizeof(Real32_t));
  return (chars[R32_byte] & 0x80) >> 7;
  /* Using cast; 
   * Technically correct, as (unsigned char*) may alias.   
   */
  /*
  return (((unsigned char*)(&f))[R32_byte] & 0x80) >> 7;
  */
  /* Using union; 
   * Technically undefined, but widely supported. 
   */
  /*
  union {float f; unsigned char c[4];} fc;
  fc.f = f;
  return (fc.c[R32_byte] & 0x80) >> 7;
  */
}
コード例 #5
0
ファイル: Sockets.c プロジェクト: DeathByTape/UofI_undergrad
int recvData(int sockfd, void* data, int len)
{
  int ret = read(sockfd, data, len);
  if(!isBigEndian())
    switchEndian(data, ret);
  return ret;
}
コード例 #6
0
ファイル: insrv.cpp プロジェクト: liuchg5/framework
int main(int argc, char const *argv[])
{
    printf("Befin insrv !!!\n");
	printf("serverIsBigEndian == %d !!!\n", isBigEndian());
	
	CShmQueueSingle inq, outq;

	outq.crt(1024 * 1024 * 16, 1111);
    outq.get();
    outq.init();
    outq.clear();

    inq.crt(1024 * 1024 * 16, 2222);
    inq.get();
    inq.init();
    inq.clear();

    CSocketEpoll epoll(8000, 0, 1000, 0, 1, 1);//(int epoll_Size, int epoll_Timeout, int Listenq, int clientIsBigEndian, int serverIsBigEndian)
    epoll.prepare("0.0.0.0", 10203, &outq, &inq);//(const char * serv_addr, int port_num, CShmQueueSingle *poutq, CShmQueueSingle *pinq);
    epoll.run();
	
	
	// test_socket_srv("192.168.190.131", 10203);
	
	return 0;
}
コード例 #7
0
ファイル: ar5312_reset.c プロジェクト: 2asoft/freebsd
/*
 * Write the given reset bit mask into the reset register
 */
static HAL_BOOL
ar5312SetResetReg(struct ath_hal *ah, uint32_t resetMask)
{
	uint32_t mask = resetMask ? resetMask : ~0;
	HAL_BOOL rt;

        if ((rt = ar5312MacReset(ah, mask)) == AH_FALSE) {
		return rt;
	}
        if ((resetMask & AR_RC_MAC) == 0) {
		if (isBigEndian()) {
			/*
			 * Set CFG, little-endian for descriptor accesses.
			 */
#ifdef AH_NEED_DESC_SWAP
			mask = INIT_CONFIG_STATUS | AR_CFG_SWRD;
#else
			mask = INIT_CONFIG_STATUS |
                                AR_CFG_SWTD | AR_CFG_SWRD;
#endif
			OS_REG_WRITE(ah, AR_CFG, mask);
		} else
			OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
	}
	return rt;
}
コード例 #8
0
ファイル: PacketManager.cpp プロジェクト: stal888/gnet
bool PacketManager::Write64(Uint64 val){
  Uint32 size = dataPos + sizeof(Uint64);
  if(bufferSize < size)if(!Allocate(size))return false;
  Uint8 *v = (Uint8*)(&val);
  if(isBigEndian()){
    buffer[dataPos + 0] = v[0];
    buffer[dataPos + 1] = v[1];
    buffer[dataPos + 2] = v[2];
    buffer[dataPos + 3] = v[3];
    buffer[dataPos + 4] = v[4];
    buffer[dataPos + 5] = v[5];
    buffer[dataPos + 6] = v[6];
    buffer[dataPos + 7] = v[7];
  }else{
    buffer[dataPos + 7] = v[0];
    buffer[dataPos + 6] = v[1];
    buffer[dataPos + 5] = v[2];
    buffer[dataPos + 4] = v[3];
    buffer[dataPos + 3] = v[4];
    buffer[dataPos + 2] = v[5];
    buffer[dataPos + 1] = v[6];
    buffer[dataPos + 0] = v[7];
  }
  dataPos += sizeof(Uint64);
  if(dataLength < dataPos)dataLength = dataPos;
  return true;
}
コード例 #9
0
ファイル: PacketManager.cpp プロジェクト: stal888/gnet
bool PacketManager::ReadD(double *val){
  if(dataLength < dataPos + sizeof(double))return false;
  double v;
  if(isBigEndian()){
    ((Uint8*)(&v))[0] = buffer[dataPos + 0];
    ((Uint8*)(&v))[1] = buffer[dataPos + 1];
    ((Uint8*)(&v))[2] = buffer[dataPos + 2];
    ((Uint8*)(&v))[3] = buffer[dataPos + 3];
    ((Uint8*)(&v))[4] = buffer[dataPos + 4];
    ((Uint8*)(&v))[5] = buffer[dataPos + 5];
    ((Uint8*)(&v))[6] = buffer[dataPos + 6];
    ((Uint8*)(&v))[7] = buffer[dataPos + 7];
  }else{
    ((Uint8*)(&v))[7] = buffer[dataPos + 0];
    ((Uint8*)(&v))[6] = buffer[dataPos + 1];
    ((Uint8*)(&v))[5] = buffer[dataPos + 2];
    ((Uint8*)(&v))[4] = buffer[dataPos + 3];
    ((Uint8*)(&v))[3] = buffer[dataPos + 4];
    ((Uint8*)(&v))[2] = buffer[dataPos + 5];
    ((Uint8*)(&v))[1] = buffer[dataPos + 6];
    ((Uint8*)(&v))[0] = buffer[dataPos + 7];
  }
  dataPos += sizeof(double);
  if(val != NULL)*val = v;
  return true;
}
コード例 #10
0
ファイル: utility.cpp プロジェクト: MickeMakaron/ShankBot
std::vector<size_t> rgbaToTransparencyTreeSprite(const unsigned char* rgba, size_t width, size_t height, bool* isBlank)
{
    std::vector<unsigned char> sprite;
    sprite.push_back(width);
    sprite.push_back(height);
    size_t size = width * height * BYTES_PER_PIXEL_RGBA;
    size_t stripSize = 0;
    auto compressor = isBigEndian() ? compressBigEndianMultiByteValue<size_t> : compressSmallEndianMultiByteValue<size_t>;
    for(size_t i = 0; i + BYTES_PER_PIXEL_RGBA - 1 < size; i += BYTES_PER_PIXEL_RGBA)
    {
        if(rgba[i + BYTES_PER_PIXEL_RGBA - 1] == 255)
        {
            if(stripSize == 0)
            {
                compressor(i, sprite);
            }

            stripSize++;
        }
        else if(stripSize > 0)
        {
            compressor(stripSize, sprite);
            stripSize = 0;
        }
    }
    if(isBlank)
        *isBlank = (sprite.size() == 2);
    return packBytes(sprite);
}
コード例 #11
0
ファイル: signBit.c プロジェクト: kayceesrk/mlton-zmq
C_Int_t Real64_signBit (Real64_t d) {
  int R64_byte;
  if (isBigEndian()) {
    R64_byte = BIG_R64_byte;
  } else {
    R64_byte = LITTLE_R64_byte;
  }

  /* Using memcpy. 
   * Technically correct.
   */
  unsigned char chars[8];
  memcpy(chars, &d, sizeof(Real64_t));
  return (chars[R64_byte] & 0x80) >> 7;
  /* Using cast; 
   * Technically correct, as (unsigned char*) may alias.   
   */
  /*
  return (((unsigned char*)(&d))[R64_byte] & 0x80) >> 7;
  */
  /* Using union; 
   * Technically undefined, but widely supported. 
   */
  /*
  union {double d; unsigned char c[8];} dc;
  dc.d = d;
  return (dc.c[R64_byte] & 0x80) >> 7;
  */
}
コード例 #12
0
ファイル: nitrofile.cpp プロジェクト: bsmr-games/xoreos
Common::SeekableSubReadStreamEndian *NitroFile::open(Common::SeekableReadStream &stream) {
	const size_t begin = stream.pos();
	const size_t end   = stream.size();

	const bool bigEndian = isBigEndian(stream);

	return new Common::SeekableSubReadStreamEndian(&stream, begin, end, bigEndian, false);
}
コード例 #13
0
ファイル: nitrofile.cpp プロジェクト: ImperatorPrime/xoreos
Common::SeekableSubReadStreamEndian *NitroFile::open(Common::SeekableReadStream *stream) {
	Common::ScopedPtr<Common::SeekableReadStream> nitroStream(stream);

	const size_t begin = nitroStream->pos();
	const size_t end   = nitroStream->size();

	const bool bigEndian = isBigEndian(*nitroStream);

	return new Common::SeekableSubReadStreamEndian(nitroStream.release(), begin, end, bigEndian, true);
}
コード例 #14
0
void ElfFile::save(const std::wstring&fileName)
{
	fileData.clear();

	// reserve space for header and table data
	fileData.reserveBytes(sizeof(Elf32_Ehdr));

	for (int i = 0; i < 4; i++)
	{
		switch (partsOrder[i])
		{
		case ELFPART_SEGMENTTABLE:
			fileData.alignSize(4);
			fileHeader.e_phoff = (Elf32_Off) fileData.size();
			fileData.reserveBytes(segments.size()*fileHeader.e_phentsize);
			break;
		case ELFPART_SECTIONTABLE:
			fileData.alignSize(4);
			fileHeader.e_shoff = (Elf32_Off) fileData.size();
			fileData.reserveBytes(sections.size()*fileHeader.e_shentsize);
			break;
		case ELFPART_SEGMENTS:
			for (int i = 0; i < (int)segments.size(); i++)
			{
				segments[i]->writeData(fileData);
			}
			break;
		case ELFPART_SEGMENTLESSSECTIONS:
			for (int i = 0; i < (int)segmentlessSections.size(); i++)
			{
				segmentlessSections[i]->writeData(fileData);
			}
			break;
		}
	}

	// copy data to the tables
	bool bigEndian = isBigEndian();
	writeHeader(fileData, 0, bigEndian);
	for (int i = 0; i < (int)segments.size(); i++)
	{
		int pos = fileHeader.e_phoff+i*fileHeader.e_phentsize;
		segments[i]->writeHeader(fileData, pos, bigEndian);
	}
	
	for (int i = 0; i < (int)sections.size(); i++)
	{
		int pos = fileHeader.e_shoff+i*fileHeader.e_shentsize;
		sections[i]->writeHeader(fileData, pos, bigEndian);
	}

	fileData.toFile(fileName);
}
コード例 #15
0
void ElfFile::loadProgramHeader(Elf32_Phdr& header, ByteArray& data, int pos)
{
	bool bigEndian = isBigEndian();
	header.p_type   = data.getDoubleWord(pos + 0x00, bigEndian);
	header.p_offset = data.getDoubleWord(pos + 0x04, bigEndian);
	header.p_vaddr  = data.getDoubleWord(pos + 0x08, bigEndian);
	header.p_paddr  = data.getDoubleWord(pos + 0x0C, bigEndian);
	header.p_filesz = data.getDoubleWord(pos + 0x10, bigEndian);
	header.p_memsz  = data.getDoubleWord(pos + 0x14, bigEndian);
	header.p_flags  = data.getDoubleWord(pos + 0x18, bigEndian);
	header.p_align  = data.getDoubleWord(pos + 0x1C, bigEndian);
}
コード例 #16
0
void writeFreqsTable(char* filename, uint32_t* table)
{
	FILE* f = fopen(filename, "wb");
	if(!isBigEndian())
	{
		for(int a = 0; a < table[-1] / sizeof(uint32_t); a ++)
		{
			table[a] = __builtin_bswap32(table[a]);
		}
	}
	fwrite(table, table[-1], 1, f);
	//switch back
	if(!isBigEndian())
	{
		for(int a = 0; a < table[-1] / sizeof(uint32_t); a ++)
		{
			table[a] = __builtin_bswap32(table[a]);
		}
	}
	fclose(f);
}
コード例 #17
0
void ElfFile::loadSectionHeader(Elf32_Shdr& header, ByteArray& data, int pos)
{
	bool bigEndian = isBigEndian();
	header.sh_name      = data.getDoubleWord(pos + 0x00, bigEndian);
	header.sh_type      = data.getDoubleWord(pos + 0x04, bigEndian);
	header.sh_flags     = data.getDoubleWord(pos + 0x08, bigEndian);
	header.sh_addr      = data.getDoubleWord(pos + 0x0C, bigEndian);
	header.sh_offset    = data.getDoubleWord(pos + 0x10, bigEndian);
	header.sh_size      = data.getDoubleWord(pos + 0x14, bigEndian);
	header.sh_link      = data.getDoubleWord(pos + 0x18, bigEndian);
	header.sh_info      = data.getDoubleWord(pos + 0x1C, bigEndian);
	header.sh_addralign = data.getDoubleWord(pos + 0x20, bigEndian);
	header.sh_entsize   = data.getDoubleWord(pos + 0x24, bigEndian);
}
コード例 #18
0
ファイル: MrcFileImpl.cpp プロジェクト: SoumyajitG/VolRoverN
//! Associates this reader with the file given by fileName.
bool MrcFileImpl::attachToFile(const QString& fileName, Mode mode)
{
	QFileInfo fileInfo(fileName);

	// set the mode
	m_OpenMode = mode;

	if (mode == Read) {
		// first check to make sure it exists
		if (!fileInfo.exists()) {
			qDebug("File does not exist");
			return false;
		}

		QString absFilePath = fileInfo.absFilePath();

		m_File.setName(absFilePath);
		if (!m_File.open(QIODevice::ReadOnly | QIODevice::Unbuffered)) {
			qDebug("Error opening file");
			return false;
		}

		if (readHeader(m_File.size())) {
			// success
			m_Attached = true;
			return true;
		}
		else {
			// failure
			close();
			return false;
		}
	}
	else { // mode == Write
		// open the file
		QString absFilePath = fileInfo.absFilePath();

		m_File.setName(absFilePath);
		if (!m_File.open(QIODevice::WriteOnly | QIODevice::Unbuffered)) {
			qDebug("Error opening file");
			return false;
		}

		m_Attached = true;
		if (isBigEndian())
			m_MustSwap = true;
	}

	return m_Attached;
}
コード例 #19
0
ファイル: nitrofile.cpp プロジェクト: bsmr-games/xoreos
Common::SeekableSubReadStreamEndian *NitroFile::open(Common::SeekableReadStream *stream) {
	const size_t begin = stream->pos();
	const size_t end   = stream->size();

	bool bigEndian = false;
	try {
		bigEndian = isBigEndian(*stream);
	} catch (...) {
		delete stream;
		throw;
	}

	return new Common::SeekableSubReadStreamEndian(stream, begin, end, bigEndian, true);
}
コード例 #20
0
ファイル: reverse_endianness.cpp プロジェクト: fkfc/lobots
float ReverseFloat( const float inFloat ) {
   if (isBigEndian()) {
      float retVal;
      char *floatToConvert = ( char* ) & inFloat;
      char *returnFloat = ( char* ) & retVal;

      // swap the bytes into a temporary buffer
      returnFloat[0] = floatToConvert[3];
      returnFloat[1] = floatToConvert[2];
      returnFloat[2] = floatToConvert[1];
      returnFloat[3] = floatToConvert[0];

      return retVal;
   } else return inFloat;
}
コード例 #21
0
ファイル: reverse_endianness.cpp プロジェクト: fkfc/lobots
int ReverseInt( const int inInt ) {
   if (isBigEndian()) {
      int retVal;
      char *intToConvert = ( char* ) & inInt;
      char *returnInt = ( char* ) & retVal;

      // swap the bytes into a temporary buffer
      returnInt[0] = intToConvert[3];
      returnInt[1] = intToConvert[2];
      returnInt[2] = intToConvert[1];
      returnInt[3] = intToConvert[0];

      return retVal;
   } else return inInt;
}
コード例 #22
0
ファイル: utils.cpp プロジェクト: nnen/cppapp
uint32_t hostToLittleEndian(uint32_t value)
{
	if (!isBigEndian()) return value;
	
	union {
		char     raw[sizeof(uint32_t)];
		uint32_t value;
	} newValue;
	
	newValue.value = value;
	#define SWAP(a, b) { char c = (a); (a) = (b); (b) = c; }
	SWAP(newValue.raw[0], newValue.raw[3])
	SWAP(newValue.raw[1], newValue.raw[2])
	#undef SWAP
	return newValue.value;
}
コード例 #23
0
bool ElfFile::getSymbol(Elf32_Sym& symbol, size_t index)
{
	if (symTab == NULL)
		return false;

	ByteArray &data = symTab->getData();
	int pos = index*sizeof(Elf32_Sym);
	bool bigEndian = isBigEndian();
	symbol.st_name  = data.getDoubleWord(pos + 0x00, bigEndian);
	symbol.st_value = data.getDoubleWord(pos + 0x04, bigEndian);
	symbol.st_size  = data.getDoubleWord(pos + 0x08, bigEndian);
	symbol.st_info  = data[pos + 0x0C];
	symbol.st_other = data[pos + 0x0D];
	symbol.st_shndx = data.getWord(pos + 0x0E, bigEndian);

	return true;
}
コード例 #24
0
uint32_t* readFreqsTable(char* filename)
{
	FILE* f = fopen(filename, "rb");
	uint64_t tableBytes = getFileSize_64(filename);
	uint32_t* table = mallocClean(tableBytes + sizeof(uint32_t));
	table[0] = tableBytes;
	fread(table + 1, tableBytes, 1, f);
	if(!isBigEndian())
	{
		for(int a = 0; a < tableBytes / sizeof(uint32_t); a ++)
		{
			table[a + 1] = __builtin_bswap32(table[a + 1]);
		}
	}
	fclose(f);
	return (uint32_t*) table + 1;
}
コード例 #25
0
void ElfFile::loadElfHeader()
{
	memcpy(fileHeader.e_ident, &fileData[0], sizeof(fileHeader.e_ident));
	bool bigEndian = isBigEndian();
	fileHeader.e_type = fileData.getWord(0x10, bigEndian);
	fileHeader.e_machine = fileData.getWord(0x12, bigEndian);
	fileHeader.e_version = fileData.getDoubleWord(0x14, bigEndian);
	fileHeader.e_entry = fileData.getDoubleWord(0x18, bigEndian);
	fileHeader.e_phoff = fileData.getDoubleWord(0x1C, bigEndian);
	fileHeader.e_shoff = fileData.getDoubleWord(0x20, bigEndian);
	fileHeader.e_flags = fileData.getDoubleWord(0x24, bigEndian);
	fileHeader.e_ehsize = fileData.getWord(0x28, bigEndian);
	fileHeader.e_phentsize = fileData.getWord(0x2A, bigEndian);
	fileHeader.e_phnum = fileData.getWord(0x2C, bigEndian);
	fileHeader.e_shentsize = fileData.getWord(0x2E, bigEndian);
	fileHeader.e_shnum = fileData.getWord(0x30, bigEndian);
	fileHeader.e_shstrndx = fileData.getWord(0x32, bigEndian);
}
コード例 #26
0
ファイル: reverse_endianness.cpp プロジェクト: fkfc/lobots
double ReverseDouble( const double inDouble ) {
   if (isBigEndian()) {
      double retVal;
      char *doubleToConvert = ( char* ) & inDouble;
      char *returnDouble = ( char* ) & retVal;

      // swap the bytes into a temporary buffer
      returnDouble[0] = doubleToConvert[7];
      returnDouble[1] = doubleToConvert[6];
      returnDouble[2] = doubleToConvert[5];
      returnDouble[3] = doubleToConvert[4];
      returnDouble[4] = doubleToConvert[3];
      returnDouble[5] = doubleToConvert[2];
      returnDouble[6] = doubleToConvert[1];
      returnDouble[7] = doubleToConvert[0];
     
      return retVal;
   } else return inDouble;
}
コード例 #27
0
ファイル: memory.c プロジェクト: akonecki/CodingProjects
int main(int argc, char * argv[]) {
    int * intPtr = NULL;
    volatile int number = 0;
    treenode_t * root = NULL;

    printf("intPtr is at address %p\n", &intPtr);
    malloc_wrapper((void *)&intPtr, 4);
    if (intPtr == NULL) {
        printf("could not malloc\n");
        return -1;
    }

    printf("intPtr is at address %p\n", &intPtr);
    printf("intPtr is pointing to %p\n", intPtr);

    free (intPtr);

    printf("is big endian result : %08x\n", isBigEndian());

    insert(&root, 1);
    printf("root is %p\n", root);
    traversal(root);
    insert(&root, 2);
    traversal(root);
    insert(&root, 3);
    traversal(root);
    insert(&root, 1);
    traversal(root);
    insert(&root, 2);
    traversal(root);
    insert(&root, 3);
    traversal(root);
    insert(&root, -1);
    traversal(root);
    insert(&root, 0);
    traversal(root);

    printf("\n");
    deleteTree(&root);

    return 0;
}
コード例 #28
0
ファイル: grfmt_png.cpp プロジェクト: 2693/opencv
bool  PngEncoder::write( const Mat& img, const vector<int>& params )
{
    png_structp png_ptr = png_create_write_struct( PNG_LIBPNG_VER_STRING, 0, 0, 0 );
    png_infop info_ptr = 0;
    FILE* f = 0;
    int y, width = img.cols, height = img.rows;
    int depth = img.depth(), channels = img.channels();
    bool result = false;
    AutoBuffer<uchar*> buffer;

    if( depth != CV_8U && depth != CV_16U )
        return false;

    if( png_ptr )
    {
        info_ptr = png_create_info_struct( png_ptr );

        if( info_ptr )
        {
            if( setjmp( png_jmpbuf ( png_ptr ) ) == 0 )
            {
                if( m_buf )
                {
                    png_set_write_fn(png_ptr, this,
                        (png_rw_ptr)writeDataToBuf, (png_flush_ptr)flushBuf);
                }
                else
                {
                    f = fopen( m_filename.c_str(), "wb" );
                    if( f )
                        png_init_io( png_ptr, f );
                }

                int compression_level = -1; // Invalid value to allow setting 0-9 as valid
                int compression_strategy = Z_RLE; // Default strategy
                bool isBilevel = false;

                for( size_t i = 0; i < params.size(); i += 2 )
                {
                    if( params[i] == CV_IMWRITE_PNG_COMPRESSION )
                    {
                        compression_level = params[i+1];
                        compression_level = MIN(MAX(compression_level, 0), Z_BEST_COMPRESSION);
                    }
                    if( params[i] == CV_IMWRITE_PNG_STRATEGY )
                    {
                        compression_strategy = params[i+1];
                        compression_strategy = MIN(MAX(compression_strategy, 0), Z_FIXED);
                    }
                    if( params[i] == CV_IMWRITE_PNG_BILEVEL )
                    {
                        isBilevel = params[i+1] != 0;
                    }
                }

                if( m_buf || f )
                {
                    if( compression_level >= 0 )
                    {
                        png_set_compression_level( png_ptr, compression_level );
                    }
                    else
                    {
                        // tune parameters for speed
                        // (see http://wiki.linuxquestions.org/wiki/Libpng)
                        png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_FILTER_SUB);
                        png_set_compression_level(png_ptr, Z_BEST_SPEED);
                    }
                    png_set_compression_strategy(png_ptr, compression_strategy);

                    png_set_IHDR( png_ptr, info_ptr, width, height, depth == CV_8U ? isBilevel?1:8 : 16,
                        channels == 1 ? PNG_COLOR_TYPE_GRAY :
                        channels == 3 ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGBA,
                        PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
                        PNG_FILTER_TYPE_DEFAULT );

                    png_write_info( png_ptr, info_ptr );

                    if (isBilevel)
                        png_set_packing(png_ptr);

                    png_set_bgr( png_ptr );
                    if( !isBigEndian() )
                        png_set_swap( png_ptr );

                    buffer.allocate(height);
                    for( y = 0; y < height; y++ )
                        buffer[y] = img.data + y*img.step;

                    png_write_image( png_ptr, buffer );
                    png_write_end( png_ptr, info_ptr );

                    result = true;
                }
            }
        }
    }

    png_destroy_write_struct( &png_ptr, &info_ptr );
    if(f) fclose( f );

    return result;
}
コード例 #29
0
ファイル: grfmt_png.cpp プロジェクト: 2693/opencv
bool  PngDecoder::readData( Mat& img )
{
    bool result = false;
    AutoBuffer<uchar*> _buffer(m_height);
    uchar** buffer = _buffer;
    int color = img.channels() > 1;
    uchar* data = img.data;
    int step = (int)img.step;

    if( m_png_ptr && m_info_ptr && m_end_info && m_width && m_height )
    {
        png_structp png_ptr = (png_structp)m_png_ptr;
        png_infop info_ptr = (png_infop)m_info_ptr;
        png_infop end_info = (png_infop)m_end_info;

        if( setjmp( png_jmpbuf ( png_ptr ) ) == 0 )
        {
            int y;

            if( img.depth() == CV_8U && m_bit_depth == 16 )
                png_set_strip_16( png_ptr );
            else if( !isBigEndian() )
                png_set_swap( png_ptr );

            if(img.channels() < 4)
            {
                /* observation: png_read_image() writes 400 bytes beyond
                 * end of data when reading a 400x118 color png
                 * "mpplus_sand.png".  OpenCV crashes even with demo
                 * programs.  Looking at the loaded image I'd say we get 4
                 * bytes per pixel instead of 3 bytes per pixel.  Test
                 * indicate that it is a good idea to always ask for
                 * stripping alpha..  18.11.2004 Axel Walthelm
                 */
                 png_set_strip_alpha( png_ptr );
            }

            if( m_color_type == PNG_COLOR_TYPE_PALETTE )
                png_set_palette_to_rgb( png_ptr );

            if( m_color_type == PNG_COLOR_TYPE_GRAY && m_bit_depth < 8 )
#if (PNG_LIBPNG_VER_MAJOR*10000 + PNG_LIBPNG_VER_MINOR*100 + PNG_LIBPNG_VER_RELEASE >= 10209) || \
    (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR == 0 && PNG_LIBPNG_VER_RELEASE >= 18)
                png_set_expand_gray_1_2_4_to_8( png_ptr );
#else
                png_set_gray_1_2_4_to_8( png_ptr );
#endif

            if( CV_MAT_CN(m_type) > 1 && color )
                png_set_bgr( png_ptr ); // convert RGB to BGR
            else if( color )
                png_set_gray_to_rgb( png_ptr ); // Gray->RGB
            else
                png_set_rgb_to_gray( png_ptr, 1, 0.299, 0.587 ); // RGB->Gray

            png_read_update_info( png_ptr, info_ptr );

            for( y = 0; y < m_height; y++ )
                buffer[y] = data + y*step;

            png_read_image( png_ptr, buffer );
            png_read_end( png_ptr, end_info );

            result = true;
        }
    }

    close();
    return result;
}
コード例 #30
0
HAL_STATUS
ath_hal_v4kEepromAttach(struct ath_hal *ah)
{
#define	NW(a)	(sizeof(a) / sizeof(uint16_t))
    HAL_EEPROM_v4k *ee = AH_PRIVATE(ah)->ah_eeprom;
    uint16_t *eep_data, magic;
    HAL_BOOL need_swap;
    u_int w, off, len;
    uint32_t sum;

    HALASSERT(ee == AH_NULL);
    /*
     * Don't check magic if we're supplied with an EEPROM block,
     * typically this is from Howl but it may also be from later
     * boards w/ an embedded WMAC.
     */
    if (ah->ah_eepromdata == NULL) {
        if (!ath_hal_eepromRead(ah, AR5416_EEPROM_MAGIC_OFFSET, &magic)) {
            HALDEBUG(ah, HAL_DEBUG_ANY,
                     "%s Error reading Eeprom MAGIC\n", __func__);
            return HAL_EEREAD;
        }
    }
    HALDEBUG(ah, HAL_DEBUG_ATTACH, "%s Eeprom Magic = 0x%x\n",
             __func__, magic);
    if (magic != AR5416_EEPROM_MAGIC) {
        HALDEBUG(ah, HAL_DEBUG_ANY, "Bad magic number\n");
        return HAL_EEMAGIC;
    }

    ee = ath_hal_malloc(sizeof(HAL_EEPROM_v4k));
    if (ee == AH_NULL) {
        /* XXX message */
        return HAL_ENOMEM;
    }

    eep_data = (uint16_t *)&ee->ee_base;
    for (w = 0; w < NW(struct ar5416eeprom_4k); w++) {
        off = owl_eep_start_loc + w;	/* NB: AP71 starts at 0 */
        if (!ath_hal_eepromRead(ah, off, &eep_data[w])) {
            HALDEBUG(ah, HAL_DEBUG_ANY,
                     "%s eeprom read error at offset 0x%x\n",
                     __func__, off);
            return HAL_EEREAD;
        }
    }
    /* Convert to eeprom native eeprom endian format */
    /*
     * XXX this is likely incorrect but will do for now
     * XXX to get embedded boards working.
     */
    if (ah->ah_eepromdata == NULL && isBigEndian()) {
        for (w = 0; w < NW(struct ar5416eeprom_4k); w++)
            eep_data[w] = __bswap16(eep_data[w]);
    }

    /*
     * At this point, we're in the native eeprom endian format
     * Now, determine the eeprom endian by looking at byte 26??
     */
    need_swap = ((ee->ee_base.baseEepHeader.eepMisc & AR5416_EEPMISC_BIG_ENDIAN) != 0) ^ isBigEndian();
    if (need_swap) {
        HALDEBUG(ah, HAL_DEBUG_ATTACH | HAL_DEBUG_EEPROM,
                 "Byte swap EEPROM contents.\n");
        len = __bswap16(ee->ee_base.baseEepHeader.length);
    } else {
        len = ee->ee_base.baseEepHeader.length;
    }
    len = AH_MIN(len, sizeof(struct ar5416eeprom_4k)) / sizeof(uint16_t);

    /* Apply the checksum, done in native eeprom format */
    /* XXX - Need to check to make sure checksum calculation is done
     * in the correct endian format.  Right now, it seems it would
     * cast the raw data to host format and do the calculation, which may
     * not be correct as the calculation may need to be done in the native
     * eeprom format
     */
    sum = 0;
    for (w = 0; w < len; w++) {
        sum ^= eep_data[w];
    }
    /* Check CRC - Attach should fail on a bad checksum */
    if (sum != 0xffff) {
        HALDEBUG(ah, HAL_DEBUG_ANY,
                 "Bad EEPROM checksum 0x%x (Len=%u)\n", sum, len);
        return HAL_EEBADSUM;
    }

    if (need_swap)
        eepromSwap(&ee->ee_base);	/* byte swap multi-byte data */

    /* swap words 0+2 so version is at the front */
    magic = eep_data[0];
    eep_data[0] = eep_data[2];
    eep_data[2] = magic;

    HALDEBUG(ah, HAL_DEBUG_ATTACH | HAL_DEBUG_EEPROM,
             "%s Eeprom Version %u.%u\n", __func__,
             owl_get_eep_ver(ee), owl_get_eep_rev(ee));

    /* NB: must be after all byte swapping */
    if (owl_get_eep_ver(ee) != AR5416_EEP_VER) {
        HALDEBUG(ah, HAL_DEBUG_ANY,
                 "Bad EEPROM version 0x%x\n", owl_get_eep_ver(ee));
        return HAL_EEBADSUM;
    }

    v4kEepromReadCTLInfo(ah, ee);		/* Get CTLs */

    AH_PRIVATE(ah)->ah_eeprom = ee;
    AH_PRIVATE(ah)->ah_eeversion = ee->ee_base.baseEepHeader.version;
    AH_PRIVATE(ah)->ah_eepromDetach = v4kEepromDetach;
    AH_PRIVATE(ah)->ah_eepromGet = v4kEepromGet;
    AH_PRIVATE(ah)->ah_eepromSet = v4kEepromSet;
    AH_PRIVATE(ah)->ah_getSpurChan = v4kEepromGetSpurChan;
    AH_PRIVATE(ah)->ah_eepromDiag = v4kEepromDiag;
    return HAL_OK;
#undef NW
}