/*  一つ分の受信データを解析し、AXIS Neuron の BVH データならば格納 */
bool PacketParserNeuron::Read(const uint8* raw, const int32 length, UMocapPose* pose)
{
	if (!CheckHeader(raw, length)) return false;

	/* ヘッダーを読んだ時点でユーザーIDが分るので設定 */
	pose->UserId = this->userId;

	/* 読み込まれないボーンを空にする */
	for (int i = 0; i < (sizeof(EmptyBoneIndices) / sizeof(EmptyBoneIndices[0])); i++) {
		pose->BoneRotations[EmptyBoneIndices[i]] = FQuat(0, 0, 0, 1);
	}

	/* 読込開始 */
	int index = 64;

	/*  Refecence ありの場合、float16 × 6 がヘッダー後に存在するのでスキップ */
	if (this->hasReference) index += 24;

	/*  最初はルート位置が届く */
	FVector position = GetPosition(raw, index);
	pose->OriginalRootPosition = position;
	index += 12;

	/*  各関節の角度 */
	for (int i = 0; i < BoneCount; i++) {
		ProcessSegment(raw, i, index, pose);
		index += (this->hasDisplacement ? 24 : 12);
	}

	return true;
}
Exemplo n.º 2
0
bool TiffPlugin::LoadDoc(cpcl::IOStream *input, plcl::Doc **r) {
	cpcl::IOStream *input_ = input->Clone();
	if (!input_) {
		cpcl::Error(cpcl::StringPieceFromLiteral("TiffPlugin::Load(): IOStream::Clone() fails"));
		return false;
	}
	std::auto_ptr<cpcl::IOStream> input_guard(input_);
	
	if (!CheckHeader(input_guard.get()))
		return false;

	input_guard->Seek(0, SEEK_SET, NULL);
	TiffStuff tiff_stuff(input_guard.get());
	if (!tiff_stuff)
		throw tiff_exception("TiffPlugin::Load(): unable to create and initialize libtiff handler");

	TIFF *tif = tiff_stuff.tif;

	unsigned int page_count = 1;
	while (TIFFReadDirectory(tif))
		++page_count;

	std::auto_ptr<TiffDoc> doc(new TiffDoc(input_guard, page_count));
	if (r)
		*r = doc.release();

	return true;
}
int32_t FixedMemPool::Init(void* mem, uint32_t max_node_num, size_t node_size, bool check_header) {
    if (!mem) {
        return -1;
    }

    m_header = (MemHeader*)mem;

    if (!check_header) {
        //init head
        m_header->max_size = GetAllocSize(max_node_num, node_size);
        m_header->max_node_num = max_node_num;
        //we use the beginning of the memory pool to as head infomation
        m_header->used_size = sizeof(MemHeader);
        m_header->used_node_num = 0;
        //block size is based on node size aligned by 8 bytes
        m_header->block_size = GetBlockSize(node_size);
        //no block is freed
        m_header->free_list_offset = kInvalidPointer;

        m_data = (char*)m_header + sizeof(MemHeader);
    } else {
        if (!CheckHeader(max_node_num, node_size, m_header)) {
            snprintf(m_error_msg, sizeof(m_error_msg), "Memory pool head check error!");
            return -1;
        }

        m_data = (char*)m_header + sizeof(MemHeader);
    }

    return 0;
}
Exemplo n.º 4
0
  void PngReader::ReadFromMemory(const void* buffer,
                                 size_t size)
  {
    if (size < 8)
    {
      throw OrthancException(ErrorCode_BadFileFormat);
    }

    CheckHeader(buffer);

    PngRabi rabi;

    if (setjmp(png_jmpbuf(rabi.png_)))
    {
      rabi.Destruct();
      throw OrthancException(ErrorCode_BadFileFormat);
    }

    MemoryBuffer tmp;
    tmp.buffer_ = reinterpret_cast<const uint8_t*>(buffer) + 8;  // We skip the header
    tmp.size_ = size - 8;
    tmp.pos_ = 0;
    tmp.ok_ = true;

    png_set_read_fn(rabi.png_, &tmp, PngRabi::MemoryCallback);

    Read(rabi);

    if (!tmp.ok_)
    {
      throw OrthancException(ErrorCode_BadFileFormat);
    }
  }
Exemplo n.º 5
0
void BlockManager::FlushHeader()
{
    CheckHeader();
    m_pFile->Seek(offset_type(0), IFile::S_Begin);

    m_pFile->Write(&m_Header, offset_type(sizeof(m_Header)));
}
Exemplo n.º 6
0
/*****************************************************************************
 * ParseTags: check if ID3/APE tags at common locations.
 ****************************************************************************/
static int ParseTags( vlc_object_t *p_this )
{
    demux_meta_t *p_demux_meta = (demux_meta_t *)p_this;
    demux_t      *p_demux = (demux_t *)p_demux_meta->p_demux;
    bool    b_seekable;
    int64_t       i_init;

    msg_Dbg( p_demux_meta, "checking for ID3v1/2 and APEv1/2 tags" );
    stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
    if( !b_seekable )
        return VLC_EGENERIC;

    i_init = stream_Tell( p_demux->s );

    TAB_INIT( p_demux_meta->i_attachments, p_demux_meta->attachments );
    p_demux_meta->p_meta = NULL;

    /* */
    CheckFooter( p_demux_meta );

    /* */
    CheckHeader( p_demux_meta );

    /* Restore position
     *  Demuxer will not see tags at the start as src/input/demux.c skips it
     *  for them
     */
    stream_Seek( p_demux->s, i_init );
    if( !p_demux_meta->p_meta && p_demux_meta->i_attachments <= 0 )
        return VLC_EGENERIC;
    return VLC_SUCCESS;
}
Exemplo n.º 7
0
void XFileLoader::Load(string filename)
{	
	m_nodes.clear();
	m_meshes.clear();
	m_materials.clear();
	m_materialLookup.clear();
	ifstream s;
	s.open(filename);
	if (!s)
		throw "Could not open file!";
	CheckHeader(s);
	int prevSybling = -1;
	while (true)
	{
		XFileToken token = XFileToken::NextToken(s);
		if (token.m_type == XFileToken::Identifier)
		{
			if (token.m_content == "Frame")
				prevSybling = ReadSceneNode(s, prevSybling);
			else if (token.m_content == "Mesh")
				ReadMesh(s);
			else
				SkipDataObject(s);
		}
		else if (token.m_type == XFileToken::LeftBrace)
			SkipDataReference(s);
		else if (token.m_type == XFileToken::None)
			break;
        else
            THROW_EXCEPTION_T("Parsing error", ParsingException);
	}
	s.close();
}
Exemplo n.º 8
0
bool PdfPlugin::LoadDoc(cpcl::IOStream *input, plcl::Doc **r) {
	cpcl::IOStream *input_ = input->Clone();
	if (!input_) {
		cpcl::Error(cpcl::StringPieceFromLiteral("PdfPlugin::LoadDoc(): IOStream::Clone() fails"));
		return false;
	}
	std::tr1::shared_ptr<cpcl::IOStream> input_guard(input_);

	if (!CheckHeader(input_guard.get()))
		return false;
	input_guard->Seek(0, SEEK_SET, NULL);

	GooString *owner_pw(0), *user_pw(0);
	Object obj; obj.initNull();
	std::auto_ptr<BaseStream> input_stream(new WrapperStream(input_guard, 0, gFalse, 0, &obj));
	std::auto_ptr<PDFDoc> doc(new PDFDoc(input_stream.get(), owner_pw, user_pw));
	// if ctor throw, then PDFDoc.dtor i.e. ~PDFDoc() {...} NOT called, so no delete input_stream, and its safe
	input_stream.release();

	if (doc->isOk() != gTrue) {
		cpcl::Error(cpcl::StringPieceFromLiteral("PdfPlugin::LoadDoc(): unable to open pdf document"));
		return false;
	}

	std::auto_ptr<PdfDoc> pdf_doc(new PdfDoc(doc->getNumPages()));
	pdf_doc->doc.reset(doc.release()); // also because class use dynamic resources, its safe to release pointer, but not pass in ctor
	// because ctor may fail for example if memory allocation fails, and in that case resources become abadoned
	// yeah, BUT if pass reference to auto_ptr, then ownership transfered only AFTER memory allocation to object and BEFORE user ctor
	// so, if memory allocation fails, then ownership not yet transfered and auto_ptr<> doc free resources
	// in other case, if user ctor failed, then ownership transfered to auto_ptr<> PdfDoc::doc, and all constructed class fields be deleted, without user dtor(that not called anyway)

	if (r)
		*r = pdf_doc.release();
	return true;
}
Exemplo n.º 9
0
void BlockManager::LoadExist(offset_type blocksize)
{
    m_pFile->Seek(offset_type(0), IFile::S_Begin);

    offset_type sizetoread;
    sizetoread.offset = sizeof(m_Header);
    m_pFile->Read(&m_Header, sizetoread);
    assert(m_Header.BlockSize == blocksize && "Block Size Error");
    CheckHeader();
}
Exemplo n.º 10
0
offset_type BlockManager::AllocNewBlock()
{
    CheckHeader();
    assert(m_Header.Unused.offset < 0);
    offset_type blockid = m_Header.Blocks;
    ++m_Header.Blocks.offset;
    m_pFile->ReserveSpace(CalcOffset(m_Header.Blocks));
    FlushHeader();
    return blockid;
}
Exemplo n.º 11
0
int Assimp_CompareDump (const char* const* params, unsigned int num)
{
	// --help
	if ((num == 1 && !strcmp( params[0], "-h")) || !strcmp( params[0], "--help") || !strcmp( params[0], "-?") ) {
		printf("%s",AICMD_MSG_CMPDUMP_HELP);
		return 0;
	}

	// assimp cmpdump actual expected
	if (num < 1) {
		std::cout << "assimp cmpdump: Invalid number of arguments. "
			"See \'assimp cmpdump --help\'\r\n" << std::endl;
		return 1;
	}

	if(!strcmp(params[0],params[1])) {
		std::cout << "assimp cmpdump: same file, same content." << std::endl;
		return 0;
	}

	FILE* actual = fopen(params[0],"rb"), *expected = fopen(params[1],"rb");
	if (!actual) {
		std::cout << "assimp cmpdump: Failure reading ACTUAL data from " << 
			params[0]  << std::endl;
		return -5;
	}
	if (!expected) {
		std::cout << "assimp cmpdump: Failure reading EXPECT data from " << 
			params[1]  << std::endl;
		return -6;
	}

	comparer_context comp(actual,expected);
	try {
		CheckHeader(comp);
		CompareOnTheFly(comp);
	}
	catch(const compare_fails_exception& ex) {
		printf("%s",ex.what());
		return -1;
	}
	catch(...) {
		// we don't bother checking too rigourously here, so
		// we might end up here ...
		std::cout << "Unknown failure, are the input files well-defined?";
		return -3;
	}

	std::cout << "Success (totally " << std::dec << comp.get_num_chunks() << 
		" chunks)" << std::endl;

	return 0;
}
Exemplo n.º 12
0
offset_type BlockManager::AllocExistBlock()
{
    CheckHeader();
    assert(m_Header.Unused.offset >= 0);
    offset_type result = m_Header.Unused;
    offset_type header;
    ReadEmptyBlockHeader(result, header);
    m_Header.Unused = header;
    header = result;
    ZeroBlock(result);
    FlushHeader();
    return result;
}
Exemplo n.º 13
0
bool CPkt30viewDoc::OpenFile(LPCTSTR psName)
{
	if (!m_FileMap.Open(psName, false))
		throw (_T("Error opening file"));

	if (!CheckHeader())
		throw (_T("Invalid header"));

	BuildIndex();
	LoadOpcodes();
	LoadParsers();

	return true;
}
Exemplo n.º 14
0
int main(int argc, char **argv)
{

    if (argc != 2)
    {
        fprintf(stderr, "\nusage opf_check <input ASCII file in the LibOPF format>\nNote that the input file for opf_check must be a text file.\nUse opf2txt to convert your OPF binary file into a text file.\n");
        exit(-1);
    }
    FILE *fp = NULL;
    char header[HEADERSIZE], line[LINESIZE], OK = 1;
    int nsamples, nlabels, nfeats, i;
    char *result = NULL;

    fp = fopen(argv[1], "r");
    if (!fp)
    {
        fprintf(stderr, "\nunable to open file %s\n", argv[1]);
        exit(-1);
    }

    /* it checks the header */
    result = fgets(header, HEADERSIZE, fp);
    if (!CheckHeader(header, &nsamples, &nlabels, &nfeats))
    {
        fprintf(stderr, "\nAn error has been found at line 1 (HEADER).");
        fprintf(stderr, "\nThe header should contain only three integers:");
        fprintf(stderr, "\n<#samples> <#labels> <#features>\n");
        OK = 0;
    }

    /* it checks the remaining file */
    for (i = 1; i <= nsamples; i++)
    {
        result = fgets(line, LINESIZE, fp);
        if (!CheckLine(line, nlabels, nfeats, i))
        {
            fprintf(stderr, "\nAn error has been found at line %d\n", i + 1);
            OK = 0;
            break;
        }
    }
    fclose(fp);
    if (result)
        result++;

    if (OK)
        fprintf(stderr, "\nThis file is in the proper format. Enjoy.\n");

    return 1;
}
Exemplo n.º 15
0
bool LoadHeader(rFile& pkg_f, PKGHeader* m_header)
{
	pkg_f.Seek(0);
	
	if (pkg_f.Read(m_header, sizeof(PKGHeader)) != sizeof(PKGHeader)) {
		LOG_ERROR(LOADER, "PKG: Package file is too short!");
		return false;
	}

	if (!CheckHeader(pkg_f, m_header))
		return false;

	return true;
}
Exemplo n.º 16
0
////////////////////////////////////////////////////////////////////////////////
// Set an entry and send out update events to all listeners.
int LocalBB::ProcessSetEntryMessage(QueuePointer &resp_queue, player_msghdr * hdr, void * data)
{
	if (!CheckHeader(hdr))
		return -1;

	player_blackboard_entry_t *request = reinterpret_cast<player_blackboard_entry_t*>(data);
	BlackBoardEntry entry = FromPlayerBlackBoardEntry(*request);

	SetEntry(entry);

	// Send out update events to other listening devices for key group combinations
	std::vector<QueuePointer> &devices = listeners[entry.group][entry.key];

	for (std::vector<QueuePointer>::iterator itr=devices.begin(); itr != devices.end(); itr++)
	{
		QueuePointer device_queue = (*itr);
		this->Publish(this->device_addr,
			device_queue,
			PLAYER_MSGTYPE_DATA,
			PLAYER_BLACKBOARD_DATA_UPDATE,
			data,
			hdr->size,
			NULL);
	}

	// Send out update events to just groups
	std::vector<QueuePointer> &devices_groups = group_listeners[entry.group];
	for (std::vector<QueuePointer>::iterator itr=devices_groups.begin(); itr != devices_groups.end(); itr++)
	{
		QueuePointer device_queue = (*itr);
		this->Publish(this->device_addr,
			device_queue,
			PLAYER_MSGTYPE_DATA,
			PLAYER_BLACKBOARD_DATA_UPDATE,
			data,
			hdr->size,
			NULL);
	}

	// Send back an empty ack
	this->Publish(this->device_addr,
		resp_queue,
		PLAYER_MSGTYPE_RESP_ACK,
		PLAYER_BLACKBOARD_REQ_SET_ENTRY,
		NULL,
		0,
		NULL);

	return 0;
}
Exemplo n.º 17
0
bool LoadHeader(wxFile& pkg_f, PKGHeader* m_header)
{
	pkg_f.Seek(0);
	
	if (pkg_f.Read(m_header, sizeof(PKGHeader)) != sizeof(PKGHeader)) {
		ConLog.Error("PKG: Package file is too short!");
		return false;
	}

	if (!CheckHeader(pkg_f, m_header))
		return false;

	return true;
}
Exemplo n.º 18
0
////////////////////////////////////////////////////////////////////////////////
// Subscribe a device to a group. Send out data messages for the current group entries.
int LocalBB::ProcessSubscribeGroupMessage(QueuePointer &resp_queue, player_msghdr * hdr, void * data)
{
	if (!CheckHeader(hdr))
			return -1;

	// Add the device to the listeners map
	player_blackboard_entry_t *request = reinterpret_cast<player_blackboard_entry_t*>(data);
	std::vector<BlackBoardEntry> entries = SubscribeGroup(request->group, resp_queue, hdr->addr);

	for (std::vector<BlackBoardEntry>::iterator itr = entries.begin(); itr != entries.end(); itr++)
	{
		BlackBoardEntry current_value = *itr;
		player_blackboard_entry_t response = ToPlayerBlackBoardEntry(current_value);
		size_t response_size = sizeof(player_blackboard_entry_t) + response.key_count + response.group_count + response.data_count;

		// Publish the blackboard entries
		this->Publish(this->device_addr,
			resp_queue,
			PLAYER_MSGTYPE_DATA,
			PLAYER_BLACKBOARD_DATA_UPDATE,
			&response,
			response_size,
			NULL);

		if (response.key)
		{
			delete [] response.key;
		}
		if (response.group)
		{
			delete [] response.group;
		}
		if (response.data)
		{
			delete [] response.data;
		}
	}

	// Then send an empty ack
	this->Publish(
		this->device_addr,
		resp_queue,
		PLAYER_MSGTYPE_RESP_ACK,
		PLAYER_BLACKBOARD_REQ_SUBSCRIBE_TO_GROUP,
		NULL,
		0,
		NULL);

	return 0;
}
Exemplo n.º 19
0
bool CPDF_DataAvail::CheckDocStatus(DownloadHints* pHints) {
  switch (m_docStatus) {
    case PDF_DATAAVAIL_HEADER:
      return CheckHeader(pHints);
    case PDF_DATAAVAIL_FIRSTPAGE:
      return CheckFirstPage(pHints);
    case PDF_DATAAVAIL_HINTTABLE:
      return CheckHintTables(pHints);
    case PDF_DATAAVAIL_END:
      return CheckEnd(pHints);
    case PDF_DATAAVAIL_CROSSREF:
      return CheckCrossRef(pHints);
    case PDF_DATAAVAIL_CROSSREF_ITEM:
      return CheckCrossRefItem(pHints);
    case PDF_DATAAVAIL_CROSSREF_STREAM:
      return CheckAllCrossRefStream(pHints);
    case PDF_DATAAVAIL_TRAILER:
      return CheckTrailer(pHints);
    case PDF_DATAAVAIL_TRAILER_APPEND:
      return CheckTrailerAppend(pHints);
    case PDF_DATAAVAIL_LOADALLCROSSREF:
      return LoadAllXref(pHints);
    case PDF_DATAAVAIL_LOADALLFILE:
      return LoadAllFile(pHints);
    case PDF_DATAAVAIL_ROOT:
      return CheckRoot(pHints);
    case PDF_DATAAVAIL_INFO:
      return CheckInfo(pHints);
    case PDF_DATAAVAIL_ACROFORM:
      return CheckAcroForm(pHints);
    case PDF_DATAAVAIL_PAGETREE:
      if (m_bTotalLoadPageTree)
        return CheckPages(pHints);
      return LoadDocPages(pHints);
    case PDF_DATAAVAIL_PAGE:
      if (m_bTotalLoadPageTree)
        return CheckPage(pHints);
      m_docStatus = PDF_DATAAVAIL_PAGE_LATERLOAD;
      return true;
    case PDF_DATAAVAIL_ERROR:
      return LoadAllFile(pHints);
    case PDF_DATAAVAIL_PAGE_LATERLOAD:
      m_docStatus = PDF_DATAAVAIL_PAGE;
    default:
      m_bDocAvail = true;
      return true;
  }
}
Exemplo n.º 20
0
int GetAudioLength(const char *filename) {
  FILE *fp = fopen(filename, "rb");
  if (NULL == fp) {
    return 0;
  }

  if (0 == CheckHeader(fp)) {
    fclose(fp);
    return -1;
  }

  char data_check[5] = { 0 };
  data_check[4] = '\0';
  unsigned char for_int_number[4];

  // Quantization
  fseek(fp, 10, SEEK_CUR);
  fread(for_int_number, 1, 2, fp);
  int nbit = for_int_number[0];

  while (0 != fread(data_check, 1, 1, fp)) {
    if ('d' == data_check[0]) {
      fread(&data_check[1], 1, 3, fp);
      if (0 != strcmp(data_check, "data"))
        fseek(fp, -3, SEEK_CUR);
      else
        break;
    }
  }
  if (0 != strcmp(data_check, "data")) {
    fclose(fp);
    return -1;
  }

  fread(for_int_number, 1, 4, fp);  // "data"
  fclose(fp);

  int wav_length = 0;
  for (int i = 3; i >= 0; --i)
    wav_length = wav_length * 256 + for_int_number[i];
  wav_length /= (nbit / 8);

  return wav_length;
}
Exemplo n.º 21
0
////////////////////////////////////////////////////////////////////////////////
// Unsubscribe a device from a group.
int LocalBB::ProcessUnsubscribeGroupMessage(QueuePointer &resp_queue, player_msghdr * hdr, void * data)
{
	if (!CheckHeader(hdr))
		return -1;

	// Remove the device from the group listeners map
	player_blackboard_entry_t *request = reinterpret_cast<player_blackboard_entry_t*>(data);
	UnsubscribeGroup(request->group, resp_queue);

	// Send back an empty ack
	this->Publish(
		this->device_addr,
		resp_queue,
		PLAYER_MSGTYPE_RESP_ACK,
		PLAYER_BLACKBOARD_REQ_UNSUBSCRIBE_FROM_GROUP,
		NULL,
		0,
		NULL);

	return 0;
}
Exemplo n.º 22
0
CSMFMapFile::CSMFMapFile(const std::string& mapFileName)
	: ifs(mapFileName), featureFileOffset(0)
{
	char buf[512] = {0};
	auto& h = header;

	memset(&h, 0, sizeof(header));
	memset(&featureHeader, 0, sizeof(featureHeader));

	if (!ifs.FileExists()) {
		snprintf(buf, sizeof(buf), "[%s] could not open \"%s\"", __func__, mapFileName.c_str());
		throw content_error(buf);
	}

	ReadMapHeader(h, ifs);

	if (CheckHeader(h))
		return;

	snprintf(buf, sizeof(buf), "[%s] corrupt header for \"%s\" (v=%d ts=%d tps=%d ss=%d)", __func__, mapFileName.c_str(), h.version, h.tilesize, h.texelPerSquare, h.squareSize);
	throw content_error(buf);
}
Exemplo n.º 23
0
double * wavread(char* filename, int *fs, int *nbit, int *wav_length) {
  FILE *fp = fopen(filename, "rb");
  if (NULL == fp) {
    printf("File not found.\n");
    return NULL;
  }

  if (CheckHeader(fp) == false) {
    fclose(fp);
    return NULL;
  }

  if (GetParameters(fp, fs, nbit, wav_length) == false) {
    fclose(fp);
    return NULL;
  }

  double *waveform = calloc(*wav_length, sizeof(double));
  if (waveform == NULL) return NULL;

  int quantization_byte = *nbit / 8;
  double zero_line = pow(2.0, *nbit - 1);
  double tmp, sign_bias;
  unsigned char for_int_number[4];
  for (int i = 0; i < *wav_length; ++i) {
    sign_bias = tmp = 0.0;
    fread(for_int_number, 1, quantization_byte, fp);  // "data"
    if (for_int_number[quantization_byte-1] >= 128) {
      sign_bias = pow(2.0, *nbit - 1);
      for_int_number[quantization_byte - 1] =
        for_int_number[quantization_byte - 1] & 0x7F;
    }
    for (int j = quantization_byte - 1; j >= 0; --j)
      tmp = tmp * 256.0 + for_int_number[j];
    waveform[i] = (tmp - sign_bias) / zero_line;
  }
  fclose(fp);
  return waveform;
}
Exemplo n.º 24
0
////////////////////////////////////////////////////////////////////////////////
// Retrieve an entry for a key.
int LocalBB::ProcessGetEntryMessage(QueuePointer &resp_queue, player_msghdr * hdr, void * data)
{
	if (!CheckHeader(hdr))
		return -1;

	// Retrieve the entry for the key
	player_blackboard_entry_t *request = reinterpret_cast<player_blackboard_entry_t*>(data);
	BlackBoardEntry current_value = entries[std::string(request->group)][std::string(request->key)];

	// Convert the entry
	player_blackboard_entry_t response = ToPlayerBlackBoardEntry(current_value);
	size_t response_size = sizeof(player_blackboard_entry_t) + response.key_count + response.group_count + response.data_count;

	// Publish the blackboard entry
	this->Publish(
		this->device_addr,
		resp_queue,
		PLAYER_MSGTYPE_RESP_ACK,
		PLAYER_BLACKBOARD_REQ_GET_ENTRY,
		&response,
		response_size,
		NULL);

	if (response.key)
	{
		delete [] response.key;
	}
	if (response.group)
	{
		delete [] response.group;
	}
	if (response.data)
	{
		delete [] response.data;
	}

	return 0;
}
Exemplo n.º 25
0
////////////////////////////////////////////////////////////////////////////////
// Subscribe a device to a key.
int LocalBB::ProcessSubscribeKeyMessage(QueuePointer &resp_queue, player_msghdr * hdr, void * data)
{
	if (!CheckHeader(hdr))
		return -1;

	// Add the device to the listeners map
	player_blackboard_entry_t *request = reinterpret_cast<player_blackboard_entry_t*>(data);
	BlackBoardEntry current_value = SubscribeKey(request->key, request->group, resp_queue, hdr->addr);

	// Get the entry for the given key
	player_blackboard_entry_t response = ToPlayerBlackBoardEntry(current_value);
	size_t response_size = sizeof(player_blackboard_entry_t) + response.key_count + response.group_count + response.data_count;

	// Publish the blackboard entry
	this->Publish(
		this->device_addr,
		resp_queue,
		PLAYER_MSGTYPE_RESP_ACK,
		PLAYER_BLACKBOARD_REQ_SUBSCRIBE_TO_KEY,
		&response,
		response_size,
		NULL);

	if (response.key)
	{
		delete [] response.key;
	}
	if (response.group)
	{
		delete [] response.group;
	}
	if (response.data)
	{
		delete [] response.data;
	}

	return 0;
}
Exemplo n.º 26
0
void wavread(const char* filename, int *fs, int *nbit, double *x) {
  FILE *fp = fopen(filename, "rb");
  if (NULL == fp) {
    printf("File not found.\n");
    return;
  }

  if (0 == CheckHeader(fp)) {
    fclose(fp);
    return;
  }

  int x_length;
  if (0 == GetParameters(fp, fs, nbit, &x_length)) {
    fclose(fp);
    return;
  }

  int quantization_byte = *nbit / 8;
  double zero_line = pow(2.0, *nbit - 1);
  double tmp, sign_bias;
  unsigned char for_int_number[4];
  for (int i = 0; i < x_length; ++i) {
    sign_bias = tmp = 0.0;
    fread(for_int_number, 1, quantization_byte, fp);  // "data"
    if (for_int_number[quantization_byte-1] >= 128) {
      sign_bias = pow(2.0, *nbit - 1);
      for_int_number[quantization_byte - 1] =
        for_int_number[quantization_byte - 1] & 0x7F;
    }
    for (int j = quantization_byte - 1; j >= 0; --j)
      tmp = tmp * 256.0 + for_int_number[j];
    x[i] = (tmp - sign_bias) / zero_line;
  }
  fclose(fp);
}
Exemplo n.º 27
0
  void PngReader::ReadFromFile(const std::string& filename)
  {
    FileRabi f(filename.c_str());

    char header[8];
    if (fread(header, 1, 8, f.fp_) != 8)
    {
      throw OrthancException(ErrorCode_BadFileFormat);
    }

    CheckHeader(header);

    PngRabi rabi;

    if (setjmp(png_jmpbuf(rabi.png_)))
    {
      rabi.Destruct();
      throw OrthancException(ErrorCode_BadFileFormat);
    }

    png_init_io(rabi.png_, f.fp_);

    Read(rabi);
  }
Exemplo n.º 28
0
/**
 * Allocate and read GPT data from the drive.
 *
 * The sector_bytes and gpt_drive_sectors fields should be filled on input.  The
 * primary and secondary header and entries are filled on output.
 *
 * Returns 0 if successful, 1 if error.
 */
int AllocAndReadGptData(VbExDiskHandle_t disk_handle, GptData *gptdata)
{
	uint64_t max_entries_bytes = MAX_NUMBER_OF_ENTRIES * sizeof(GptEntry);
	int primary_valid = 0, secondary_valid = 0;

	/* No data to be written yet */
	gptdata->modified = 0;

	/* Allocate all buffers */
	gptdata->primary_header = (uint8_t *)VbExMalloc(gptdata->sector_bytes);
	gptdata->secondary_header =
		(uint8_t *)VbExMalloc(gptdata->sector_bytes);
	gptdata->primary_entries = (uint8_t *)VbExMalloc(max_entries_bytes);
	gptdata->secondary_entries = (uint8_t *)VbExMalloc(max_entries_bytes);

	if (gptdata->primary_header == NULL ||
	    gptdata->secondary_header == NULL ||
	    gptdata->primary_entries == NULL ||
	    gptdata->secondary_entries == NULL)
		return 1;

	/* Read primary header from the drive, skipping the protective MBR */
	if (0 != VbExDiskRead(disk_handle, 1, 1, gptdata->primary_header)) {
		VBDEBUG(("Read error in primary GPT header\n"));
		Memset(gptdata->primary_header, 0, gptdata->sector_bytes);
	}

	/* Only read primary GPT if the primary header is valid */
	GptHeader* primary_header = (GptHeader*)gptdata->primary_header;
	if (0 == CheckHeader(primary_header, 0,
			gptdata->streaming_drive_sectors,
			gptdata->gpt_drive_sectors,
			gptdata->flags)) {
		primary_valid = 1;
		uint64_t entries_bytes = primary_header->number_of_entries
				* primary_header->size_of_entry;
		uint64_t entries_sectors = entries_bytes
					/ gptdata->sector_bytes;
		if (0 != VbExDiskRead(disk_handle,
				      primary_header->entries_lba,
				      entries_sectors,
				      gptdata->primary_entries)) {
			VBDEBUG(("Read error in primary GPT entries\n"));
			primary_valid = 0;
		}
	} else {
		VBDEBUG(("Primary GPT header invalid!\n"));
	}

	/* Read secondary header from the end of the drive */
	if (0 != VbExDiskRead(disk_handle, gptdata->gpt_drive_sectors - 1, 1,
			      gptdata->secondary_header)) {
		VBDEBUG(("Read error in secondary GPT header\n"));
		Memset(gptdata->secondary_header, 0, gptdata->sector_bytes);
	}

	/* Only read secondary GPT if the secondary header is valid */
	GptHeader* secondary_header = (GptHeader*)gptdata->secondary_header;
	if (0 == CheckHeader(secondary_header, 1,
			gptdata->streaming_drive_sectors,
			gptdata->gpt_drive_sectors,
			gptdata->flags)) {
		secondary_valid = 1;
		uint64_t entries_bytes = secondary_header->number_of_entries
				* secondary_header->size_of_entry;
		uint64_t entries_sectors = entries_bytes
				/ gptdata->sector_bytes;
		if (0 != VbExDiskRead(disk_handle,
				      secondary_header->entries_lba,
				      entries_sectors,
				      gptdata->secondary_entries)) {
			VBDEBUG(("Read error in secondary GPT entries\n"));
			secondary_valid = 0;
		}
	} else {
		VBDEBUG(("Secondary GPT header invalid!\n"));
	}

	/* Return 0 if least one GPT header was valid */
	return (primary_valid || secondary_valid) ? 0 : 1;
}
Exemplo n.º 29
0
int CLogCache::LoadOneItem(GitRev &Rev,ULONGLONG offset)
{
	if(m_pCacheData == NULL)
		return -1;

	if (offset + sizeof(SLogCacheRevItemHeader) > m_DataFileLength)
		return -2;

	SLogCacheRevItemHeader *header;
	header = (SLogCacheRevItemHeader *)(this->m_pCacheData + offset);

	if( !CheckHeader(header))
		return -2;

	Rev.m_Action = 0;
	SLogCacheRevFileHeader *fileheader;

	offset += sizeof(SLogCacheRevItemHeader);
	fileheader =(SLogCacheRevFileHeader *)(this->m_pCacheData + offset);

	for (DWORD i = 0; i < header->m_FileCount; ++i)
	{
		CTGitPath path;
		CString oldfile;
		path.Reset();

		if (offset + sizeof(SLogCacheRevFileHeader) > m_DataFileLength)
			return -2;

		if(!CheckHeader(fileheader))
			return -2;

		CString file(fileheader->m_FileName, fileheader->m_FileNameSize);
		if(fileheader->m_OldFileNameSize)
		{
			oldfile = CString(fileheader->m_FileName + fileheader->m_FileNameSize, fileheader->m_OldFileNameSize);
		}
		path.SetFromGit(file,&oldfile);

		path.m_ParentNo = fileheader ->m_ParentNo;
		path.m_Stage = fileheader ->m_Stage;
		path.m_Action = fileheader ->m_Action;
		Rev.m_Action |= path.m_Action;

		if(fileheader->m_Add == 0xFFFFFFFF)
			path.m_StatAdd=_T("-");
		else
			path.m_StatAdd.Format(_T("%d"),fileheader->m_Add);

		if(fileheader->m_Del == 0xFFFFFFFF)
			path.m_StatDel=_T("-");
		else
			path.m_StatDel.Format(_T("%d"), fileheader->m_Del);

		Rev.m_Files.AddPath(path);

		offset += sizeof(*fileheader) + fileheader->m_OldFileNameSize*sizeof(TCHAR) + fileheader->m_FileNameSize*sizeof(TCHAR) - sizeof(TCHAR);
		fileheader = (SLogCacheRevFileHeader *) (this->m_pCacheData + offset);
	}
	return 0;
}
Exemplo n.º 30
0
int CLogCache::SaveCache()
{
	if (!m_bEnabled)
		return 0;

	int ret =0;
	BOOL bIsRebuild=false;

	if (this->m_HashMap.empty()) // is not sufficient, because "working copy changes" are always included
		return 0;

	if( this->m_GitDir.IsEmpty())
		return 0;

	if (this->m_pCacheIndex && m_pCacheIndex->m_Header.m_ItemCount == 0) // check for empty log list (issue #915)
		return 0;

	SLogCacheIndexFile *pIndex =  NULL;
	if(this->m_pCacheIndex)
	{
		pIndex = (SLogCacheIndexFile *)malloc(sizeof(SLogCacheIndexFile)
					+sizeof(SLogCacheIndexItem) * (m_pCacheIndex->m_Header.m_ItemCount) );
		if(pIndex ==NULL)
			return -1;

		memcpy(pIndex,this->m_pCacheIndex,
			sizeof(SLogCacheIndexFile) + sizeof(SLogCacheIndexItem) *( m_pCacheIndex->m_Header.m_ItemCount-1)
			);
	}

	this->CloseDataHandles();
	this->CloseIndexHandles();

	SLogCacheIndexHeader header;
	CString file = this->m_GitDir + INDEX_FILE_NAME;
	do
	{
		m_IndexFile = CreateFile(file,
						GENERIC_READ|GENERIC_WRITE,
						0,
						NULL,
						OPEN_ALWAYS,
						FILE_ATTRIBUTE_NORMAL,
						NULL);

		if(m_IndexFile == INVALID_HANDLE_VALUE)
		{
			ret = -1;
			break;
		}

		file = m_GitDir + DATA_FILE_NAME;

		m_DataFile = CreateFile(file,
						GENERIC_READ|GENERIC_WRITE,
						0,
						NULL,
						OPEN_ALWAYS,
						FILE_ATTRIBUTE_NORMAL,
						NULL);

		if(m_DataFile == INVALID_HANDLE_VALUE)
		{
			ret = -1;
			break;
		}


		{

			memset(&header,0,sizeof(SLogCacheIndexHeader));
			DWORD num=0;
			if((!ReadFile(m_IndexFile,&header, sizeof(SLogCacheIndexHeader),&num,0)) ||
				!CheckHeader(&header)
				)
			{
				RebuildCacheFile();
				bIsRebuild =true;
			}
		}
		if(!bIsRebuild)
		{
			SLogCacheDataFileHeader header;
			DWORD num=0;
			if((!ReadFile(m_DataFile,&header,sizeof(SLogCacheDataFileHeader),&num,0)||
				!CheckHeader(&header)))
			{
				RebuildCacheFile();
				bIsRebuild=true;
			}
		}

		if(bIsRebuild)
			header.m_ItemCount=0;

		SetFilePointer(m_DataFile,0,0,2);
		SetFilePointer(m_IndexFile,0,0,2);

		for (auto i = m_HashMap.begin(); i != m_HashMap.end(); ++i)
		{
			if(this->GetOffset((*i).second.m_CommitHash,pIndex) ==0 || bIsRebuild)
			{
				if((*i).second.m_IsDiffFiles && !(*i).second.m_CommitHash.IsEmpty())
				{
					LARGE_INTEGER offset;
					offset.LowPart=0;
					offset.HighPart=0;
					LARGE_INTEGER start;
					start.QuadPart = 0;
					SetFilePointerEx(this->m_DataFile,start,&offset,1);
					if (this->SaveOneItem((*i).second, (LONG)offset.QuadPart))
					{
						TRACE(_T("Save one item error"));
						SetFilePointerEx(this->m_DataFile,offset, &offset,0);
						continue;
					}

					SLogCacheIndexItem item;
					item.m_Hash = (*i).second.m_CommitHash;
					item.m_Offset=offset.QuadPart;

					DWORD num;
					WriteFile(m_IndexFile,&item,sizeof(SLogCacheIndexItem),&num,0);
					++header.m_ItemCount;
				}
			}
		}
		FlushFileBuffers(m_IndexFile);

		m_IndexFileMap = CreateFileMapping(m_IndexFile, NULL, PAGE_READWRITE,0,0,NULL);
		if(m_IndexFileMap == INVALID_HANDLE_VALUE)
		{
			ret =-1;
			break;
		}

		m_pCacheIndex = (SLogCacheIndexFile*)MapViewOfFile(m_IndexFileMap,FILE_MAP_WRITE,0,0,0);
		if(m_pCacheIndex == NULL)
		{
			ret = -1;
			break;
		}

		m_pCacheIndex->m_Header.m_ItemCount = header.m_ItemCount;
		Sort();
		FlushViewOfFile(m_pCacheIndex,0);

	}while(0);

	this->CloseDataHandles();
	this->CloseIndexHandles();

	if(pIndex)
		free(pIndex);
	return ret;
}