コード例 #1
0
ファイル: Transport.cpp プロジェクト: svn2github/Escript
void TransportProblem::setToSolution(escript::Data& out, escript::Data& u0,
                                     escript::Data& source, double dt,
                                     bp::object& options)
{
    if (out.isComplex() || u0.isComplex() || source.isComplex())
    {
        throw ValueError("setToSolution: complex arguments not supported");
    }
  
    Options paso_options(options);
    options.attr("resetDiagnostics")();
    if (out.getDataPointSize() != getBlockSize()) {
        throw ValueError("setToSolution: block size of solution does not match block size of transport problems.");
    } else if (source.getDataPointSize() != getBlockSize()) {
        throw ValueError("setToSolution: block size of source term does not match block size of transport problems.");
    } else if (out.getFunctionSpace() != getFunctionSpace()) {
        throw ValueError("setToSolution: function spaces of solution and of transport problem don't match.");
    } else if (source.getFunctionSpace() != getFunctionSpace()) {
        throw ValueError("setToSolution: function spaces of source term and of transport problem don't match.");
    } else if (dt <= 0.) {
        throw ValueError("setToSolution: time increment dt needs to be positive.");
    }
    out.expand();
    source.expand();
    u0.expand();
    out.requireWrite();
    source.requireWrite();
    u0.requireWrite();
    double* out_dp = out.getExpandedVectorReference(static_cast<escript::DataTypes::real_t>(0)).data();
    double* u0_dp = u0.getExpandedVectorReference(static_cast<escript::DataTypes::real_t>(0)).data();
    double* source_dp = source.getExpandedVectorReference(static_cast<escript::DataTypes::real_t>(0)).data();
    solve(out_dp, dt, u0_dp, source_dp, &paso_options);
    paso_options.updateEscriptDiagnostics(options);
}
コード例 #2
0
ファイル: OTPassword.cpp プロジェクト: Kodachi75/opentxs
// OTPassword::SetSize   (Low-level)
//
// There are certain weird cases, like in OTSymmetricKey::GetPassphraseFromUser,
// where we set the password using the getPassword_writable, and it's properly
// null-terminated, yet this instance still doesn't know its actual size (even
// though
// the size is known.) Therefore I added this call in order to set the size in
// those odd cases where it's necessary. That being said, YOU should normally
// NEVER
// need to use this function, so just pretend it doesn't exist.
//
// This adds a null terminator, IF we're in text mode (not binary mode.)
//
bool OTPassword::SetSize(uint32_t uSize)
{
    if (isBinary_) {
        if (uSize > getBlockSize())
            uSize = getBlockSize(); // Truncated password beyond max size.
        size_ = uSize;
        return true;
    }
    else if (isText_) {
        // Cannot be as much as the blocksize,
        // because no room for null-terminator.
        if (uSize >= getBlockSize()) {
            uSize = getBlockSize() - 1; // Truncated password to blocksize-1.
        }
        // The actual null-terminator.
        data_[uSize] = '\0';
        // If size is 3, the terminator is at
        size_ = uSize;
        // data_[3] (which is the 4th byte.)
        return true;
    }
    otErr << __FUNCTION__ << ": Error: isBinary_ and isText_ are both "
                             "false. (Should never happen.)\n";
    return false;
}
コード例 #3
0
ファイル: Store.cpp プロジェクト: gesundkrank/multimap
Store::Store(const boost::filesystem::path& filename, const Options& options)
    : options_(options) {
  MT_REQUIRE_NOT_ZERO(getBlockSize());
  if (boost::filesystem::is_regular_file(filename)) {
    fd_ = mt::open(filename, options.readonly ? O_RDONLY : O_RDWR);
    mt::seek(fd_.get(), 0, SEEK_END);
    const auto length = mt::tell(fd_.get());
    mt::Check::isZero(length % getBlockSize(),
                      "Store: block size does not match size of data file");
    if (length != 0) {
      auto prot = PROT_READ;
      if (!options.readonly) {
        prot |= PROT_WRITE;
      }
      mapped_.data = mt::mmap(nullptr, length, prot, MAP_SHARED, fd_.get(), 0);
      mapped_.size = length;
    }

  } else {
    fd_ = mt::open(filename, O_RDWR | O_CREAT, 0644);
  }
  if (!options.readonly) {
    mt::Check::isZero(options.buffer_size % getBlockSize(),
                      "Store: buffer size must be a multiple of block size");
    buffer_.data.reset(new char[options.buffer_size]);
    buffer_.size = options.buffer_size;
  }
}
コード例 #4
0
ファイル: simulation.cpp プロジェクト: zaolij/libaudioverse
void Simulation::setOutputDevice(int index, int channels, float minLatency, float startLatency, float maxLatency) {
	if(index < -1) ERROR(Lav_ERROR_RANGE, "Index -1 is default; all other negative numbers are invalid.");
	if(output_device) {
		output_device->stop();
	}
	std::lock_guard<std::recursive_mutex> g(mutex);
	auto factory = getOutputDeviceFactory();
	if(factory == nullptr) ERROR(Lav_ERROR_CANNOT_INIT_AUDIO, "Failed to get output device factory.");
	auto sptr = std::static_pointer_cast<Simulation>(shared_from_this());
	std::weak_ptr<Simulation> wptr(sptr);
	int blockSize=getBlockSize();
	auto cb =[wptr, blockSize](float* buffer, int channels)->void {
		auto strong =wptr.lock();
		if(strong==nullptr) memset(buffer, 0, sizeof(float)*blockSize*channels);
		else {
			std::lock_guard<Simulation> guard(*strong);
			strong->getBlock(buffer, channels);
		}
	};
	std::shared_ptr<audio_io::OutputDevice> dev;
	try {
		dev =factory->createDevice(cb, index, channels, getSr(), getBlockSize(), minLatency, startLatency, maxLatency);
		if(dev == nullptr) ERROR(Lav_ERROR_CANNOT_INIT_AUDIO, "Device could not be created.");
	}
	catch(std::exception &e) {
		ERROR(Lav_ERROR_CANNOT_INIT_AUDIO, e.what());
	}
	output_device=dev;
}
コード例 #5
0
ファイル: Store.cpp プロジェクト: gesundkrank/multimap
uint32_t Store::putUnlocked(const char* block) {
  if (buffer_.full()) {
    // Flush buffer and remap data file.
    buffer_.flushTo(fd_.get());
    const auto new_size = mt::tell(fd_.get());
    const auto prot = PROT_READ | PROT_WRITE;
    if (mapped_.data) {
      // fsync(fd_);
      // Since Linux provides a so-called unified virtual memory system, it
      // is not necessary to write the content of the buffer cache to disk to
      // ensure that the newly appended data is visible after the remapping.
      // In a unified virtual memory system, memory mappings and blocks of the
      // buffer cache share the same pages of physical memory. [kerrisk p1032]
      MT_ASSERT_LT(mapped_.size, new_size);
#ifdef _GNU_SOURCE
      mapped_.data =
          mt::mremap(mapped_.data, mapped_.size, new_size, MREMAP_MAYMOVE);
#else
      mt::munmap(mapped_.data, mapped_.size);
      mapped_.data =
          mt::mmap(nullptr, new_size, prot, MAP_SHARED, fd_.get(), 0);
#endif
    } else {
      mapped_.data =
          mt::mmap(nullptr, new_size, prot, MAP_SHARED, fd_.get(), 0);
    }
    mapped_.size = new_size;
  }

  std::memcpy(buffer_.data.get() + buffer_.offset, block, getBlockSize());
  buffer_.offset += getBlockSize();

  return getNumBlocksUnlocked() - 1;
}
コード例 #6
0
void AbstractTransportProblem::insertConstraint(Data& source, Data& q, Data& r)
{
    source.expand();
    if (isEmpty())
        throw TransportProblemException("insertConstraint(): Transport problem is empty.");
    if (q.isEmpty()) {
        return;
    }
    if (((getBlockSize()==1) && (q.getDataPointRank()>0)) || (q.getDataPointRank()>1))
        throw ValueError("insertConstraint(): illegal rank of constraint location.");
    if (q.getDataPointSize()!=getBlockSize())
        throw ValueError("insertConstraint(): Block size of transport problem and constraint location don't match.");
    Data q2=Data(q,getFunctionSpace());

    if (r.isEmpty()) {
        Data r2=Data(0.,q.getDataPointShape(),getFunctionSpace(), false);
        copyConstraint(source,q2,r2);
    } else {
        if (((getBlockSize()==1) && (r.getDataPointRank()>0)) || (r.getDataPointRank()>1))
            throw ValueError("Illegal rank of constraint value.");
        if (r.getDataPointSize()!=getBlockSize())
            throw ValueError("Block size of transport problem and constraint value don't match.");
        Data r2=Data(r,getFunctionSpace());
        copyConstraint(source,q2,r2);
    }
}
コード例 #7
0
ファイル: PluginProcessor.cpp プロジェクト: OpenDAWN/mcfx
//==============================================================================
Mcfx_convolverAudioProcessor::Mcfx_convolverAudioProcessor() :
_min_in_ch(0),
_min_out_ch(0),
_num_conv(0),
_ConvBufferPos(0),
_isProcessing(false),
_configLoaded(false)

{
    _SampleRate = getSampleRate();
    _BufferSize = getBlockSize();
    _ConvBufferSize = getBlockSize();
    
    presetDir = presetDir.getSpecialLocation(File::userApplicationDataDirectory).getChildFile("mcfx/convolver_presets");
    std::cout << "Search dir:" << presetDir.getFullPathName() << std::endl;
    
	String debug;
    debug << "Search dir: " << presetDir.getFullPathName() << "\n\n";
    
    DebugPrint(debug);
    
    SearchPresets(presetDir);
    
    
    // this is for the open dialog of the gui
    lastDir = lastDir.getSpecialLocation(File::userHomeDirectory);
}
コード例 #8
0
ファイル: vram_mgr.c プロジェクト: DavisDev/oslib-mod
int oslVramMgrSetParameters(void *baseAddr, int size)		{
   int curVramSize = osl_vramSize;
   int blockNum = osl_vramBlocksNb - 1;
   int sizeDiff;

	if (!osl_useVramManager)
		return 0;
	//La taille est toujours multiple de 16 - arrondir au bloc supérieur
	if (size & 15)
		size += 16;

	//Différence de taille (négatif pour réduction, positif pour aggrandissement)
   sizeDiff = size - curVramSize;

	//Le dernier bloc est TOUJOURS libre, même s'il reste 0 octet. Cf la bidouille dans ulTexVramAlloc
	if (isBlockFree(blockNum) && getBlockSize(blockNum) + sizeDiff >= 0)			{
		setBlockSize(blockNum, getBlockSize(blockNum) + sizeDiff);
		osl_vramBase = (u32)baseAddr;
		osl_vramSize = size;
		//Pour ceux qui ne veulent pas utiliser le gestionnaire...
		osl_currentVramPtr = osl_vramBase;
	}
	else
		return 0;
	return 1;
}
コード例 #9
0
ファイル: Transport.cpp プロジェクト: svn2github/Escript
void TransportProblem::copyConstraint(escript::Data& source, escript::Data& q,
                                      escript::Data& r)
{
    if (source.isComplex() || q.isComplex() || r.isComplex())
    {
        throw ValueError("copyConstraint: complex arguments not supported.");
    }
    if (q.getDataPointSize() != getBlockSize()) {
        throw ValueError("copyConstraint: block size does not match the number of components of constraint mask.");
    } else if (q.getFunctionSpace() != getFunctionSpace()) {
        throw ValueError("copyConstraint: function spaces of transport problem and constraint mask don't match.");
    } else if (r.getDataPointSize() != getBlockSize()) {
        throw ValueError("copyConstraint: block size does not match the number of components of constraint values.");
    } else if (r.getFunctionSpace() != getFunctionSpace()) {
        throw ValueError("copyConstraint: function spaces of transport problem and constraint values don't match.");
    } else if (source.getDataPointSize() != getBlockSize()) {
        throw ValueError("copyConstraint: block size does not match the number of components of source.");
    } else if (source.getFunctionSpace() != getFunctionSpace()) {
        throw ValueError("copyConstraint: function spaces of transport problem and source don't match.");
    }

#if 0
    // r2=r where q>0, 0 elsewhere
    escript::Data r2(0., q.getDataPointShape(), q.getFunctionSpace());
    r2.copyWithMask(r, q);

    // source -= tp->mass_matrix*r2
    r2.expand();
    source.expand();
    q.expand();
    r2.requireWrite();
    source.requireWrite();
    q.requireWrite();
    double* r2_dp = r2.getSampleDataRW(0);
    double* source_dp = source.getSampleDataRW(0);
    double* q_dp = q.getSampleDataRW(0);

    mass_matrix->MatrixVector(-1., r2_dp, 1., source_dp);

    // insert 0 rows into transport matrix
    transport_matrix->nullifyRows(q_dp, 0.);

    // insert 0 rows and 1 in main diagonal into mass matrix
    mass_matrix->nullifyRowsAndCols(q_dp, q_dp, 1.);
    source.copyWithMask(escript::Data(0.,q.getDataPointShape(),q.getFunctionSpace()),q);
#else
    r.expand();
    source.expand();
    q.expand();
    r.requireWrite();
    source.requireWrite();
    q.requireWrite();
    double* r_dp = r.getExpandedVectorReference(static_cast<escript::DataTypes::real_t>(0)).data();
    double* source_dp = source.getExpandedVectorReference(static_cast<escript::DataTypes::real_t>(0)).data();
    double* q_dp = q.getExpandedVectorReference(static_cast<escript::DataTypes::real_t>(0)).data();
    setUpConstraint(q_dp);
    insertConstraint(r_dp, source_dp);
#endif
}
コード例 #10
0
ファイル: OTPassword.cpp プロジェクト: Kodachi75/opentxs
// (FYI, truncates if nAppendSize + getPasswordSize() is larger than
// getBlockSize.)
// Returns number of bytes appended, or -1 for error.
//
int32_t OTPassword::addMemory(const void* vAppend, uint32_t nAppendSize)
{
    OT_ASSERT(nullptr != vAppend);

    //  const char * szFunc = "OTPassword::addMemory";

    if (0 == nAppendSize) return 0;

    // If I'm currently at a 0 size, then call setMemory instead.
    //
    if (size_ == 0) return setMemory(vAppend, nAppendSize);
    //
    // By this point, I know I already have some memory allocated,
    // and I'm actually appending some other memory onto the end of it.
    //
    // Should already be set from the above setMemory call.
    OT_ASSERT(isBinary_);

    // Make sure total new size isn't larger than our block size
    //
    if ((nAppendSize + size_) > getBlockSize()) {
        // Truncated password beyond max size.
        nAppendSize = (getBlockSize() - size_);
    }
    //  OT_ASSERT(nAppendSize >= 0);

    if (0 == nAppendSize) return 0;

    // By this point, I know nAppendSize is larger than 0, AND that appending it
    // onto the
    // existing memory of this object will not exceed the total allowed block
    // size.
    //
    // Because we use setMemory when empty, and only use addMemory when we KNOW
    // something
    // is already there, therefore we know the page is already locked, so no
    // need to go
    // trying to lock it again.

    OTPassword::safe_memcpy(static_cast<void*>(&(data_[size_])),
                            nAppendSize, // dest size is based on the source
                                         // size, but guaranteed to be >0 and
                                         // <=getBlockSize
                            vAppend,
                            nAppendSize); // Since dest size is
                                          // known to be src size or
                                          // less (and >0) we use it
                                          // as src size. (We may
                                          // have truncated... and
                                          // we certainly don't want
                                          // to copy beyond our own
                                          // truncation.)

    size_ += nAppendSize;

    return nAppendSize;
}
コード例 #11
0
asagi::Grid::Error grid::NumaLocalStaticGrid::init() {
    unsigned long blockSize = getTotalBlockSize();
    size_t block[3];
    unsigned long masterBlockCount = getThreadBlockCount()*m_threadHandle.getThreadCount();
    //the first thread allocates the memory.
    if (m_threadHandle.getThreadRank(pthread_self())==0) {
        asagi::Grid::Error error;
        error = m_allocator.allocate(getType().getSize() * blockSize * masterBlockCount, m_data);
        if (error != asagi::Grid::SUCCESS)
            return error;
        // Load the blocks from the file, which we control
      /*  for (unsigned long i = 0; i < getLocalBlockCount(); i++) {
            if (getGlobalBlock(i) >= getBlockCount()){
                // Last process(es) may control less blocks
                break;
            }
            // Get x, y and z coordinates of the block
            getBlockPos(getGlobalBlock(i), block);
            
            // Get x, y and z coordinates of the first value in the block
            for (unsigned char j = 0; j < 3; j++)
                block[j] *= getBlockSize(j);
            getType().load(getInputFile(),
                    block, getBlockSize(),
                    &m_data[getType().getSize() * blockSize * i]);
        }*/
        //m_threadHandle.m_staticPtr[pthread_self()][m_id]=m_data;
       // std::cout << "Thread: " << pthread_self() << " Pointer: " << &m_data;
        m_threadHandle.setStaticPtr(pthread_self(), m_data, m_id);
    }
    else {
        //The memory was already allocated by the masterthread.
   
                //Simply shift the Pointer in the right space.
                m_data = m_threadHandle.getStaticPtr(m_threadHandle.getMasterthreadId(), m_id) + (getType().getSize() * blockSize * m_threadHandle.getThreadRank(pthread_self()) * getThreadBlockCount());
              //  std::cout << "Thread: " << pthread_self() << " Pointer: " << &m_data;
                m_threadHandle.setStaticPtr(pthread_self(), m_data, m_id);
    }
    // Load the blocks from the file, which we control
        for (unsigned long i = m_threadHandle.getThreadRank(pthread_self())*getThreadBlockCount(); i < (m_threadHandle.getThreadRank(pthread_self())*getThreadBlockCount()+getThreadBlockCount()); i++) {
            if (getGlobalBlock(i) >= getBlockCount()){
                // Last process(es) may control less blocks
                break;
            }
            // Get x, y and z coordinates of the block
            getBlockPos(getGlobalBlock(i), block);
            
            // Get x, y and z coordinates of the first value in the block
            for (unsigned char j = 0; j < 3; j++)
                block[j] *= getBlockSize(j);
            getType().load(m_threadHandle.getInputFile(),
                    block, getBlockSize(),
                    &m_data[getType().getSize() * blockSize * (i-m_threadHandle.getThreadRank(pthread_self())*getThreadBlockCount())]);
        }
    
    return asagi::Grid::SUCCESS;
}
コード例 #12
0
ファイル: OTPassword.cpp プロジェクト: Kodachi75/opentxs
// Returns size of memory (in case truncation is necessary.)
// Returns -1 in case of error.
//
int32_t OTPassword::setMemory(const void* vInput, uint32_t nInputSize)
{
    OT_ASSERT(nullptr != vInput);

    // Wipe whatever was in there before.
    //
    if (size_ > 0) zeroMemory();

    isBinary_ = true;
    isText_ = false;

    if (0 == nInputSize) return 0;

    // Make sure no input size is larger than our block size
    //
    if (nInputSize > getBlockSize())
        nInputSize = getBlockSize(); // Truncated password beyond max size.

#ifndef _WIN32
    //
    // Lock the memory page, before we copy the data over.
    // (If it's not already locked, which I doubt it will be.)
    //
    if (!isPageLocked_) // it won't be locked already, since we just zero'd it
                        // (above.) But I check this anyway...
    {
        if (ot_lockPage(static_cast<void*>(&(data_[0])), getBlockSize())) {
            isPageLocked_ = true;
        }
        else {
            otErr << __FUNCTION__
                  << ": Error: Failed attempting to lock memory page.\n";
        }
    }
#endif

    OTPassword::safe_memcpy(static_cast<void*>(&(data_[0])),
                            // dest size is based on the source
                            // size, but guaranteed to be >0 and
                            // <=getBlockSize
                            nInputSize,
                            // Since dest size is known
                            // to be src size or less
                            // (and >0) we use it as src
                            // size. (We may have
                            // truncated... and we
                            // certainly don't want to
                            // copy beyond our own
                            // truncation.)
                            vInput, nInputSize);

    size_ = nInputSize;
    return size_;
}
コード例 #13
0
ファイル: Store.cpp プロジェクト: gesundkrank/multimap
void Store::getUnlocked(uint32_t id, char* block) const {
  if (fill_page_cache_) {
    fill_page_cache_ = false;
    // Touch each block to load it into the OS page cache.
    const auto num_blocks_mapped = mapped_.getNumBlocks(getBlockSize());
    for (uint32_t i = 0; i != num_blocks_mapped; ++i) {
      std::memcpy(block, getAddressOf(i), getBlockSize());
    }
  }
  std::memcpy(block, getAddressOf(id), getBlockSize());
}
コード例 #14
0
ファイル: Store.cpp プロジェクト: gesundkrank/multimap
char* Store::getAddressOf(uint32_t id) const {
  MT_REQUIRE_LT(id, getNumBlocksUnlocked());

  const auto num_blocks_mapped = mapped_.getNumBlocks(getBlockSize());
  if (id < num_blocks_mapped) {
    const auto offset = getBlockSize() * id;
    return static_cast<char*>(mapped_.data) + offset;
  } else {
    const auto offset = getBlockSize() * (id - num_blocks_mapped);
    return buffer_.data.get() + offset;
  }
}
コード例 #15
0
// ---------------------------------------------------------
// Returns size of memory (in case truncation is necessary.)
// Returns -1 in case of error.
//
int32_t OTPassword::randomizeMemory(uint32_t nNewSize/*=DEFAULT_SIZE*/)
{
    const char * szFunc = "OTPassword::randomizeMemory";
    uint32_t nSize = nNewSize;
    // ---------------------------------
	// Wipe whatever was in there before.
    //
	if (m_nPasswordSize > 0)
		zeroMemory();
	// ---------------------------------
	if (0 > nSize)
		return (-1);
    // ---------------------------------
    m_bIsBinary = true;
    m_bIsText   = false;
	// ---------------------------------
	if (0 == nSize)
		return 0;
	// ---------------------------------
	// Make sure no input size is larger than our block size
	//
	if (nSize > getBlockSize())
		nSize = getBlockSize(); // Truncated password beyond max size.

#ifndef _WIN32
    //
    // Lock the memory page, before we randomize 'size bytes' of the data.
    // (If it's not already locked, which I doubt it will be.)
    //
    if (!m_bIsPageLocked) // it won't be locked already, since we just zero'd it (above.) But I check this anyway...
    {
        if (ot_lockPage(static_cast<void *>(&(m_szPassword[0])), getBlockSize()))
        {
            m_bIsPageLocked = true;
        }
        else
            OTLog::vError("%s: Error: Failed attempting to lock memory page.\n", szFunc);
    }  
#endif
	// ---------------------------------
    //
	if (!OTPassword::randomizeMemory_uint8(&(m_szPassword[0]), nSize))
    {
        // randomizeMemory (above) already logs, so I'm not logging again twice here.
        //
        zeroMemory();
		return -1;
	}
	// --------------------------------------------------
	m_nPasswordSize = nSize;

	return m_nPasswordSize;
}
コード例 #16
0
// ---------------------------------------------------------
// Returns size of memory (in case truncation is necessary.)
// Returns -1 in case of error.
//
int32_t OTPassword::setMemory(const void * vInput, uint32_t nInputSize)
{		
    OT_ASSERT(NULL != vInput);
    
    const char * szFunc = "OTPassword::setMemory";
    // ---------------------------------
	// Wipe whatever was in there before.
    //
	if (m_nPasswordSize > 0)
		zeroMemory();
	// ---------------------------------
	if (0 > nInputSize)
		return (-1);
    // ---------------------------------
    m_bIsBinary = true;
    m_bIsText   = false;
	// ---------------------------------
	if (0 == nInputSize)
		return 0;
	// ---------------------------------
	// Make sure no input size is larger than our block size
	//
	if (nInputSize > getBlockSize())
		nInputSize = getBlockSize(); // Truncated password beyond max size.
	// ---------------------------------

#ifndef _WIN32
    //
    // Lock the memory page, before we copy the data over.
    // (If it's not already locked, which I doubt it will be.)
    //
    if (!m_bIsPageLocked) // it won't be locked already, since we just zero'd it (above.) But I check this anyway...
    {
        if (ot_lockPage(static_cast<void *>(&(m_szPassword[0])), getBlockSize()))
        {
            m_bIsPageLocked = true;
        }
        else
            OTLog::vError("%s: Error: Failed attempting to lock memory page.\n", szFunc);
    }    
#endif

	// ---------------------------------    
    OTPassword::safe_memcpy(static_cast<void *>(&(m_szPassword[0])),
                            static_cast<uint32_t>(nInputSize), // dest size is based on the source size, but guaranteed to be >0 and <=getBlockSize
                            vInput,
                            static_cast<uint32_t>(nInputSize)); // Since dest size is known to be src size or less (and >0) we use it as src size. (We may have truncated... and we certainly don't want to copy beyond our own truncation.)    
	// ---------------------------------
    m_nPasswordSize = nInputSize;
	// ---------------------------------
	return m_nPasswordSize;
}
コード例 #17
0
ファイル: prf.cpp プロジェクト: Perseus14/scapi
void PrpFromPrfFixed::computeBlock(const vector<byte> & inBytes, int inOff, int inLen, vector<byte>& outBytes, int outOff) {
	if (!isKeySet())
		throw IllegalStateException("secret key isn't set");
	if ((inOff > inBytes.size()) || (inOff + inLen > inBytes.size()))
		throw out_of_range("wrong offset for the given input buffer");
	if ((outOff > outBytes.size()) || (outOff + getBlockSize() > outBytes.size()))
		throw out_of_range("wrong offset for the given output buffer");

	// if the input and output length are equal to the blockSize, call the computeBlock that doesn't take length arguments.
	if (inLen == getBlockSize())
		this->computeBlock(inBytes, inOff, outBytes, outOff);
	else
		throw out_of_range("input and output lengths should be equal to Block size");
}
コード例 #18
0
void Simulation::writeFile(std::string path, int channels, double duration, bool mayApplyMixingMatrix) {
	int blocks = (duration*getSr()/block_size)+1;
	auto file = FileWriter();
	file.open(path.c_str(), sr, channels);
	//vectors are guaranteed to be contiguous. Using a vector here guarantees proper cleanup.
	std::vector<float> block;
	block.resize(channels*getBlockSize());
	for(int i = 0; i < blocks; i++) {
		getBlock(&block[0], channels, mayApplyMixingMatrix);
		unsigned int written= 0;
		while(written < getBlockSize()) written += file.write(getBlockSize(), &block[0]);
	}
	file.close();
}
コード例 #19
0
// (FYI, truncates if nAppendSize + getPasswordSize() is larger than getBlockSize.)
// Returns number of bytes appended, or -1 for error.
//
int32_t OTPassword::addMemory(const void * vAppend, uint32_t nAppendSize) 
{
    OT_ASSERT(NULL != vAppend);

//  const char * szFunc = "OTPassword::addMemory";
    // ---------------------------------
	if (0 > nAppendSize)
		return (-1);
    // ---------------------------------
	if (0 == nAppendSize)
		return 0;
	// ---------------------------------
	// If I'm currently at a 0 size, then call setMemory instead.
    //
	if (m_nPasswordSize == 0)
		return this->setMemory(vAppend, nAppendSize);
    // ***********************************************
    //
    // By this point, I know I already have some memory allocated,
    // and I'm actually appending some other memory onto the end of it.
    //
    OT_ASSERT(m_bIsBinary); // Should already be set from the above setMemory call.
	// ---------------------------------
	// Make sure total new size isn't larger than our block size
	//
	if ((nAppendSize + m_nPasswordSize) > getBlockSize())
		nAppendSize = (getBlockSize() - m_nPasswordSize); // Truncated password beyond max size.
	// ---------------------------------
//  OT_ASSERT(nAppendSize >= 0);
    
    if (0 == nAppendSize)
        return 0;
    // ------------------------------------
    // By this point, I know nAppendSize is larger than 0, AND that appending it onto the
    // existing memory of this object will not exceed the total allowed block size.
    //
    // Because we use setMemory when empty, and only use addMemory when we KNOW something
    // is already there, therefore we know the page is already locked, so no need to go
    // trying to lock it again.
	// ---------------------------------    
    OTPassword::safe_memcpy(static_cast<void *>(&(m_szPassword[m_nPasswordSize])),
                            static_cast<uint32_t>(nAppendSize), // dest size is based on the source size, but guaranteed to be >0 and <=getBlockSize
                            vAppend,
                            static_cast<uint32_t>(nAppendSize)); // Since dest size is known to be src size or less (and >0) we use it as src size. (We may have truncated... and we certainly don't want to copy beyond our own truncation.)    
	// ---------------------------------
    m_nPasswordSize += nAppendSize;
	// ---------------------------------
	return nAppendSize;
}
コード例 #20
0
ファイル: OTPassword.cpp プロジェクト: Kodachi75/opentxs
// Returns size of memory (in case truncation is necessary.)
// Returns -1 in case of error.
//
int32_t OTPassword::randomizeMemory(uint32_t nNewSize)
{
    uint32_t nSize = nNewSize;

    // Wipe whatever was in there before.
    //
    if (size_ > 0) zeroMemory();

    isBinary_ = true;
    isText_ = false;

    if (0 == nSize) return 0;

    // Make sure no input size is larger than our block size
    //
    if (nSize > getBlockSize())
        nSize = getBlockSize(); // Truncated password beyond max size.

#ifndef _WIN32
    //
    // Lock the memory page, before we randomize 'size bytes' of the data.
    // (If it's not already locked, which I doubt it will be.)
    //
    if (!isPageLocked_) // it won't be locked already, since we just zero'd it
                        // (above.) But I check this anyway...
    {
        if (ot_lockPage(static_cast<void*>(&(data_[0])), getBlockSize())) {
            isPageLocked_ = true;
        }
        else {
            otErr << __FUNCTION__
                  << ": Error: Failed attempting to lock memory page.\n";
        }
    }
#endif

    //
    if (!OTPassword::randomizeMemory_uint8(&(data_[0]), nSize)) {
        // randomizeMemory (above) already logs, so I'm not logging again twice
        // here.
        //
        zeroMemory();
        return -1;
    }

    size_ = nSize;

    return size_;
}
コード例 #21
0
ファイル: vram_mgr.c プロジェクト: DavisDev/oslib-mod
//Note: il faut traduire une vraie adresse en offset
int oslVramMgrFreeBlock(void *blockAddress, int blockSize)		{
	int i, j, updateNeeded;
	int blockOffset = (u32)blockAddress - (u32)osl_vramBase;

	//Sans le manager, c'est plus simple...
	if (!osl_useVramManager)		{
		osl_currentVramPtr -= blockSize;
		//Pas vraiment utile, juste là pour s'assurer qu'on ne dépassera jamais de l'espace alloué
		if (osl_currentVramPtr < osl_vramBase)
			osl_currentVramPtr = osl_vramBase;
		return 1;
	}

	//Trouvons le bloc qui va bien
	for (i=0;i<osl_vramBlocksNb;i++)		{
		if (getBlockOffset(i) == blockOffset)
			break;
	}

	//Impossible de trouver le bloc
	if (i >= osl_vramBlocksNb)
		return 0;

	//Le bloc est maintenant libre ^^
	setBlockFree(i, 1);

	//Bon maintenant reste à "assembler" les blocs libres adjacents
	do		{
		updateNeeded = 0;
		for (j=0;j<osl_vramBlocksNb-1;j++)			{
			//Cherchons deux blocs adjacents
			if ((isBlockFree(j) && isBlockFree(j + 1))
				|| (isBlockFree(j) && getBlockSize(j) == 0))			{
				//Assemblons ces blocs maintenant
				int newSize = getBlockSize(j) + getBlockSize(j + 1), newAdd = getBlockOffset(j);
				memmove(osl_vramBlocks + j, osl_vramBlocks + j + 1, sizeof(OSL_VRAMBLOCK) * (osl_vramBlocksNb - j - 1));
				setBlockOffset(j, newAdd);
				setBlockSize(j, newSize);
				//Le bloc entre deux est supprimé
				osl_vramBlocksNb--;
				//ATT: On devra refaire un tour pour vérifier si de nouveaux blocs n'ont pas été créés
				updateNeeded = 1;
			}
		}

	} while (updateNeeded);

	return 1;
}
コード例 #22
0
ファイル: PluginProcessor.cpp プロジェクト: OpenDAWN/mcfx
void Mcfx_convolverAudioProcessor::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
{
    
    // std::cout << "in: " << getNumInputChannels() << " out: " << getNumOutputChannels() << std::endl;
    
    if (_configLoaded)
    {
        
        _isProcessing = true;
        
#ifdef USE_ZITA_CONVOLVER
        
        for (int i=0; i < jmin(conv_data.getNumInputChannels(), getNumInputChannels()) ; i++)
        {
            float* indata = zita_conv.inpdata(i)+_ConvBufferPos;
            memcpy(indata, buffer.getReadPointer(i), getBlockSize()*sizeof(float));
        }
        
        _ConvBufferPos += getBlockSize();
        
        if (_ConvBufferPos >= _ConvBufferSize) {
            zita_conv.process(THREAD_SYNC_MODE);
            _ConvBufferPos = 0;
        }
        
        
        
        for (int i=0; i < jmin(conv_data.getNumOutputChannels(), getNumOutputChannels()) ; i++)
        {
            float* outdata = zita_conv.outdata(i)+_ConvBufferPos;
            memcpy(buffer.getWritePointer(i), outdata, getBlockSize()*sizeof(float));
        }
        
#else
        mtxconv_.processBlock(buffer, buffer);
        
#endif
        
        _isProcessing = false;
        
    } else { // config loaded
        
        // clear output in case no config is loaded!
        buffer.clear();
    }
    

}
コード例 #23
0
ファイル: Node.cpp プロジェクト: babymastodon/moo-synth
 /**
  * DummyNode
  */
 DummyNode::DummyNode(const NodeSettings & ps):
   Node(ps),
   null_audio_frames_(0.0, getBlockSize(), 1),
   output_buffer_(getNumAudioOutputs(), &null_audio_frames_)
 {
   DEBUG("Dummy constructor " << getId())
 }
コード例 #24
0
ファイル: FileSystemMinix.cpp プロジェクト: crazy-weasel/sweb
FileSystemMinix::FileSystemMinix(FsDevice* device, uint32 mount_flags,
    minix_super_block super_block, uint16 minix_version, uint16 filename_len) :
    FileSystemUnix(device, mount_flags),
    superblock_(super_block), zone_size_(0),
    FILENAME_LEN_(filename_len), DIR_ENTRY_SIZE_(FILENAME_LEN_+2),
    zone_bitmap_(NULL)
{
  assert( FILENAME_LEN_ == 14 || FILENAME_LEN_ == 30 );

  // setting Minix Blocks size on FsDevice
  device_->setBlockSize(getBlockSize());

  // calculate the bitmap and table offsets
  calculateOffsets();

  // creating the i-node table
  createInodeTable(minix_version);

  // create the zone-bitmap
  zone_bitmap_ = new FsBitmap(this, getVolumeManager(),
                              zone_bitmap_sector_, zone_bitmap_sector_+zone_bitmap_size_-1,
                              superblock_.s_nzones);
  debug(FS_MINIX, "FileSystemMinix() - FsBitmap Zone successfully created\n");

  // init root-directory
  initRootInode();
}
コード例 #25
0
ファイル: InstanceProcessor.cpp プロジェクト: grrrr/Camomile
void InstanceProcessor::loadPatch(std::string const& name, std::string const& path)
{
    suspendProcessing(true);
    if(isSuspended())
    {
        {
            releaseDsp();
            m_patch = pd::Patch(*this, name, path);
            pd::Patch patch(getPatch());
            if(patch.isValid())
            {
                m_patch_tie = pd::Tie(std::to_string(patch.getDollarZero()) + "-playhead");
            }
            else
            {
                m_patch_tie = pd::Tie();
                sendConsoleError("Camomile can't find the patch : " + name);
            }
        }
        parametersChanged();
        prepareDsp(getTotalNumInputChannels(), getTotalNumOutputChannels(),
                   AudioProcessor::getSampleRate(), getBlockSize());
        
        pd::PatchManager::notifyListeners();
    }
    
    suspendProcessing(false);
}
コード例 #26
0
 void processAudio(AudioBuffer &buffer){
   float *sig=buffer.getSamples(0);
   if(success==false){
     for(int n=0; n<getBlockSize(); n++){
       sig[n]+=0.05*rand()/(float)RAND_MAX;
     }
   } else {
     static float phase=0;
     float inc=2*M_PI/200.0f;
     for(int n=0; n<getBlockSize(); n++){
       sig[n]+=0.2*sinf(phase);
       phase+=inc;
       phase= phase>2*M_PI ? phase-2*M_PI : phase;
     }
   }
 }
コード例 #27
0
ファイル: HeavyPatch.hpp プロジェクト: smrq/OwlProgram
  void processAudio(AudioBuffer &buffer) {
    float paramA = getParameterValue(PARAMETER_A);
    float paramB = getParameterValue(PARAMETER_B);
    float paramC = getParameterValue(PARAMETER_C);
    float paramD = getParameterValue(PARAMETER_D);
    
    // Note: The 0.0 parameter is the timestamp at which to execute the message,
    // but in this case it simply means to execute it immediately. "f" says that
    // the message contains one element and its type is float. paramA is then the
    // value.
    hv_vscheduleMessageForReceiver(context, "Channel-A", 0.0, "f", paramA);
    hv_vscheduleMessageForReceiver(context, "Channel-B", 0.0, "f", paramB);
    hv_vscheduleMessageForReceiver(context, "Channel-C", 0.0, "f", paramC);
    hv_vscheduleMessageForReceiver(context, "Channel-D", 0.0, "f", paramD);

    // int nbSples = buffer.getSize()*buffer.getChannels();
    // int nbSples = buffer.getSize()*HEAVY_CHANNELS;
    // float* inputCopy = (float*)malloc(nbSples*sizeof(float));
    // memcpy(inputCopy, buffer.getSamples(0), nbSples*sizeof(float));

    // float** inputs = { &inputCopy, &inputCopy+getBlockSize()};
    float* outputs[] = {buffer.getSamples(0), buffer.getSamples(1) };
    
    hv_owl_process(context, outputs, outputs, getBlockSize());		     
  }
コード例 #28
0
const NAString
ElemDDLFileAttrBlockSize::displayLabel1() const
{
  char buffer[80];
  sprintf(buffer, "%d", getBlockSize());
  return NAString("Block size: ") + NAString(buffer);
}
コード例 #29
0
 AgnesiEnvelopePatch(){
   registerParameter(PARAMETER_A, "Rate");
   registerParameter(PARAMETER_B, "Radius");
   registerParameter(PARAMETER_C, "Offset");
   envelope = FloatArray::create(getBlockSize());
   x = 0;
 }
コード例 #30
0
ファイル: LpfDelayPatch.hpp プロジェクト: mazbox/OwlPatches
  void processAudio(AudioBuffer &buffer){
    float y[getBlockSize()];
    setCoeffs(getLpFreq(), 0.8f);
    float delayTime = getParameterValue(PARAMETER_A); // get delay time value    
    float feedback  = getParameterValue(PARAMETER_B); // get feedback value
    float wetDry    = getParameterValue(PARAMETER_D); // get gain value

    if(abs(time - delayTime) < 0.01)
      delayTime = time;
    else
      time = delayTime;
        
    float delaySamples = delayTime * (delayBuffer.getSize()-1);        
    int size = buffer.getSize();
    float* x = buffer.getSamples(0);
    process(size, x, y);     // low pass filter for delay buffer
    for(int n = 0; n < size; n++){
        
      //linear interpolation for delayBuffer index
      dSamples = olddelaySamples + (delaySamples - olddelaySamples) * n / size;
        
      y[n] = y[n] + feedback * delayBuffer.read(dSamples);
      x[n] = (1.f - wetDry) * x[n] + wetDry * y[n];  //crossfade for wet/dry balance
      delayBuffer.write(x[n]);
    }
    olddelaySamples = delaySamples;
  }