示例#1
0
	ISoundSource* CSoundManager::CreateSource(const wchar *filename, Vec3 position, bool relativeToListener)
	{
		CSoundBuffer* buff = CreateBuffer(filename);
		if(!buff) return NULL;

		CSoundSource* source = new CSoundSource();
		if(!source)
		{
			DestroyBuffer(buff);
			return NULL;
		}

		source->Create(m_extensions, buff, position, relativeToListener);
		m_sources.push_back(source);

		return source;
	}
示例#2
0
bool VertexBuffer::SetupIndexBuffer(IndexVector* indices, Usage::Usage usage)
{
    assert(!indices->empty());

    VertexBuffer::Description description;
    description.ElementCount = indices->size();
    description.ElementSize = sizeof(unsigned int);
    description.Usage = usage;
    description.FirstElementPointer = &(indices->front());

    if (!CreateBuffer(&mIndexBuffer, description, D3D10_BIND_INDEX_BUFFER))
        return false;

    mIndexCount = indices->size();

    return true;
}
EXPORT_C TInt CMTPTypeOpaqueData::FirstWriteChunk(TPtr8& aChunk, TUint aDataLength )
    {
    if(KMaxSizeOfWriteBuffer < aDataLength )
        return KErrOverflow;
    
    TInt size = aDataLength;
    if( aDataLength <= 0 )
        {
        size = KMaxSizeOfWriteBuffer;
        }
    
    TInt err =  CreateBuffer( size );
    if( KErrNone != err)
        return err;

    
    return FirstWriteChunk(aChunk);
    }
示例#4
0
    bufPtr OverArea::LoadMap32()
    {
        u8 a         = 0;
        u8 b         = 0;

        u32 i        = 0;
        u32 tableLoc = 0;
        u32 offset   = 0;

        bufPtr data1 = NULL;
        bufPtr data2 = NULL;

        // map32 in Zelda should contain 0x200 bytes of data
        bufPtr map32Buf = CreateBuffer(0x10, 0x10, 2);

        // ---------------------------------------------

        tableLoc = CpuToRomAddr(Get3Bytes(this->rom, asm_overmap_ptrs));
        offset   = Get3Bytes(this->rom, tableLoc + (areaNum * 3));
        data1    = DecompressBank02(this->rom, CpuToRomAddr(offset) );

        tableLoc = CpuToRomAddr(Get3Bytes(this->rom, asm_overmap_ptrs2));
        offset   = Get3Bytes(this->rom, tableLoc + (areaNum * 3));
        data2    = DecompressBank02(this->rom, CpuToRomAddr(offset) );

        for(i = 0; i < 0x100; ++i)
        {
            // notice how this data is interlaced from two separate sources
            // strange storage method... maybe it compresses better that way
            a = GetByte(data1, i);
            b = GetByte(data2, i);
            PutByte(map32Buf, (i*2)+1, a);
            PutByte(map32Buf, (i*2),   b);
        }

        DeallocBuffer(data1);
        DeallocBuffer(data2);

        // signal that there's a problem if the map32 data is not of the correct size
        if(map32Buf->length != 0x200)
            map32Buf->error = 1;

        return map32Buf;
    }
示例#5
0
void OnRead(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) {
  TcpWrap* tcp_wrap = reinterpret_cast<TcpWrap*>(handle->data);
  IOTJS_ASSERT(tcp_wrap != NULL);

  // tcp handle
  JObject jtcp = tcp_wrap->jobject();
  IOTJS_ASSERT(jtcp.IsObject());

  // socket object
  JObject jsocket = jtcp.GetProperty("owner");
  IOTJS_ASSERT(jsocket.IsObject());

  // onread callback
  JObject jonread = jtcp.GetProperty("onread");
  IOTJS_ASSERT(jonread.IsFunction());

  JArgList jargs(4);
  jargs.Add(jsocket);
  jargs.Add(JVal::Number((int)nread));
  jargs.Add(JVal::Bool(false));

  if (nread <= 0) {
    if (buf->base != NULL) {
      ReleaseBuffer(buf->base);
    }
    if (nread < 0) {
      if (nread == UV__EOF) {
        jargs.Set(2, JVal::Bool(true));
      }
      MakeCallback(jonread, JObject::Null(), jargs);
    }
    return;
  }

  JObject jbuffer(CreateBuffer(static_cast<size_t>(nread)));
  BufferWrap* buffer_wrap = BufferWrap::FromJBuffer(jbuffer);

  buffer_wrap->Copy(buf->base, nread);

  jargs.Add(jbuffer);
  MakeCallback(jonread, JObject::Null(), jargs);

  ReleaseBuffer(buf->base);
}
示例#6
0
/* 
 * This application substitues in the DNA sequence the outside ACGT chars by random ACGT symbols.
 */
int main(int argc, char *argv[]){
  uint32_t streamSize, index, seed = 0;
  uint8_t  value;
  char     *bases = "ACGT";
  BUF *Buffer;
  srand(seed);
  
  char *programName = argv[0];
  struct argparse_option options[] = {
        OPT_HELP(),
        OPT_GROUP("Basic options"),
        OPT_BUFF('<', "input.seq", "Input sequence file (stdin)"),
        OPT_BUFF('>', "output.seq", "Output sequence file (stdout)"),
        OPT_END(),
  };
  struct argparse argparse;

  char usage[250] = "\nExample: "; 
  strcat(usage, programName);
  strcat(usage, " < input.seq > output.seq\n");

  argparse_init(&argparse, options, NULL, programName, 0);
  argparse_describe(&argparse, "\nIt substitues in the DNA sequence the outside "
    "ACGT chars by random ACGT symbols.\nIt works in sequence file formats\n", usage);
  argc = argparse_parse(&argparse, argc, argv);

  if(argc != 0)
    argparse_help_cb(&argparse, options);

  Buffer = CreateBuffer(BUF_SIZE);

  while((streamSize = fread(Buffer->buf, 1, Buffer->size, stdin)))
    for(index = 0 ; index < streamSize ; ++index)
    {
      value = Buffer->buf[index];
      if(value == '\n')
        continue;
      RandIfExtra(value, bases);
    } 

  RemoveBuffer(Buffer); 
  return EXIT_SUCCESS;
}
示例#7
0
void FillBufferCannotWriteMore(struct test_result *testResult)
{
    /* Setup */
    int buf_size = 8;
    char input[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
    int input_size = 8;

    Log(L_INFO, "Start FillBufferCannotWriteMore");
    /* Test */
    Assert(CreateBuffer(buf_size) == buf_size, testResult);
    Assert(WriteBuffer(input, input_size) == input_size, testResult);
    Assert(WriteBuffer(input, 1) == 0, testResult);

    /* Cleanup */
    ReleaseBuffer();
    if (testResult->status == STATUS_INCOMPLETE) {
        testResult->status = STATUS_PASS;
    }
}
示例#8
0
bool DSound::Start()
{
	if (FAILED(DirectSoundCreate8(0, &ds, 0)))
		return false;
	if (hWnd)
	{
		HRESULT hr = ds->SetCooperativeLevel((HWND)hWnd, DSSCL_PRIORITY);
	}
	if (!CreateBuffer())
		return false;

	DWORD num1;
	short* p1;
	dsBuffer->Lock(0, bufferSize, (void* *)&p1, &num1, 0, 0, DSBLOCK_ENTIREBUFFER);
	memset(p1, 0, num1);
	dsBuffer->Unlock(p1, num1, 0, 0);
	thread = std::thread(std::mem_fun(&DSound::SoundLoop), this);
	return true;
}
示例#9
0
文件: AS.cpp 项目: 0rel/okkuplektor
bool CASOut::Init()
{
    DSBUFFERDESC DSBuffDesc;

    // DirectSound Device Object erzeugen.
    if( !m_uiInstances_ )
    {
        // rem: DSSCL_EXCLUSIVE wäre auch möglich, ist jedoch teilweise nicht unterstützt.
        DirectSoundCreate8( NULL, &m_poDSDev_, 0 );
        m_poDSDev_->SetCooperativeLevel( GetDesktopWindow(), DSSCL_PRIORITY ); // z.B. mit GetConsoleWindow()

        // Primary Buffer erzeugen.
        m_poDSBuffer = 0;
        ZeroMemory(&DSBuffDesc, sizeof(DSBUFFERDESC) );
        DSBuffDesc.dwSize =	sizeof(DSBUFFERDESC);
        DSBuffDesc.dwFlags =	DSBCAPS_PRIMARYBUFFER;
        m_poDSDev_->CreateSoundBuffer( &DSBuffDesc, &m_poDSBuffer, NULL );

        // Format des Primary Buffers setzen.
        m_poDSBuffer->SetFormat( &m_oWaveFormatEx );
        SAFE_RELEASE( m_poDSBuffer );
    }

    // Secondary Buffer erzeugen.
    m_poDSBuffer = 0;
    ZeroMemory(&DSBuffDesc, sizeof(DSBUFFERDESC));
    DSBuffDesc.dwSize =	sizeof(DSBUFFERDESC);
    DSBuffDesc.dwFlags =	//DSBCAPS_CTRLVOLUME |
        //DSBCAPS_CTRLFREQUENCY |
        //DSBCAPS_CTRLPOSITIONNOTIFY |
        DSBCAPS_GETCURRENTPOSITION2 |
        DSBCAPS_GLOBALFOCUS;
    DSBuffDesc.dwBufferBytes =	m_uiBufferSize;
    DSBuffDesc.lpwfxFormat =	&m_oWaveFormatEx;
    m_poDSDev_->CreateSoundBuffer( &DSBuffDesc, &m_poDSBuffer, NULL );

    CreateBuffer();

    ++m_uiInstances_;

    return true;
}
示例#10
0
void WriteBufferAndReadOneByteSuccessful(struct test_result *testResult)
{
    int buf_size = 0x20;
    char input[] = {(char) 0xBB};
    int input_size = 1;
    char *output = NULL;

    Log(L_INFO, "Start WriteBufferAndReadOneByteSuccessful");
    output = malloc(buf_size * sizeof(char));
    Assert(CreateBuffer(buf_size) == buf_size, testResult);
    Assert(WriteBuffer(input, input_size) == input_size, testResult);
    Assert(ReadBuffer(output, input_size) == input_size, testResult);
    Assert(AreEqual(input, output, input_size), testResult);

    ReleaseBuffer();
    free(output);
    if (testResult->status == STATUS_INCOMPLETE) {
        testResult->status = STATUS_PASS;
    }
}
示例#11
0
int Mesh::InitIndexData(void* data, UINT numIndices, DXGI_FORMAT indexFormat, D3D11_USAGE usageHint, UINT cpuAccessFlags)
{
    if (indexBuffer) {
        indexBuffer->Release();
        indexBuffer = 0;
    }
    // todo: allow something other than UINT, such as shorts
    this->indexFormat = indexFormat;
    this->numIndices = numIndices;

    unsigned int indexSize = 0;
    if (indexFormat == DXGI_FORMAT_R16_UINT)
        indexSize = 2;
    else if (indexFormat == DXGI_FORMAT_R32_UINT)
        indexSize = 4;
    else
        return INVALID_PARAMETER;

    return CreateBuffer(device, data, indexSize*numIndices, usageHint, cpuAccessFlags, D3D11_BIND_INDEX_BUFFER, &indexBuffer);
}
示例#12
0
bool MUSIKAPEDecoder::OpenMedia(const char *FileName)
{

	int nRetVal=0;
	CSmartPtr<wchar_t> wsFileName;
	wsFileName.Assign(GetUTF16FromANSI(FileName),TRUE);
	IAPEDecompress * pAPEDecompress = CreateIAPEDecompress(wsFileName, &nRetVal);
	if (pAPEDecompress != NULL)
	{
		m_ApeInfo.pAPEDecompress = pAPEDecompress;
		m_Info.bitrate = pAPEDecompress->GetInfo(APE_INFO_AVERAGE_BITRATE);
		m_Info.bits_per_sample = pAPEDecompress->GetInfo(APE_INFO_BITS_PER_SAMPLE);
		m_Info.channels = pAPEDecompress->GetInfo(APE_INFO_CHANNELS);
		m_Info.frequency = pAPEDecompress->GetInfo(APE_INFO_SAMPLE_RATE);
		m_Info.SampleCount = pAPEDecompress->GetInfo(APE_DECOMPRESS_TOTAL_BLOCKS);
		int bytesPerBlock = m_Info.channels * (m_Info.bits_per_sample >> 3);
		int decoder_buffer_size = bytesPerBlock * (int)((APEDecodeBufferSec * pAPEDecompress->GetInfo(APE_INFO_SAMPLE_RATE)) + 0.5);
		m_Info.FileSize = pAPEDecompress->GetInfo(APE_INFO_APE_TOTAL_BYTES);
		return CreateBuffer(decoder_buffer_size);
	}
    // Return a memory location in distance less than 2^31 from input address 
    UINT_PTR GetLocation(UINT_PTR addr)
    {
        MemoryBuffer *pBuff = m_pages;
        for (; pBuff<m_lastBuffer && IsInDistance(pBuff->m_next, addr, MAX_DISTANCE); ++pBuff)
        {
            if (pBuff->m_next < pBuff->m_base + pBuff->m_size)
            {
                UINT_PTR loc = pBuff->m_next;
                pBuff->m_next += MAX_PROBE_SIZE;
                return loc;
            }
        }

        pBuff = CreateBuffer(addr);
        if(!pBuff)
            return 0;

        UINT_PTR loc = pBuff->m_next;
        pBuff->m_next += MAX_PROBE_SIZE;
        return loc;
    }
示例#14
0
JHANDLER_FUNCTION(Slice, handler) {
  IOTJS_ASSERT(handler.GetArgLength() == 2);
  IOTJS_ASSERT(handler.GetArg(0)->IsNumber());
  IOTJS_ASSERT(handler.GetArg(1)->IsNumber());

  JObject* jbuiltin = handler.GetThis();
  BufferWrap* buffer_wrap = BufferWrap::FromJBufferBuiltin(*jbuiltin);

  int start = handler.GetArg(0)->GetInt32();
  int end = handler.GetArg(1)->GetInt32();
  int length = end - start;
  IOTJS_ASSERT(length >= 0);

  JObject jnew_buffer = CreateBuffer(length);
  BufferWrap* new_buffer_wrap = BufferWrap::FromJBuffer(jnew_buffer);
  new_buffer_wrap->Copy(buffer_wrap->buffer(), start, end, 0);

  handler.Return(jnew_buffer);

  return true;
}
示例#15
0
IUnknown* DX11Engine::createBuffer(IUnknown* pDeviceIn, const STAR_BUFFER_DESC& desc, 
    const STAR_SUBRESOURCE_DATA* pInitialData, size_t size, const char* name) const
{
    auto pDevice = reinterpret_cast<ID3D11Device*>(pDeviceIn);

    static_assert(sizeof(D3D11_BUFFER_DESC) == sizeof(STAR_BUFFER_DESC),
        "D3D11_BUFFER_DESC size different");
    static_assert(sizeof(D3D11_SUBRESOURCE_DATA) == sizeof(STAR_SUBRESOURCE_DATA),
        "D3D11_SUBRESOURCE_DATA size different");

    HRESULT hr = S_OK;
    ID3D11Buffer* pBuffer;
    V(pDevice->CreateBuffer(
            reinterpret_cast<const D3D11_BUFFER_DESC *>(&desc),
        reinterpret_cast<const D3D11_SUBRESOURCE_DATA *>(pInitialData),
        &pBuffer));

    STAR_SET_DEBUG_NAME(pBuffer, size, name);

    return pBuffer;
}
示例#16
0
bool AudioAsset::LoadFromRawPCMWavData(const u8 *data, size_t numBytes, bool stereo, bool is16Bit, int frequency)
{
    // Clean up the previous OpenAL audio buffer handle, if old data existed.
    DoUnload();

#ifndef TUNDRA_NO_AUDIO
    if (!data || numBytes == 0)
    {
        LogError("Null data passed in AudioAsset::LoadFromWavData!");
        return false;
    }

    if (!CreateBuffer())
        return false;

    ALenum openALFormat;
    if (stereo && is16Bit) openALFormat = AL_FORMAT_STEREO16;
    else if (!stereo && is16Bit) openALFormat = AL_FORMAT_MONO16;
    else if (stereo && !is16Bit) openALFormat = AL_FORMAT_STEREO8;
    else /* (!stereo && !is16Bit)*/ openALFormat = AL_FORMAT_MONO8;

    // Copy the new data over.
    std::vector<u8> tmpData(data, data + numBytes);
    alBufferData(handle, openALFormat, &tmpData[0], tmpData.size(), frequency);
    ALenum error = alGetError();
    if (error != AL_NONE)
    {
        const ALchar unknownError[] = "unknown error";
        const ALchar *errorString = alGetString(error);
        if (!errorString)
            errorString = unknownError;
        LogError("Could not set OpenAL sound buffer data: OpenAL error number " + QString::number(error) + ": " + errorString);
        DoUnload();
        return false;
    }
    return true;
#else
    return false;
#endif
}
示例#17
0
void Buffer_WriteAndRead_Valid(struct test_result *testResult)
{
    int buf_size = 0x0F;
    char *temp = NULL;
    int i, result;
    char a1[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
    char a2[] = {(char) 0xDE, (char) 0xAD, (char) 0xBE, (char) 0xEF,
                 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10};

    CreateBuffer(buf_size);
    result = WriteBuffer(a1, sizeof(a1));
    printf("** Write 1: Wrote %d.\n", result);
    result = WriteBuffer(a2, sizeof(a2));
    printf("** Write 2: Wrote %d.\n", result);
    temp = malloc(sizeof(char) * 0x20);
    result = ReadBuffer(temp, 20);
    printf("** Read 1: Read %d.\n", result);
    for (i = 0; i < sizeof(a2); ++i) {
        printf("0x%1X ", (unsigned) (unsigned char) temp[i]);
    }
    ReleaseBuffer();
}
示例#18
0
bool CWinGlkOGGSound::Play(int iRepeat, int iVolume, bool PauseState)
{
  m_pReadPtr = m_pData;
  if (m_pReadPtr == NULL)
    return false;

  // Open the stream
  ov_callbacks VorbisCBs;
  VorbisCBs.read_func = VorbisRead;
  VorbisCBs.close_func = VorbisClose;
  VorbisCBs.seek_func = VorbisSeek;
  VorbisCBs.tell_func = VorbisTell;
  if (ov_open_callbacks(this,&m_Stream,NULL,0,VorbisCBs) < 0)
    return false;
  m_StreamOpen = true;
  vorbis_info* Info = ov_info(&m_Stream,-1);

  // Create a buffer
  if (CreateBuffer(Info->channels,Info->rate,16) == false)
    return false;

  // Set the duration of the sample
  if (iRepeat > 0)
    m_Duration = (DWORD)ceil(1000.0 * iRepeat * ov_time_total(&m_Stream,-1));
  else
    m_Duration = -1;

  // Fill the buffer with sample data
  m_iRepeat = (iRepeat < 0) ? -1 : iRepeat - 1;
  if (FillBuffer(GetBufferSize()) == false)
    return false;

  // Set the volume for the buffer
  SetVolume(iVolume);

  // Start the buffer playing
  return PlayBuffer(PauseState);
}
示例#19
0
void CompletelyFillAndEmptyBuffer(struct test_result *testResult)
{
    /* Setup */
    int buf_size = 8;
    char input[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
    int input_size = 8;
    char *output = NULL;

    Log(L_INFO, "Start CompletelyFillAndEmptyBuffer");
    /* Test */
    output = malloc(sizeof(char) * input_size);
    Assert(CreateBuffer(buf_size) == buf_size, testResult);
    Assert(WriteBuffer(input, input_size) == input_size, testResult);
    Assert(ReadBuffer(output, input_size) == input_size, testResult);
    Assert(AreEqual(input, output, input_size), testResult);

    /* Cleanup */
    ReleaseBuffer();
    free(output);
    if (testResult->status == STATUS_INCOMPLETE) {
        testResult->status = STATUS_PASS;
    }
}
void glutLeaveGameMode(void)
{
   if(!GameMode)
      return;

   glFBDevDestroyContext(GameContext);
   glFBDevDestroyVisual(Visual);

   VarInfo = NormVarInfo;
   Visual = NormVisual;
   
   if(Visual) {
      SetVideoMode();
      CreateBuffer();
   
      if(!glFBDevMakeCurrent( Context, Buffer, Buffer )) {
	 sprintf(exiterror, "Failure to Make Current\n");
	 exit(0);
      }
      
      Redisplay = 1;
   }

   KeyboardFunc = KeyFuncs[0];
   KeyboardUpFunc = KeyFuncs[1];

   DisplayFunc = NormFuncs[0];
   ReshapeFunc = NormFuncs[1];
   MouseFunc = NormFuncs[2];
   MotionFunc = NormFuncs[3];
   PassiveMotionFunc = NormFuncs[4];
   VisibilityFunc = NormFuncs[5];
   SpecialFunc = NormFuncs[6];
   SpecialUpFunc = NormFuncs[7];

   GameMode = 0;
}
void test_Removeall_SHOULD_REMOVE_ALL_THE_DATA_INSIDE_THE_BUFFER()
{

	int data;
	//Create the buffer set and input some data inside the buffer.
	CircularBuffer *testBuffer= CreateBuffer(SIZE_OF_BUFFER);
	add(testBuffer,1);
	add(testBuffer,2);
	add(testBuffer,3);
	add(testBuffer,4);
	add(testBuffer,5);
	//Remove all the data inside the buffer.
	Removeall(testBuffer);
	//Show the slot are empty.
	TEST_ASSERT_EQUAL(0,testBuffer->buffer[0]); //slot 0
	TEST_ASSERT_EQUAL(0,testBuffer->buffer[1]); //slot 1
	TEST_ASSERT_EQUAL(0,testBuffer->buffer[2]); //slot 2
	TEST_ASSERT_EQUAL(0,testBuffer->buffer[3]); //slot 3
	TEST_ASSERT_EQUAL(0,testBuffer->buffer[4]); //slot 4
	TEST_ASSERT_EQUAL(0,testBuffer->buffer[5]); //slot 5

	//Add some data and remove some data to make the head and tail
	//does not point to the initial position
	add(testBuffer,1);
	add(testBuffer,2);
	add(testBuffer,3);
	Remove(testBuffer,&data);
	Remove(testBuffer,&data);
	//Remove all the data inside the buffer.
	Removeall(testBuffer);
	//Make sure head and tail is pointing to the initial position.
	TEST_ASSERT_EQUAL_PTR(testBuffer->buffer,testBuffer->head);
	TEST_ASSERT_EQUAL_PTR(testBuffer->buffer,testBuffer->tail);
	//Test the length of the buffer is zero.
	TEST_ASSERT_EQUAL(0,testBuffer->length);
}
示例#22
0
文件: threader.c 项目: mjwolf/httplib
int main(int argc, char **argv)
{
    int i, rc;

    Log(L_INFO, "Starting program\n\n");

    if (CreateBuffer(BUF_SIZE) == 0) {
        Log(L_ERROR, "Buffer not created with expected size!\nExiting\n");
        return -1;
    }

    srandom(SEED);

    pthread_t write_threads[NUM_WRITERS];
    pthread_t read_thread;

    pthread_create(&read_thread, NULL, Reader, NULL);

    for (i = 0; i < NUM_WRITERS; ++i) {
        rc = pthread_create(&write_threads[i], NULL, Writer,
                            (void *) (intptr_t) i);
        if (rc) {
            return -2;
        }
    }

    for (i = 0; i < NUM_WRITERS; ++i) {
        pthread_join(write_threads[i], NULL);
    }

    exit_reader = true;
    ReleaseBuffer();

    Log(L_INFO, "Exiting program\n\n");
    pthread_exit(NULL);
}
示例#23
0
void
Client::StartWorker(workMode pMode, const wxString& pMessage) {
    char* tmpbuf = wxStrdup(pMessage.mb_str());
    int msgsize = strlen(tmpbuf);
    char* buf = CreateBuffer(&msgsize);
    memset(buf+2,0x0,msgsize);
    memcpy(buf+2,tmpbuf,msgsize);
    free(tmpbuf);

    if (pMode == THREADS) {
        ThreadWorker* c = new ThreadWorker(m_host,buf,msgsize+2);
        if (c->Create() != wxTHREAD_NO_ERROR) {
            wxLogError(wxT("Cannot create more threads"));
        } else {
            c->Run();
            m_threadWorkers.Append(c);
        }
    } else {
        EventWorker* e = new EventWorker(m_host,buf,msgsize+2);
        e->Run();
        m_eventWorkers.Append(e);
    }
    m_statConnecting++;
}
示例#24
0
/* [implicit_jscontext] dpoIData mapData (in jsval source); */
NS_IMETHODIMP dpoCContext::MapData(const jsval & source, JSContext *cx, dpoIData **_retval)
{
  cl_int err_code;
  nsresult result;
  JSObject *tArray;
  nsCOMPtr<dpoCData> data;

  result = ExtractArray( source, &tArray, cx);
  if (NS_SUCCEEDED(result)) {
    // we have a typed array
    data = new dpoCData( this);
    if (data == NULL) {
      DEBUG_LOG_STATUS("MapData", "Cannot create new dpoCData object");
      return NS_ERROR_OUT_OF_MEMORY;
    }

    // USE_HOST_PTR is save as the CData object will keep the associated typed array alive as long as the
    // memory buffer lives
    cl_mem_flags flags = CL_MEM_READ_ONLY;
    void *tArrayBuffer = NULL;
    size_t arrayByteLength = JS_GetTypedArrayByteLength(tArray, cx);
    if(arrayByteLength == 0) {
        arrayByteLength = 1;
    }
    else {
        tArrayBuffer = GetPointerFromTA(tArray, cx);
        flags |= CL_MEM_USE_HOST_PTR;
    }

    cl_mem memObj = CreateBuffer(flags, arrayByteLength, tArrayBuffer , &err_code);
    if (err_code != CL_SUCCESS) {
      DEBUG_LOG_ERROR("MapData", err_code);
      return NS_ERROR_NOT_AVAILABLE;
    }

    result = data->InitCData(cx, cmdQueue, memObj, JS_GetTypedArrayType(tArray, cx), JS_GetTypedArrayLength(tArray, cx), 
        JS_GetTypedArrayByteLength(tArray, cx), tArray);

#ifdef SUPPORT_MAPPING_ARRAYS
  } else if (JSVAL_IS_OBJECT(source)) {
    // maybe it is a regular array. 
    //
    // WARNING: We map a pointer to the actual array here. All this works on CPU only
    //          and only of the OpenCL compiler knows what to do! For the current Intel OpenCL SDK
    //          this works but your milage may vary.
    const jsval *elems = UnsafeDenseArrayElements(cx, JSVAL_TO_OBJECT(source));
    if (elems != NULL) {
      data = new dpoCData( this);
      if (data == NULL) {
        DEBUG_LOG_STATUS("MapData", "Cannot create new dpoCData object");
        return NS_ERROR_OUT_OF_MEMORY;
      }
	  cl_mem memObj = CreateBuffer(CL_MEM_COPY_HOST_PTR | CL_MEM_READ_ONLY, sizeof(double *), &elems, &err_code);
      if (err_code != CL_SUCCESS) {
        DEBUG_LOG_ERROR("MapData", err_code);
        return NS_ERROR_NOT_AVAILABLE;
      }
      result = data->InitCData(cx, cmdQueue, memObj, 0 /* bogus type */, 1, sizeof(double *), JSVAL_TO_OBJECT(source));
#ifndef DEBUG_OFF
    } else {
        DEBUG_LOG_STATUS("MapData", "No elements returned!");
#endif /* DEBUG_OFF */
    }
#endif /* SUPPORT_MAPPING_ARRAYS */
  }

  if (NS_SUCCEEDED(result)) {
    data.forget((dpoCData **)_retval);
  }

  return result;
}
示例#25
0
HRESULT CAppStream::ProcessOutputs( BYTE **ppbOutData )
{
    HRESULT hr = S_OK;
    DWORD   dwStatus=0;
    ULONG   ulSize=0;
    BYTE    *pOut=0;

    CMediaBuffer            *pOutputBuffer;
    DMO_OUTPUT_DATA_BUFFER  dataBufferStruct;

    hr = CreateBuffer( m_uDataSize,&pOutputBuffer );
    if ( FAILED( hr ) ) {
        return hr;
    }

    dataBufferStruct.pBuffer      = pOutputBuffer;
    dataBufferStruct.dwStatus     = 0;  // No flag is set
    dataBufferStruct.rtTimestamp  = 0;  // not used in ProcessOutput()
    dataBufferStruct.rtTimelength = 0;  // not used in ProcessOutput()

    *ppbOutData = new BYTE[m_uDataSize];
    if( *ppbOutData == 0 ){
       return E_OUTOFMEMORY;
    }

    //process until no more data
    if (SUCCEEDED(hr)) do {
        hr = m_pObject->ProcessOutput(  DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER,
                                        1, //output buffer count
                                        &dataBufferStruct,
                                        &dwStatus );
        if ( FAILED( hr ) ) {
            return hr;
        }

        if( SUCCEEDED(hr) && (hr != S_FALSE) ) {
            hr = dataBufferStruct.pBuffer->GetBufferAndLength(&pOut, &ulSize);
            if ( FAILED( hr ) ) {
                return hr;
            }

            CopyMemory(*ppbOutData, pOut, m_uDataSize);

            hr = dataBufferStruct.pBuffer->SetLength( 0 );
            if( FAILED( hr ) ) {
                break;
            }
        }

    } while ( dataBufferStruct.dwStatus & DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE );

    // free output buffer allocated:
    SAFE_RELEASE( pOutputBuffer );

    // Send Discontinuity on output stream
    hr = m_pObject->Discontinuity( 0 );
    if ( FAILED( hr ) ) {
        return hr;
    }

    return hr;
}
示例#26
0
HRESULT CAppStream::Stream( BYTE **ppbOutData, ULONG *pbDataSize, LPWAVEFORMATEX *ppwfx )
{
    HRESULT         hr = S_OK;
    BYTE            *pOut;

    *pbDataSize     = m_uDataSize;
    *ppwfx          = m_pwfx;

    if ( m_pObjectInPlace ){

        pOut = new BYTE [m_uDataSize];

        if( pOut == 0 ){
            return E_OUTOFMEMORY;
        }
        CopyMemory(pOut, m_pbInData, m_uDataSize);

        // pass the number of samples to Process()
        hr = m_pObjectInPlace->Process( m_uDataSize,
                                        pOut,
                                        0,
                                        DMO_INPLACE_NORMAL);
        if( FAILED( hr ) ){
            return hr;
        }
        *ppbOutData = pOut;
        SAFE_RELEASE( m_pObjectInPlace );
    }
    else
    {
        CMediaBuffer            *pInputBuffer;
        const REFERENCE_TIME    rtStart     = 0;
        const REFERENCE_TIME    rtStop      = 0;
        BYTE*                   pBuffer;
        DWORD                   dwLength;

        // create and fill CMediaBuffer
        hr = CreateBuffer(m_uDataSize, &pInputBuffer);
        if( FAILED( hr ) ){
            return hr;
        }

        hr = pInputBuffer->GetBufferAndLength( &pBuffer, &dwLength );
        if( FAILED( hr ) ){
            return hr;
        }
        CopyMemory(pBuffer, m_pbInData, m_uDataSize);

        hr = pInputBuffer->SetLength( m_uDataSize );
        if( FAILED( hr ) ){
            return hr;
        }

        // call processInput
        hr = m_pObject->ProcessInput( 0,
                                pInputBuffer,
                                DMO_INPUT_DATA_BUFFERF_SYNCPOINT,
                                rtStart,
                                rtStop - rtStart);
        if( FAILED( hr ) ){
            return hr;
        }

        //release input buffer
        SAFE_RELEASE( pInputBuffer );

        // retrieve the output data from DMO and put into pOut
        if(S_FALSE == hr){
            return E_FAIL;
        } else {
            pOut = NULL;
            hr = ProcessOutputs( &pOut );
            if( FAILED( hr ) ){
                delete [] pOut;
                return hr;
            }
        }

        *ppbOutData = pOut;
        SAFE_RELEASE( m_pObject );
    }

    return S_OK;
}
// Constructor helper
void  RenderDevice::initShadersAndStates()
{
    CurRenderTarget = NULL;
    for(int i = 0; i < Shader_Count; i++)
    {
        UniformBuffers[i] = *CreateBuffer();
        MaxTextureSet[i] = 0;
    }

    ID3D10Blob* vsData = CompileShader("vs_4_0", DirectVertexShaderSrc);
    VertexShaders[VShader_MV] = *new VertexShader(this, vsData);
    for(int i = 1; i < VShader_Count; i++)
    {
        VertexShaders[i] = *new VertexShader(this, CompileShader("vs_4_0", VShaderSrcs[i]));
    }

    for(int i = 0; i < FShader_Count; i++)
    {
        PixelShaders[i] = *new PixelShader(this, CompileShader("ps_4_0", FShaderSrcs[i]));
    }

    intptr_t            bufferSize = vsData->GetBufferSize();
    const void*         buffer     = vsData->GetBufferPointer();
    ModelVertexIL = NULL;
    ID3D11InputLayout** objRef     = &ModelVertexIL.GetRawRef();

    HRESULT validate = Device->CreateInputLayout(ModelVertexDesc, sizeof(ModelVertexDesc)/sizeof(D3D11_INPUT_ELEMENT_DESC),
        buffer, bufferSize, objRef);
    OVR_UNUSED(validate);

    Ptr<ShaderSet> gouraudShaders = *new ShaderSet();
    gouraudShaders->SetShader(VertexShaders[VShader_MVP]);
    gouraudShaders->SetShader(PixelShaders[FShader_Gouraud]);
    DefaultFill = *new ShaderFill(gouraudShaders);

    D3D11_BLEND_DESC bm;
    memset(&bm, 0, sizeof(bm));
    bm.RenderTarget[0].BlendEnable = true;
    bm.RenderTarget[0].BlendOp     = bm.RenderTarget[0].BlendOpAlpha    = D3D11_BLEND_OP_ADD;
    bm.RenderTarget[0].SrcBlend    = bm.RenderTarget[0].SrcBlendAlpha   = D3D11_BLEND_SRC_ALPHA;
    bm.RenderTarget[0].DestBlend   = bm.RenderTarget[0].DestBlendAlpha  = D3D11_BLEND_INV_SRC_ALPHA;
    bm.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
    BlendState = NULL;
    Device->CreateBlendState(&bm, &BlendState.GetRawRef());

    D3D11_RASTERIZER_DESC rs;
    memset(&rs, 0, sizeof(rs));
    rs.AntialiasedLineEnable = true;
    rs.CullMode              = D3D11_CULL_BACK;    
    rs.DepthClipEnable       = true;
    rs.FillMode              = D3D11_FILL_SOLID;
    Rasterizer = NULL;
    Device->CreateRasterizerState(&rs, &Rasterizer.GetRawRef());

    QuadVertexBuffer = *CreateBuffer();
    const Vertex QuadVertices[] =
    { Vertex(Vector3f(0, 1, 0)), Vertex(Vector3f(1, 1, 0)),
    Vertex(Vector3f(0, 0, 0)), Vertex(Vector3f(1, 0, 0)) };
    QuadVertexBuffer->Data(Buffer_Vertex, QuadVertices, sizeof(QuadVertices));

    SetDepthMode(0, 0);
}
示例#28
0
/* [implicit_jscontext] dpoIData allocateData2 (in dpoIData templ, [optional] in uint32_t length); */
NS_IMETHODIMP dpoCContext::AllocateData2(dpoIData *templ, uint32_t length, JSContext *cx, dpoIData **_retval) 
{
	// this cast is only safe as long as no other implementations of the dpoIData interface exist
	dpoCData *cData = (dpoCData *) templ;
	cl_int err_code;
	nsresult result;
	size_t bytePerElements;
	nsCOMPtr<dpoCData> data;
#ifdef PREALLOCATE_IN_JS_HEAP
	jsval jsBuffer;
#endif /* PREALLOCATE_IN_JS_HEAP */

	if (!JS_EnterLocalRootScope(cx)) {
		DEBUG_LOG_STATUS("AllocateData2", "Cannot root local scope");
		return NS_ERROR_NOT_AVAILABLE;
	}

	data = new dpoCData( this);
	if (data == NULL) {
		DEBUG_LOG_STATUS("AllocateData2", "Cannot create new dpoCData object");
		return NS_ERROR_OUT_OF_MEMORY;
	}
	
	if (length == 0) {
		DEBUG_LOG_STATUS("AllocateData2", "length not provided, assuming template's size");
		length = cData->GetLength();
	}

	bytePerElements = cData->GetSize() / cData->GetLength();

	DEBUG_LOG_STATUS("AllocateData2", "length " << length << " bytePerElements " << bytePerElements);

#ifdef PREALLOCATE_IN_JS_HEAP
	JSObject *jsArray;
	if (NS_FAILED(CreateAlignedTA(cData->GetType(), length, &jsArray, cx))) {
		return NS_ERROR_NOT_AVAILABLE;
	}
	if (!jsArray) {
		DEBUG_LOG_STATUS("AllocateData2", "Cannot create typed array");
		return NS_ERROR_OUT_OF_MEMORY;
	}

	cl_mem memObj = CreateBuffer(CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, 
                                 JS_GetTypedArrayByteLength(jsArray, cx), JS_GetArrayBufferViewData(jsArray, cx), &err_code);
#else /* PREALLOCATE_IN_JS_HEAP */
	JSObject *jsArray = NULL;
	cl_mem memObj = CreateBuffer(CL_MEM_READ_WRITE, length * bytePerElements, NULL, &err_code);
#endif /* PREALLOCATE_IN_JS_HEAP */
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("AllocateData2", err_code);
		return NS_ERROR_NOT_AVAILABLE;
	}

	result = data->InitCData(cx, cmdQueue, memObj, cData->GetType(), length, length * bytePerElements, jsArray);

	if (NS_SUCCEEDED(result)) {
		data.forget((dpoCData **) _retval);
	}

	JS_LeaveLocalRootScope(cx);
		
    return result;
}
示例#29
0
/* [implicit_jscontext] dpoIData allocateData (in jsval templ, [optional] in uint32_t length); */
NS_IMETHODIMP dpoCContext::AllocateData(const jsval & templ, uint32_t length, JSContext *cx, dpoIData **_retval)
{
	cl_int err_code;
	nsresult result;
	JSObject *tArray;
	size_t bytePerElements;
	nsCOMPtr<dpoCData> data;

	if (!JS_EnterLocalRootScope(cx)) {
		DEBUG_LOG_STATUS("AllocateData", "Cannot root local scope");
		return NS_ERROR_NOT_AVAILABLE;
	}

	result = ExtractArray( templ, &tArray, cx);
	if (NS_FAILED(result)) {
		return result;
	}

	data = new dpoCData( this);
	if (data == NULL) {
		DEBUG_LOG_STATUS("AllocateData", "Cannot create new dpoCData object");
		return NS_ERROR_OUT_OF_MEMORY;
	}
	
	if (length == 0) {
		DEBUG_LOG_STATUS("AllocateData", "size not provided, assuming template's size");
		length = JS_GetTypedArrayLength(tArray, cx);
	}

	bytePerElements = JS_GetTypedArrayByteLength(tArray, cx) / JS_GetTypedArrayLength(tArray, cx);

	DEBUG_LOG_STATUS("AllocateData", "length " << length << " bytePerElements " << bytePerElements);

#ifdef PREALLOCATE_IN_JS_HEAP
	JSObject *jsArray;
	if (NS_FAILED(CreateAlignedTA(JS_GetTypedArrayType(tArray, cx), length, &jsArray, cx))) {
		return NS_ERROR_NOT_AVAILABLE;
	}
	if (!jsArray) {
		DEBUG_LOG_STATUS("AllocateData", "Cannot create typed array");
		return NS_ERROR_OUT_OF_MEMORY;
	}

	cl_mem memObj = CreateBuffer( CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, 
                                  JS_GetTypedArrayByteLength(jsArray, cx), GetPointerFromTA(jsArray, cx), &err_code);
#else /* PREALLOCATE_IN_JS_HEAP */
	JSObject *jsArray =  nullptr;
	cl_mem memObj = CreateBuffer(CL_MEM_READ_WRITE, length * bytePerElements, NULL, &err_code);
#endif /* PREALLOCATE_IN_JS_HEAP */
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("AllocateData", err_code);
		return NS_ERROR_NOT_AVAILABLE;
	}

	result = data->InitCData(cx, cmdQueue, memObj, JS_GetTypedArrayType(tArray, cx), length, length * bytePerElements, jsArray);

	if (NS_SUCCEEDED(result)) {
		data.forget((dpoCData **) _retval);
	}

	JS_LeaveLocalRootScope(cx);

    return result;
}
示例#30
0
nsresult dpoCContext::InitContext(cl_platform_id platform)
{
	cl_int err_code;
	cl_device_id *devices;
	size_t cb;

#ifdef INCREMENTAL_MEM_RELEASE
	defer_list = (cl_mem *)nsMemory::Alloc(DEFER_LIST_LENGTH * sizeof(cl_mem));
	defer_pos = 0;
	defer_max = DEFER_LIST_LENGTH;
#endif /* INCREMENTAL_MEM_RELEASE */

	cl_context_properties context_properties[3] = {CL_CONTEXT_PLATFORM, (cl_context_properties)platform, NULL};
	
	context = clCreateContextFromType(context_properties, CL_DEVICE_TYPE_CPU, ReportCLError, this, &err_code);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("InitContext", err_code);
		return NS_ERROR_NOT_AVAILABLE;
	}

	err_code = clGetContextInfo(context, CL_CONTEXT_DEVICES, 0, NULL, &cb);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("InitContext", err_code);
		return NS_ERROR_NOT_AVAILABLE;
	}

	devices = (cl_device_id *)nsMemory::Alloc(sizeof(cl_device_id)*cb);
	if (devices == NULL) {
		DEBUG_LOG_STATUS("InitContext", "Cannot allocate device list");
		return NS_ERROR_OUT_OF_MEMORY;
	}

	err_code = clGetContextInfo(context, CL_CONTEXT_DEVICES, cb, devices, NULL);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("InitContext", err_code);
		nsMemory::Free(devices);
		return NS_ERROR_NOT_AVAILABLE;
	}

	cmdQueue = clCreateCommandQueue(context, devices[0], 
#ifdef CLPROFILE 
		CL_QUEUE_PROFILING_ENABLE |
#endif /* CLPROFILE */
#ifdef OUTOFORDERQUEUE
		CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE |
#endif /* OUTOFORDERQUEUE */
		0,
		&err_code);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("InitContext", err_code);
		nsMemory::Free(devices);
		return NS_ERROR_NOT_AVAILABLE;
	}
	
	DEBUG_LOG_STATUS("InitContext", "queue is " << cmdQueue);

	err_code = clGetDeviceInfo(devices[0], CL_DEVICE_MEM_BASE_ADDR_ALIGN, sizeof(alignment_size), &alignment_size, NULL);
	if (err_code != CL_SUCCESS) {
		/* we can tolerate this, simply do not align */
		alignment_size = 8;
	} 
	/* we use byte, not bits */
	if (alignment_size % 8) {
		/* they align on sub-byte borders? Odd architecture this must be. Give up */
		alignment_size = 1;
	} else {
		alignment_size = alignment_size / 8;
	}

	nsMemory::Free(devices);

	kernelFailureMem = CreateBuffer(CL_MEM_READ_WRITE, sizeof(int), NULL, &err_code);
	if (err_code != CL_SUCCESS) {
		DEBUG_LOG_ERROR("InitContext", err_code);
		return NS_ERROR_NOT_AVAILABLE;
	}

	return NS_OK;
}