Пример #1
0
void test::TestEntityPool() {
    auto entities = new stoked::EntityPool(4);

    auto e1 = entities->Create();
    auto e2 = entities->Create();
    auto e3 = entities->Create();
    auto e4 = entities->Create();

    assert(e1 != nullptr);
    assert(e2 != nullptr);
    assert(e3 != nullptr);
    assert(e4 != nullptr);

    assert(e1->GetID() < entities->GetCapacity());
    assert(e2->GetID() < entities->GetCapacity());
    assert(e3->GetID() < entities->GetCapacity());
    assert(e4->GetID() < entities->GetCapacity());

    assert(entities->Empty() && !entities->Available());

    entities->FreeAll();

    assert(!entities->Empty() && entities->Available());

    e1 = entities->Create();
    bool freeResult = entities->Free(e1);
    assert(freeResult == true);

    delete entities;

    PASSED();
}
Пример #2
0
nsresult
Http2PushTransactionBuffer::WriteSegments(nsAHttpSegmentWriter *writer,
        uint32_t count, uint32_t *countWritten)
{
    if ((mBufferedHTTP1Size - mBufferedHTTP1Used) < 20480) {
        EnsureBuffer(mBufferedHTTP1,mBufferedHTTP1Size + kDefaultBufferSize,
                     mBufferedHTTP1Used, mBufferedHTTP1Size);
    }

    count = std::min(count, mBufferedHTTP1Size - mBufferedHTTP1Used);
    nsresult rv = writer->OnWriteSegment(mBufferedHTTP1 + mBufferedHTTP1Used,
                                         count, countWritten);
    if (NS_SUCCEEDED(rv)) {
        mBufferedHTTP1Used += *countWritten;
    }
    else if (rv == NS_BASE_STREAM_CLOSED) {
        mIsDone = true;
    }

    if (Available() || mIsDone) {
        Http2Stream *consumer = mPushStream->GetConsumerStream();

        if (consumer) {
            LOG3(("Http2PushTransactionBuffer::WriteSegments notifying connection "
                  "consumer data available 0x%X [%u] done=%d\n",
                  mPushStream->StreamID(), Available(), mIsDone));
            mPushStream->ConnectPushedStream(consumer);
        }
    }

    return rv;
}
Пример #3
0
 void EGLWindow::Initialize(const WindowConfig &config)
 {
     s_assert(!Available());
     mConfig = config;
     mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
     s_assert(Available());
     s_assert(eglGetError() == EGL_SUCCESS);
     if (!eglInitialize(mEGLDisplay, nullptr, nullptr)) {
         s_error("Initialize EGL failed!\n");
         return;
     }
 }
Пример #4
0
void cVideoBufferFile::Put(uint8_t *buf, unsigned int size)
{
  if (Available() + MARGIN >= m_BufferSize)
  {
    return;
  }

  if ((m_BufferSize - m_WritePtr) <= size)
  {
    int bytes = m_BufferSize - m_WritePtr;

    int p = 0;
    off_t ptr = m_WritePtr;
    while(bytes > 0)
    {
      p = pwrite(m_Fd, buf, bytes, ptr);
      if (p < 0)
      {
        ERRORLOG("Could not write to file: %s", (const char*)m_Filename);
        return;
      }
      size -= p;
      bytes -= p;
      buf += p;
      ptr += p;
    }
    cMutexLock lock(&m_Mutex);
    m_WritePtr = 0;
  }

  off_t ptr = m_WritePtr;
  int bytes = size;
  int p;
  while(bytes > 0)
  {
    p = pwrite(m_Fd, buf, bytes, ptr);
    if (p < 0)
    {
      ERRORLOG("Could not write to file: %s", (const char*)m_Filename);
      return;
    }
    bytes -= p;
    buf += p;
    ptr += p;
  }

  cMutexLock lock(&m_Mutex);

  m_WritePtr += size;
  if (!m_BufferFull)
  {
    if ((m_WritePtr + 2*MARGIN) > m_BufferSize)
    {
      m_BufferFull = true;
      time(&m_bufferWrapTime);
    }
  }

  time(&m_bufferEndTime);
}
void
MediaSourceInputAdapter::NotifyListener()
{
  if (!mCallback) {
    return;
  }
  // Don't notify unless more data is available than the threshold, except
  // in the case that there's no more data coming.
  if (Available() < mNotifyThreshold && !mClosed && !mMediaSource->AppendDone()) {
    return;
  }
  nsCOMPtr<nsIInputStreamCallback> callback;
  if (mCallbackTarget) {
    callback = NS_NewInputStreamReadyEvent(mCallback, mCallbackTarget);
  } else {
    callback = mCallback;
  }
  MOZ_ASSERT(callback);
  mCallback = nullptr;
  mCallbackTarget = nullptr;
  mNotifyThreshold = 0;
  LOG(PR_LOG_DEBUG, ("%p IA::NotifyListener", this));
  callback->OnInputStreamReady(this);

}
Пример #6
0
void cVideoBufferRAM::Put(uint8_t *buf, unsigned int size)
{
  if (Available() + MARGIN >= m_BufferSize)
  {
    ERRORLOG("------------- skipping data");
    return;
  }

  if ((m_BufferSize - m_WritePtr) <= size)
  {
    int bytes = m_BufferSize - m_WritePtr;
    memcpy(m_BufferPtr+m_WritePtr, buf, bytes);
    size -= bytes;
    buf += bytes;
    cMutexLock lock(&m_Mutex);
    m_WritePtr = 0;
  }

  memcpy(m_BufferPtr+m_WritePtr, buf, size);

  cMutexLock lock(&m_Mutex);

  m_WritePtr += size;
  if (!m_BufferFull)
  {
    if ((m_WritePtr + 2*MARGIN) > m_BufferSize)
    {
      m_BufferFull = true;
      time(&m_bufferWrapTime);
    }
  }

  time(&m_bufferEndTime);
}
Пример #7
0
int LightProcess::pclose(FILE *f) {
  if (!Available()) {
    return ::pclose(f);
  }

  int id = GetId();
  Lock lock(g_procs[id].m_procMutex);

  std::map<int64_t, int64_t>::iterator it = g_procs[id].m_popenMap.find((int64_t)f);
  if (it == g_procs[id].m_popenMap.end()) {
    // try to close it with normal pclose
    return ::pclose(f);
  }

  int64_t f2 = it->second;
  g_procs[id].m_popenMap.erase((int64_t)f);
  fclose(f);

  lwp_write(g_procs[id].m_afdt_fd, "pclose");
  lwp_write_int64(g_procs[id].m_afdt_fd, f2);

  int ret = -1;
  lwp_read_int32(g_procs[id].m_afdt_fd, ret);
  if (ret < 0) {
    lwp_read_int32(g_procs[id].m_afdt_fd, errno);
  }
  return ret;
}
Пример #8
0
 const char *Peek(size_t *len) {
   if (Available() > 0 && buf_size_ == 0) {
     Get();
   }
   *len = buf_size_;
   return buf_begin_;
 }
Пример #9
0
pid_t LightProcess::waitpid(pid_t pid, int *stat_loc, int options,
                            int timeout) {
  if (!Available()) {
    // light process is not really there
    return ::waitpid(pid, stat_loc, options);
  }

  int id = GetId();
  Lock lock(g_procs[id].m_procMutex);

  auto fout = g_procs[id].m_afdt_fd;
  lwp_write(fout, "waitpid");
  lwp_write_int64(fout, (int64_t)pid);
  lwp_write_int32(fout, options);
  lwp_write_int32(fout, timeout);

  int64_t ret;
  int stat;
  auto fin = g_procs[id].m_afdt_fd;
  lwp_read_int64(fin, ret);
  lwp_read_int32(fin, stat);

  *stat_loc = stat;
  if (ret < 0) {
    lwp_read_int32(fin, errno);
  }
  return (pid_t)ret;
}
Пример #10
0
pid_t LightProcess::waitpid(pid_t pid, int *stat_loc, int options,
                            int timeout) {
  if (!Available()) {
    // light process is not really there
    return ::waitpid(pid, stat_loc, options);
  }

  int id = GetId();
  Lock lock(g_procs[id].m_procMutex);

  fprintf(g_procs[id].m_fout, "waitpid\n%" PRId64 " %d %d\n", (int64_t)pid, options,
          timeout);
  fflush(g_procs[id].m_fout);

  char buf[BUFFER_SIZE];
  read_buf(g_procs[id].m_fin, buf);
  if (!buf[0]) return -1;
  int64_t ret;
  int stat;
  sscanf(buf, "%" PRId64 " %d", &ret, &stat);
  *stat_loc = stat;
  if (ret < 0) {
    read_buf(g_procs[id].m_fin, buf);
    sscanf(buf, "%d", &errno);
  }
  return (pid_t)ret;
}
Пример #11
0
int LightProcess::pclose(FILE *f) {
  if (!Available()) {
    return ::pclose(f);
  }

  int id = GetId();
  Lock lock(g_procs[id].m_procMutex);

  std::map<int64_t, int64_t>::iterator it = g_procs[id].m_popenMap.find((int64_t)f);
  if (it == g_procs[id].m_popenMap.end()) {
    // try to close it with normal pclose
    return ::pclose(f);
  }

  int64_t f2 = it->second;
  g_procs[id].m_popenMap.erase((int64_t)f);
  fclose(f);
  fprintf(g_procs[id].m_fout, "pclose\n%" PRId64 "\n", f2);
  fflush(g_procs[id].m_fout);

  char buf[BUFFER_SIZE];
  read_buf(g_procs[id].m_fin, buf);
  int ret = -1;
  sscanf(buf, "%d", &ret);
  if (ret < 0) {
    read_buf(g_procs[id].m_fin, buf);
    sscanf(buf, "%d", &errno);
  }
  return ret;
}
Пример #12
0
 void EGLWindow::Finalize()
 {
     s_assert(Available());
     eglDestroyContext(mEGLDisplay, mEGLContext);
     eglDestroySurface(mEGLDisplay, mEGLSurface);
     eglTerminate(mEGLDisplay);
     mEGLDisplay = mEGLContext = mEGLSurface = nullptr;
 }
Пример #13
0
 void Graphics::Finalize()
 {
     s_assert(Available());
     mConfig = GraphicsConfig();
     mRenderer->Finalize();
     mCanvas->Finalize();
     mResourceManager->Finalize();
     mRenderer = nullptr;
 }
Пример #14
0
void FileInputStream::Skip(int64_t skip)
{
	if (skip <= 0) {
		return;
	}

	int r = skip;

	if (skip > Available()) {
		r = Available();
	}

	char *tmp = new char[r];

	r = _file->Read((char *)tmp, r);

	delete [] tmp;
}
Пример #15
0
void LightProcess::Initialize(const std::string &prefix, int count,
                              const std::vector<int> &inherited_fds) {
  if (prefix.empty() || count <= 0) {
    return;
  }

  if (Available()) {
    // already initialized
    return;
  }

  g_procs.reset(new LightProcess[count]);
  g_procsCount = count;

  auto afdt_filename = folly::sformat("{}.{}", prefix, getpid());

  // remove the possible leftover
  remove(afdt_filename.c_str());

  afdt_error_t err = AFDT_ERROR_T_INIT;
  auto afdt_lid = afdt_listen(afdt_filename.c_str(), &err);
  if (afdt_lid < 0) {
    Logger::Warning("Unable to afdt_listen to %s: %d %s",
                    afdt_filename.c_str(),
                    errno, folly::errnoStr(errno).c_str());
    return;
  }

  SCOPE_EXIT {
    ::close(afdt_lid);
    remove(afdt_filename.c_str());
  };

  for (int i = 0; i < count; i++) {
    if (!g_procs[i].initShadow(afdt_lid, afdt_filename, i, inherited_fds)) {
      for (int j = 0; j < i; j++) {
        g_procs[j].closeShadow();
      }
      g_procs.reset();
      g_procsCount = 0;
      break;
    }
  }

  if (!s_handlerInited) {
    struct sigaction sa;
    struct sigaction old_sa;
    sa.sa_sigaction = &LightProcess::SigChldHandler;
    sa.sa_flags = SA_SIGINFO | SA_NOCLDSTOP;
    if (sigaction(SIGCHLD, &sa, &old_sa) != 0) {
      Logger::Error("Couldn't install SIGCHLD handler");
      abort();
    }
    s_handlerInited = true;
  }
}
  // Append aLength bytes from aSrc to the buffer.  Caller must check that
  // sufficient space is available.
  void AppendElements(const uint8_t* aSrc, uint32_t aLength) {
    NS_ABORT_IF_FALSE(mBuffer && mCapacity, "Buffer not initialized.");
    NS_ABORT_IF_FALSE(aLength <= Available(), "Buffer full.");

    uint32_t end = (mStart + mCount) % mCapacity;

    uint32_t toCopy = std::min(mCapacity - end, aLength);
    memcpy(&mBuffer[end], aSrc, toCopy);
    memcpy(&mBuffer[0], aSrc + toCopy, aLength - toCopy);
    mCount += aLength;
  }
Пример #17
0
	void WaitForWriteCapacity(int amt)
	{
		for (; ; )
		{
			//dont return when available == amt because then we would consume the buffer and be unable to distinguish between full and empty
			if (Available() > amt)
				return;
			//this is a greedy spinlock.
			SwitchToThread();
		}
	}
Пример #18
0
pid_t LightProcess::proc_open(const char *cmd, const std::vector<int> &created,
                              const std::vector<int> &desired,
                              const char *cwd,
                              const std::vector<std::string> &env) {
  int id = GetId();
  Lock lock(g_procs[id].m_procMutex);
  always_assert(Available());
  always_assert(created.size() == desired.size());

  auto fout = g_procs[id].m_afdt_fd;
  lwp_write(fout, "proc_open");
  lwp_write(fout, cmd);
  lwp_write(fout, cwd ? cwd : "");
  lwp_write_int32(fout, (int)env.size());
  for (unsigned int i = 0; i < env.size(); i++) {
    lwp_write(fout, env[i]);
  }

  lwp_write_int32(fout, (int)created.size());
  for (unsigned int i = 0; i < desired.size(); i++) {
    lwp_write_int32(fout, desired[i]);
  }

  bool error_send = false;
  int save_errno = 0;
  for (unsigned int i = 0; i < created.size(); i++) {
    if (!send_fd(g_procs[id].m_afdt_fd, created[i])) {
      error_send = true;
      save_errno = errno;
      break;
    }
  }

  std::string buf;
  auto fin = g_procs[id].m_afdt_fd;
  lwp_read(fin, buf);
  if (buf == "error") {
    lwp_read_int32(fin, errno);
    if (error_send) {
      // On this error, the receiver side returns dummy errno,
      // use the sender side errno here.
      errno = save_errno;
    }
    return -1;
  }
  always_assert_flog(buf == "success",
                     "Unexpected message from light process: `{}'", buf);
  int64_t pid = -1;
  lwp_read_int64(fin, pid);
  always_assert(pid);
  return (pid_t)pid;
}
Пример #19
0
int CFBO::Disable (void)
{
if (!gameStates.ogl.bRender2TextureOk)
	return 0;
glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, 0);
#if 1//def _DEBUG
if (!Available ())
	return 0;
#endif
//glBindTexture (GL_TEXTURE_2D, m_info.hRenderBuffer);
OglSetDrawBuffer (GL_BACK, 1);
return 1;
}
Пример #20
0
pid_t LightProcess::proc_open(const char *cmd, const std::vector<int> &created,
                              const std::vector<int> &desired,
                              const char *cwd,
                              const std::vector<std::string> &env) {
  int id = GetId();
  Lock lock(g_procs[id].m_procMutex);
  always_assert(Available());
  always_assert(created.size() == desired.size());

  if (fprintf(g_procs[id].m_fout, "proc_open\n%s\n%s\n", cmd, cwd) <= 0) {
    Logger::Error("Failed to send command proc_open");
    return -1;
  }
  fprintf(g_procs[id].m_fout, "%d\n", (int)env.size());
  for (unsigned int i = 0; i < env.size(); i++) {
    fprintf(g_procs[id].m_fout, "%s\n", env[i].c_str());
  }

  fprintf(g_procs[id].m_fout, "%d\n", (int)created.size());

  for (unsigned int i = 0; i < desired.size(); i++) {
    fprintf(g_procs[id].m_fout, "%d\n", desired[i]);
  }
  fflush(g_procs[id].m_fout);
  bool error_send = false;
  int save_errno = 0;
  for (unsigned int i = 0; i < created.size(); i++) {
    if (!send_fd(g_procs[id].m_afdt_fd, created[i])) {
      error_send = true;
      save_errno = errno;
      break;
    }
  }

  char buf[BUFFER_SIZE];
  read_buf(g_procs[id].m_fin, buf);
  if (strncmp(buf, "error", 5) == 0) {
    read_buf(g_procs[id].m_fin, buf);
    sscanf(buf, "%d", &errno);
    if (error_send) {
      // On this error, the receiver side returns dummy errno,
      // use the sender side errno here.
      errno = save_errno;
    }
    return -1;
  }
  int64_t pid = -1;
  sscanf(buf, "%" PRId64, &pid);
  assert(pid);
  return (pid_t)pid;
}
Пример #21
0
int cVideoBufferRAM::ReadBlock(uint8_t **buf, unsigned int size, time_t &endTime, time_t &wrapTime)
{
  // move read pointer
  if (m_BytesConsumed)
  {
    cMutexLock lock(&m_Mutex);
    m_ReadPtr += m_BytesConsumed;
    if (m_ReadPtr >= m_BufferSize)
      m_ReadPtr -= m_BufferSize;

    endTime = m_bufferEndTime;
    wrapTime = m_bufferWrapTime;
  }
  m_BytesConsumed = 0;

  // check if we have anything to read
  off_t readBytes = Available();
  if (readBytes < m_Margin)
  {
    return 0;
  }

  // if we are close to end, copy margin to front
  if (m_ReadPtr > (m_BufferSize - m_Margin))
  {
    int bytesToCopy = m_BufferSize - m_ReadPtr;
    memmove(m_Buffer + (m_Margin - bytesToCopy), m_Buffer + m_ReadPtr, bytesToCopy);
    *buf = m_Buffer + (m_Margin - bytesToCopy);
  }
  else
    *buf = m_BufferPtr + m_ReadPtr;

  // Make sure we are looking at a TS packet
  while (readBytes > TS_SIZE)
  {
    if ((*buf)[0] == TS_SYNC_BYTE && (*buf)[TS_SIZE] == TS_SYNC_BYTE)
      break;
    m_BytesConsumed++;
    (*buf)++;
    readBytes--;
  }

  if ((*buf)[0] != TS_SYNC_BYTE)
  {
    return 0;
  }

  m_BytesConsumed += TS_SIZE;
  return TS_SIZE;
}
Пример #22
0
int CPBO::Disable (void)
{
if (Available () < 1)
	return 0;
#ifdef _WIN32
if (!wglMakeContextCurrentARB (hGlDC, hGlDC, hGlRC))
#else
if (!glXMakeCurrent (hGlDC, hGlWindow, hGlRC))
#endif
	return 0;
ogl.SetDrawBuffer (GL_BACK, 1);
OglSetReadBuffer (GL_FRONT, 1);
return 1;
}
Пример #23
0
int CPBO::Enable (void)
{
if (Available () < 1)
	return 0;
#ifdef _WIN32
if (!wglMakeContextCurrentARB (m_info.hDC, m_info.hDC, m_info.hRC))
#else
if (!glXMakeCurrent (m_info.hDC, m_info.hBuf, m_info.hRC))
#endif
	return 0;
ogl.SetDrawBuffer (GL_FRONT, 1);
OglSetReadBuffer (GL_FRONT, 1);
return 1;
}
Пример #24
0
int CFBO::Disable (bool bFallback)
{
if (!m_info.bActive)
	return 1;
if (Available () <= 0)
	return 0;
m_info.bActive = 0;
//if (bFallback) 
	{
	glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, 0);
	ogl.SetDrawBuffer (GL_BACK, 0);
	}
return 1;
}
Пример #25
0
uint32_t
NamedPipeInfo::Peek(void* aBuffer, int32_t aSize)
{
  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
  MOZ_ASSERT(mReadBegin <= mReadEnd);

  if (!IsConnected()) {
    // pipe unconnected
    PR_SetError(PR_NOT_CONNECTED_ERROR, 0);
    return -1;
  }

  /**
   * If there's nothing in the read buffer, try to trigger internal read
   * operation by calling |GetPollFlags|. This is required for callers that
   * use blocking I/O because they don't call |GetPollFlags| to read data,
   * but this also works for non-blocking I/O.
   */
  if (!Available()) {
    int16_t outFlag;
    GetPollFlags(PR_POLL_READ, &outFlag);

    if (!(outFlag & PR_POLL_READ)) {
      PR_SetError(IsNonblocking() ? PR_WOULD_BLOCK_ERROR
                                  : PR_IO_PENDING_ERROR,
                  0);
      return -1;
    }
  }

  // Available() can't return more than what fits to the buffer at the read offset.
  int32_t bytesRead = std::min<int32_t>(aSize, Available());
  MOZ_ASSERT(bytesRead >= 0);
  MOZ_ASSERT(mReadBegin + bytesRead <= mReadEnd);
  memcpy(aBuffer, &mReadBuffer[mReadBegin], bytesRead);
  return bytesRead;
}
Пример #26
0
void test::TestEmptyEntityPool() {
    auto entities = new stoked::EntityPool(2);
    entities->Create();
    entities->Create();
    assert(entities->Empty() && !entities->Available());

    auto nullEntity1 = entities->Create();
    auto nullEntity2 = entities->Create();

    assert(nullEntity1 == nullEntity2);
    assert(nullEntity1->IsNullEntity());
    assert(nullEntity2->IsNullEntity());

    PASSED();
}
Пример #27
0
int CFBO::Enable (bool bFallback)
{
if (m_info.bActive)
	return 1;
if (Available () <= 0)
	return 0;
//if (bFallback) 
	{
	glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, 0);
	ogl.SetDrawBuffer (GL_BACK, 0);
	}
glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, m_info.hFBO);
SetDrawBuffers ();
return m_info.bActive = 1;
}
Пример #28
0
FILE *LightProcess::popen(const char *cmd, const char *type,
                          const char *cwd /* = NULL */) {
  if (!Available()) {
    // fallback to normal popen
    Logger::Verbose("Light-weight fork not available; "
                    "use the heavy one instead.");
  } else {
    FILE *f = LightPopenImpl(cmd, type, cwd);
    if (f) {
      return f;
    }
    Logger::Verbose("Light-weight fork failed; use the heavy one instead.");
  }
  return HeavyPopenImpl(cmd, type, cwd);
}
Пример #29
0
int CFBO::Enable (void)
{
if (!gameStates.ogl.bRender2TextureOk)
	return 0;
glDrawBuffer (GL_BACK);
glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, 0);
gameStates.ogl.bDrawBufferActive = 0;
glBindTexture (GL_TEXTURE_2D, 0);
glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, m_info.hFBO);
#if 1//def _DEBUG
if (!Available ())
	return 0;
#endif
OglSetDrawBuffer (GL_COLOR_ATTACHMENT0_EXT, 1);
return 1;
}
Пример #30
0
pid_t LightProcess::pcntl_waitpid(pid_t pid, int *stat_loc, int options) {
  if (!Available()) {
    return ::waitpid(pid, stat_loc, options);
  }

  int id = GetId();
  Lock lock(g_procs[id].m_procMutex);

  pid_t p = ::waitpid(pid, stat_loc, options);
  if (p == g_procs[id].m_shadowProcess) {
    // got the shadow process, wait again
    p = ::waitpid(pid, stat_loc, options);
  }

  return p;
}