Beispiel #1
0
/* determine if out buffer threshold has been crossed, and if so, set
   the flush_required flag
*/
static int __check_outbufthresh_limit( Client *client, unsigned int cont_i,
                                     long packet_count, unsigned long wu_count,
                                     int *bufupd_pending )
{
  if ((*bufupd_pending & BUFFERUPDATE_FLUSH) == 0)
  {
    unsigned int thresh = ClientGetOutThreshold( client, cont_i, 0 );
    /* ClientGetOutThreshold() returns 0 if thresh doesn't need checking */
    if (thresh > 0) /* threshold _does_ need to be checked. */
    {
      if (packet_count < 0) /* not determined or error */
      {
        packet_count = GetBufferCount( client, cont_i, 1, &wu_count );
      }
      if (packet_count > 0) /* wu_count is valid */
      {
        if ((unsigned long)(wu_count) >= ((unsigned long)thresh))
        {
          *bufupd_pending |= BUFFERUPDATE_FLUSH;
        }
      }
    }
  }
  return ((*bufupd_pending & BUFFERUPDATE_FLUSH) != 0);
}
int BC_Example_Bridge(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
{
	int err = -EFAULT;
	int command = _IOC_NR(cmd);
	BC_Example_ioctl_package *psBridge = (BC_Example_ioctl_package *)arg;

	if(!access_ok(VERIFY_WRITE, psBridge, sizeof(BC_Example_ioctl_package)))
	{
		return err;
	}

	switch(command)
	{
		case _IOC_NR(BC_Example_ioctl_fill_buffer):
		{
			if(FillBuffer(psBridge->inputparam) == -1)
			{
				return err;
			}
			break;
		}
		case _IOC_NR(BC_Example_ioctl_get_buffer_count):
		{
			if(GetBufferCount(&psBridge->outputparam) == -1)
			{
				return err;
			}
			break;
		}
		default:
			return err;
	}

	return 0;
}
Beispiel #3
0
CConfig CChan::ToConfig() {
	CConfig config;
	CUser *pUser = m_pNetwork->GetUser();

	if (pUser->GetBufferCount() != GetBufferCount())
		config.AddKeyValuePair("Buffer", CString(GetBufferCount()));
	if (pUser->KeepBuffer() != KeepBuffer())
		config.AddKeyValuePair("KeepBuffer", CString(KeepBuffer()));
	if (IsDetached())
		config.AddKeyValuePair("Detached", "true");
	if (!GetKey().empty())
		config.AddKeyValuePair("Key", GetKey());
	if (!GetDefaultModes().empty())
		config.AddKeyValuePair("Modes", GetDefaultModes());

	return config;
}
Beispiel #4
0
bool CChan::WriteConfig(CFile& File) {
	if (!InConfig()) {
		return false;
	}

	File.Write("\t<Chan " + GetName().FirstLine() + ">\n");

	if (m_pUser->GetBufferCount() != GetBufferCount())
		m_pUser->PrintLine(File, "\tBuffer", CString(GetBufferCount()));
	if (m_pUser->KeepBuffer() != KeepBuffer())
		m_pUser->PrintLine(File, "\tKeepBuffer", CString(KeepBuffer()));
	if (IsDetached())
		m_pUser->PrintLine(File, "\tDetached", "true");
	if (!GetKey().empty())
		m_pUser->PrintLine(File, "\tKey", GetKey());
	if (!GetDefaultModes().empty())
		m_pUser->PrintLine(File, "\tModes", GetDefaultModes());

	File.Write("\t</Chan>\n");
	return true;
}
Beispiel #5
0
//     Internal function that loads 'wrdata' with a new workrecord
//     from the next open contest with available blocks.
// Return value:
//     if (return_single_count) is non-zero, returns number of packets
//     left for the same project work was found for, otherwise it
//     returns the *total* number of packets available for *all*
//     contests for the thread in question.
//
// Note that 'return_single_count' IS ALL IT TAKES TO DISABLE ROTATION.
static long __loadapacket( Client *client,
                           WorkRecord *wrdata /*where to load*/,
                           int /*ign_closed*/,
                           unsigned int prob_i /* for which 'thread' */,
                           int return_single_count /* see above */ )
{
  unsigned int proj_i;
  long bufcount, totalcount = -1;

  for (proj_i = 0; proj_i < PROJECT_COUNT; proj_i++ )
  {
    unsigned int selproject = client->project_order_map[proj_i];
    if (ProjectGetFlags(selproject) == PROJECT_UNSUPPORTED)
      continue;
    if (client->project_state[selproject] & PROJECTSTATE_USER_DISABLED)
      continue;
    if (!IsProblemLoadPermitted( (long)prob_i, selproject ))
    {
      continue; /* problem.cpp - result depends on #defs, threadsafety etc */
    }
    bufcount = -1;
    if (!wrdata) /* already loaded a packet */
      bufcount = GetBufferCount( client, selproject, 0, NULL );
    else         /* haven't got a packet yet */
    {
      bufcount = GetBufferRecord( client, wrdata, selproject, 0 );
      if (bufcount >= 0) /* no error */
        wrdata = 0;     /* don't load again */
    }
    if (bufcount >= 0) /* no error */
    {
      if (totalcount < 0)
        totalcount = 0;
      totalcount += bufcount;
      if (return_single_count)
        break;
    }
  }
  return totalcount;
}
int BC_Example_Bridge(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
{
	int err = -EFAULT;
	int command = _IOC_NR(cmd);
	BC_Example_ioctl_package sBridge;

	if (copy_from_user(&sBridge, (void *)arg, sizeof(sBridge)) != 0)
	{
		return err;
	}

	switch(command)
	{
		case _IOC_NR(BC_Example_ioctl_fill_buffer):
		{
			if(FillBuffer(sBridge.inputparam) == -1)
			{
				return err;
			}
			break;
		}
		case _IOC_NR(BC_Example_ioctl_get_buffer_count):
		{
			if(GetBufferCount(&sBridge.outputparam) == -1)
			{
				return err;
			}
			break;
		}
		default:
			return err;
	}

	if (copy_to_user((void *)arg, &sBridge, sizeof(sBridge)) != 0)
	{
		return err;
	}

	return 0;
}
Beispiel #7
0
HRESULT CDecDXVA2::CreateDXVA2Decoder(int nSurfaces, IDirect3DSurface9 **ppSurfaces)
{
  DbgLog((LOG_TRACE, 10, L"-> CDecDXVA2::CreateDXVA2Decoder"));
  HRESULT hr = S_OK;
  LPDIRECT3DSURFACE9 pSurfaces[DXVA2_MAX_SURFACES];

  if (!m_pDXVADecoderService)
    return E_FAIL;

  DestroyDecoder(false, true);

  GUID input = GUID_NULL;
  D3DFORMAT output;
  FindVideoServiceConversion(m_pAVCtx->codec_id, &input, &output);

  if (!nSurfaces) {
    m_dwSurfaceWidth = FFALIGN(m_pAVCtx->coded_width, 16);
    m_dwSurfaceHeight = FFALIGN(m_pAVCtx->coded_height, 16);

    m_NumSurfaces = GetBufferCount();
    hr = m_pDXVADecoderService->CreateSurface(m_dwSurfaceWidth, m_dwSurfaceHeight, m_NumSurfaces - 1, output, D3DPOOL_DEFAULT, 0, DXVA2_VideoDecoderRenderTarget, pSurfaces, NULL);
    if (FAILED(hr)) {
      DbgLog((LOG_TRACE, 10, L"-> Creation of surfaces failed with hr: %X", hr));
      m_NumSurfaces = 0;
      return E_FAIL;
    }
    ppSurfaces = pSurfaces;
  } else {
    m_NumSurfaces = nSurfaces;
    for (int i = 0; i < m_NumSurfaces; i++) {
      ppSurfaces[i]->AddRef();
    }
  }

  for (int i = 0; i < m_NumSurfaces; i++) {
    m_pSurfaces[i].index = i;
    m_pSurfaces[i].d3d = ppSurfaces[i];
    m_pSurfaces[i].age = 0;
    m_pSurfaces[i].used = false;
  }

  DbgLog((LOG_TRACE, 10, L"-> Successfully created %d surfaces (%dx%d)", m_NumSurfaces, m_dwSurfaceWidth, m_dwSurfaceHeight));

  DXVA2_VideoDesc desc;
  ZeroMemory(&desc, sizeof(desc));
  desc.SampleWidth = m_pAVCtx->coded_width;
  desc.SampleHeight = m_pAVCtx->coded_height;
  desc.Format = output;

  hr = FindDecoderConfiguration(input, &desc, &m_DXVAVideoDecoderConfig);
  if (FAILED(hr)) {
    DbgLog((LOG_TRACE, 10, L"-> FindDecoderConfiguration failed with hr: %X", hr));
    return hr;
  }

  IDirectXVideoDecoder *decoder = NULL;
  hr = m_pDXVADecoderService->CreateVideoDecoder(input, &desc, &m_DXVAVideoDecoderConfig, ppSurfaces, m_NumSurfaces, &decoder);
  if (FAILED(hr)) {
    DbgLog((LOG_TRACE, 10, L"-> CreateVideoDecoder failed with hr: %X", hr));
    return E_FAIL;
  }
  m_pDecoder = decoder;

  /* fill hwaccel_context */
  dxva_context *ctx = (dxva_context *)m_pAVCtx->hwaccel_context;
  ctx->cfg           = &m_DXVAVideoDecoderConfig;
  ctx->decoder       = m_pDecoder;
  ctx->surface       = m_pRawSurface;
  ctx->surface_count = m_NumSurfaces;

  if (m_dwVendorId == VEND_ID_INTEL && input == DXVADDI_Intel_ModeH264_E)
    ctx->workaround = FF_DXVA2_WORKAROUND_INTEL_CLEARVIDEO;
  else if (m_dwVendorId == VEND_ID_ATI && IsAMDUVD(m_dwDeviceId))
    ctx->workaround = FF_DXVA2_WORKAROUND_SCALING_LIST_ZIGZAG;
  else
    ctx->workaround = 0;

  memset(m_pRawSurface, 0, sizeof(m_pRawSurface));
  for (int i = 0; i < m_NumSurfaces; i++) {
    m_pRawSurface[i] = m_pSurfaces[i].d3d;
  }

  return S_OK;
}
Beispiel #8
0
CConfig CUser::ToConfig() {
	CConfig config;
	CConfig passConfig;

	CString sHash;
	switch (m_eHashType) {
	case HASH_NONE:
		sHash = "Plain";
		break;
	case HASH_MD5:
		sHash = "MD5";
		break;
	case HASH_SHA256:
		sHash = "SHA256";
		break;
	}
	passConfig.AddKeyValuePair("Salt", m_sPassSalt);
	passConfig.AddKeyValuePair("Method", sHash);
	passConfig.AddKeyValuePair("Hash", GetPass());
	config.AddSubConfig("Pass", "password", passConfig);

	config.AddKeyValuePair("Nick", GetNick());
	config.AddKeyValuePair("AltNick", GetAltNick());
	config.AddKeyValuePair("Ident", GetIdent());
	config.AddKeyValuePair("RealName", GetRealName());
	config.AddKeyValuePair("BindHost", GetBindHost());
	config.AddKeyValuePair("DCCBindHost", GetDCCBindHost());
	config.AddKeyValuePair("QuitMsg", GetQuitMsg());
	if (CZNC::Get().GetStatusPrefix() != GetStatusPrefix())
		config.AddKeyValuePair("StatusPrefix", GetStatusPrefix());
	config.AddKeyValuePair("Skin", GetSkinName());
	config.AddKeyValuePair("Language", GetLanguage());
	config.AddKeyValuePair("ChanModes", GetDefaultChanModes());
	config.AddKeyValuePair("Buffer", CString(GetBufferCount()));
	config.AddKeyValuePair("KeepBuffer", CString(KeepBuffer()));
	config.AddKeyValuePair("MultiClients", CString(MultiClients()));
	config.AddKeyValuePair("DenyLoadMod", CString(DenyLoadMod()));
	config.AddKeyValuePair("Admin", CString(IsAdmin()));
	config.AddKeyValuePair("DenySetBindHost", CString(DenySetBindHost()));
	config.AddKeyValuePair("TimestampFormat", GetTimestampFormat());
	config.AddKeyValuePair("AppendTimestamp", CString(GetTimestampAppend()));
	config.AddKeyValuePair("PrependTimestamp", CString(GetTimestampPrepend()));
	config.AddKeyValuePair("TimezoneOffset", CString(m_fTimezoneOffset));
	config.AddKeyValuePair("JoinTries", CString(m_uMaxJoinTries));
	config.AddKeyValuePair("MaxJoins", CString(m_uMaxJoins));
	config.AddKeyValuePair("IRCConnectEnabled", CString(GetIRCConnectEnabled()));

	// Allow Hosts
	if (!m_ssAllowedHosts.empty()) {
		for (set<CString>::iterator it = m_ssAllowedHosts.begin(); it != m_ssAllowedHosts.end(); ++it) {
			config.AddKeyValuePair("Allow", *it);
		}
	}

	// CTCP Replies
	if (!m_mssCTCPReplies.empty()) {
		for (MCString::const_iterator itb = m_mssCTCPReplies.begin(); itb != m_mssCTCPReplies.end(); ++itb) {
			config.AddKeyValuePair("CTCPReply", itb->first.AsUpper() + " " + itb->second);
		}
	}

	// Modules
	CModules& Mods = GetModules();

	if (!Mods.empty()) {
		for (unsigned int a = 0; a < Mods.size(); a++) {
			CString sArgs = Mods[a]->GetArgs();

			if (!sArgs.empty()) {
				sArgs = " " + sArgs;
			}

			config.AddKeyValuePair("LoadModule", Mods[a]->GetModName() + sArgs);
		}
	}

	// Networks
	for (unsigned int d = 0; d < m_vIRCNetworks.size(); d++) {
		CIRCNetwork *pNetwork = m_vIRCNetworks[d];
		config.AddSubConfig("Network", pNetwork->GetName(), pNetwork->ToConfig());
	}

	return config;
}
Beispiel #9
0
bool CUser::WriteConfig(CFile& File) {
	File.Write("<User " + GetUserName().FirstLine() + ">\n");

	if (m_eHashType != HASH_NONE) {
		CString sHash = "md5";
		if (m_eHashType == HASH_SHA256)
			sHash = "sha256";
		if (m_sPassSalt.empty()) {
			PrintLine(File, "Pass", sHash + "#" + GetPass());
		} else {
			PrintLine(File, "Pass", sHash + "#" + GetPass() + "#" + m_sPassSalt + "#");
		}
	} else {
		PrintLine(File, "Pass", "plain#" + GetPass());
	}
	PrintLine(File, "Nick", GetNick());
	PrintLine(File, "AltNick", GetAltNick());
	PrintLine(File, "Ident", GetIdent());
	PrintLine(File, "RealName", GetRealName());
	PrintLine(File, "BindHost", GetBindHost());
	PrintLine(File, "DCCBindHost", GetDCCBindHost());
	PrintLine(File, "QuitMsg", GetQuitMsg());
	if (CZNC::Get().GetStatusPrefix() != GetStatusPrefix())
		PrintLine(File, "StatusPrefix", GetStatusPrefix());
	PrintLine(File, "Skin", GetSkinName());
	PrintLine(File, "ChanModes", GetDefaultChanModes());
	PrintLine(File, "Buffer", CString(GetBufferCount()));
	PrintLine(File, "KeepBuffer", CString(KeepBuffer()));
	PrintLine(File, "MultiClients", CString(MultiClients()));
	PrintLine(File, "BounceDCCs", CString(BounceDCCs()));
	PrintLine(File, "DenyLoadMod", CString(DenyLoadMod()));
	PrintLine(File, "Admin", CString(IsAdmin()));
	PrintLine(File, "DenySetBindHost", CString(DenySetBindHost()));
	PrintLine(File, "DCCLookupMethod", CString((UseClientIP()) ? "client" : "default"));
	PrintLine(File, "TimestampFormat", GetTimestampFormat());
	PrintLine(File, "AppendTimestamp", CString(GetTimestampAppend()));
	PrintLine(File, "PrependTimestamp", CString(GetTimestampPrepend()));
	PrintLine(File, "TimezoneOffset", CString(m_fTimezoneOffset));
	PrintLine(File, "JoinTries", CString(m_uMaxJoinTries));
	PrintLine(File, "MaxJoins", CString(m_uMaxJoins));
	PrintLine(File, "IRCConnectEnabled", CString(GetIRCConnectEnabled()));
	File.Write("\n");

	// Allow Hosts
	if (!m_ssAllowedHosts.empty()) {
		for (set<CString>::iterator it = m_ssAllowedHosts.begin(); it != m_ssAllowedHosts.end(); ++it) {
			PrintLine(File, "Allow", *it);
		}

		File.Write("\n");
	}

	// CTCP Replies
	if (!m_mssCTCPReplies.empty()) {
		for (MCString::const_iterator itb = m_mssCTCPReplies.begin(); itb != m_mssCTCPReplies.end(); ++itb) {
			PrintLine(File, "CTCPReply", itb->first.AsUpper() + " " + itb->second);
		}

		File.Write("\n");
	}

	// Modules
	CModules& Mods = GetModules();

	if (!Mods.empty()) {
		for (unsigned int a = 0; a < Mods.size(); a++) {
			CString sArgs = Mods[a]->GetArgs();

			if (!sArgs.empty()) {
				sArgs = " " + sArgs;
			}

			PrintLine(File, "LoadModule", Mods[a]->GetModName() + sArgs);
		}

		File.Write("\n");
	}

	// Servers
	for (unsigned int b = 0; b < m_vServers.size(); b++) {
		PrintLine(File, "Server", m_vServers[b]->GetString());
	}

	// Chans
	for (unsigned int c = 0; c < m_vChans.size(); c++) {
		CChan* pChan = m_vChans[c];
		if (pChan->InConfig()) {
			File.Write("\n");
			if (!pChan->WriteConfig(File)) {
				return false;
			}
		}
	}

	File.Write("</User>\n");

	return true;
}
size_t SourceFileMediaFoundation::processNextReadSample()
{
	::IMFSample *mediaSample;
	DWORD streamFlags = 0;
	LONGLONG timeStamp;
	HRESULT hr = mSourceReader->ReadSample( MF_SOURCE_READER_FIRST_AUDIO_STREAM, 0, NULL, &streamFlags, &timeStamp, &mediaSample );
	CI_ASSERT( hr == S_OK );

	if( streamFlags & MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED ) {
		CI_LOG_W( "type change unhandled" );
		return 0;
	}
	if( streamFlags & MF_SOURCE_READERF_ENDOFSTREAM ) {
		// end of file
		return 0;
	}
	if( ! mediaSample ) {
		// out of samples
		mediaSample->Release();
		return 0;
	}

	auto samplePtr = ci::msw::makeComUnique( mediaSample );

	DWORD bufferCount;
	hr = samplePtr->GetBufferCount( &bufferCount );
	CI_ASSERT( hr == S_OK );

	CI_ASSERT( bufferCount == 1 ); // just looking out for a file type with more than one buffer.. haven't seen one yet.

	// get the buffer
	::IMFMediaBuffer *mediaBuffer;
	BYTE *audioData = NULL;
	DWORD audioDataLength;

	hr = samplePtr->ConvertToContiguousBuffer( &mediaBuffer );
	hr = mediaBuffer->Lock( &audioData, NULL, &audioDataLength );

	size_t numChannels = mNumChannels;
	size_t numFramesRead = audioDataLength / ( mBytesPerSample * numChannels );

	mReadBuffer.setNumFrames( numFramesRead );

	if( mSampleType == SampleType::FLOAT_32 ) {
		float *sourceFloatSamples = (float *)audioData;
		if( numChannels == 1 )
			memcpy( mReadBuffer.getData(), sourceFloatSamples, numFramesRead * sizeof( float ) );
		else
			dsp::deinterleave( sourceFloatSamples, mReadBuffer.getData(), mReadBuffer.getNumFrames(), numChannels, numFramesRead );
	}
	else if( mSampleType == SampleType::INT_16 ) {
		int16_t *sourceInt16Samples = (int16_t *)audioData;
		dsp::deinterleave( sourceInt16Samples, mReadBuffer.getData(), mReadBuffer.getNumFrames(), numChannels, numFramesRead );
	}
	else if( mSampleType == SampleType::INT_24 ) {
		const char *sourceInt24Samples = (const char *)audioData;
		if( numChannels == 1 )
			dsp::convertInt24ToFloat( sourceInt24Samples, mReadBuffer.getData(), numFramesRead );
		else {
			if( mBitConverterBuffer.getNumFrames() != numFramesRead )
				mBitConverterBuffer.setNumFrames( numFramesRead );

			dsp::convertInt24ToFloat( sourceInt24Samples, mBitConverterBuffer.getData(), numFramesRead * numChannels );
			dsp::deinterleave( mBitConverterBuffer.getData(), mReadBuffer.getData(), mReadBuffer.getNumFrames(), numChannels, numFramesRead );
		}
	}
	else
		CI_ASSERT_NOT_REACHABLE();

	hr = mediaBuffer->Unlock();
	CI_ASSERT( hr == S_OK );

	mediaBuffer->Release();
	return numFramesRead;
}
Beispiel #11
0
NS_IMETHODIMP
WebGLMemoryTracker::CollectReports(nsIHandleReportCallback* handleReport,
                                   nsISupports* data, bool)
{
#define REPORT(_path, _kind, _units, _amount, _desc)                         \
    do {                                                                     \
      nsresult rv;                                                           \
      rv = handleReport->Callback(EmptyCString(), NS_LITERAL_CSTRING(_path), \
                                   _kind, _units, _amount,                   \
                                   NS_LITERAL_CSTRING(_desc), data);         \
      NS_ENSURE_SUCCESS(rv, rv);                                             \
    } while (0)

    REPORT("webgl-texture-memory",
           KIND_OTHER, UNITS_BYTES, GetTextureMemoryUsed(),
           "Memory used by WebGL textures.The OpenGL"
           " implementation is free to store these textures in either video"
           " memory or main memory. This measurement is only a lower bound,"
           " actual memory usage may be higher for example if the storage"
           " is strided.");

    REPORT("webgl-texture-count",
           KIND_OTHER, UNITS_COUNT, GetTextureCount(),
           "Number of WebGL textures.");

    REPORT("webgl-buffer-memory",
           KIND_OTHER, UNITS_BYTES, GetBufferMemoryUsed(),
           "Memory used by WebGL buffers. The OpenGL"
           " implementation is free to store these buffers in either video"
           " memory or main memory. This measurement is only a lower bound,"
           " actual memory usage may be higher for example if the storage"
           " is strided.");

    REPORT("explicit/webgl/buffer-cache-memory",
           KIND_HEAP, UNITS_BYTES, GetBufferCacheMemoryUsed(),
           "Memory used by WebGL buffer caches. The WebGL"
           " implementation caches the contents of element array buffers"
           " only.This adds up with the webgl-buffer-memory value, but"
           " contrary to it, this one represents bytes on the heap,"
           " not managed by OpenGL.");

    REPORT("webgl-buffer-count",
           KIND_OTHER, UNITS_COUNT, GetBufferCount(),
           "Number of WebGL buffers.");

    REPORT("webgl-renderbuffer-memory",
           KIND_OTHER, UNITS_BYTES, GetRenderbufferMemoryUsed(),
           "Memory used by WebGL renderbuffers. The OpenGL"
           " implementation is free to store these renderbuffers in either"
           " video memory or main memory. This measurement is only a lower"
           " bound, actual memory usage may be higher for example if the"
           " storage is strided.");

    REPORT("webgl-renderbuffer-count",
           KIND_OTHER, UNITS_COUNT, GetRenderbufferCount(),
           "Number of WebGL renderbuffers.");

    REPORT("explicit/webgl/shader",
           KIND_HEAP, UNITS_BYTES, GetShaderSize(),
           "Combined size of WebGL shader ASCII sources and translation"
           " logs cached on the heap.");

    REPORT("webgl-shader-count",
           KIND_OTHER, UNITS_COUNT, GetShaderCount(),
           "Number of WebGL shaders.");

    REPORT("webgl-context-count",
           KIND_OTHER, UNITS_COUNT, GetContextCount(),
           "Number of WebGL contexts.");

#undef REPORT

    return NS_OK;
}
Beispiel #12
0
HRESULT CDecDXVA2::CreateDXVA2Decoder(int nSurfaces, IDirect3DSurface9 **ppSurfaces)
{
  DbgLog((LOG_TRACE, 10, L"-> CDecDXVA2::CreateDXVA2Decoder"));
  HRESULT hr = S_OK;
  LPDIRECT3DSURFACE9 pSurfaces[DXVA2_MAX_SURFACES];

  if (!m_pDXVADecoderService)
    return E_FAIL;

  DestroyDecoder(false, true);

  GUID input = GUID_NULL;
  D3DFORMAT output;
  FindVideoServiceConversion(m_pAVCtx->codec_id, &input, &output);

  if (!nSurfaces) {
    m_dwSurfaceWidth = GetAlignedDimension(m_pAVCtx->coded_width);
    m_dwSurfaceHeight = GetAlignedDimension(m_pAVCtx->coded_height);

    m_NumSurfaces = GetBufferCount();
    hr = m_pDXVADecoderService->CreateSurface(m_dwSurfaceWidth, m_dwSurfaceHeight, m_NumSurfaces - 1, output, D3DPOOL_DEFAULT, 0, DXVA2_VideoDecoderRenderTarget, pSurfaces, nullptr);
    if (FAILED(hr)) {
      DbgLog((LOG_TRACE, 10, L"-> Creation of surfaces failed with hr: %X", hr));
      m_NumSurfaces = 0;
      return E_FAIL;
    }
    ppSurfaces = pSurfaces;
  } else {
    m_NumSurfaces = nSurfaces;
    for (int i = 0; i < m_NumSurfaces; i++) {
      ppSurfaces[i]->AddRef();
    }
  }

  if (m_NumSurfaces <= 0) {
    DbgLog((LOG_TRACE, 10, L"-> No surfaces? No good!"));
    return E_FAIL;
  }

  // get the device, for ColorFill() to init the surfaces in black
  IDirect3DDevice9 *pDev = nullptr;
  ppSurfaces[0]->GetDevice(&pDev);

  for (int i = 0; i < m_NumSurfaces; i++) {
    m_pSurfaces[i].index = i;
    m_pSurfaces[i].d3d = ppSurfaces[i];
    m_pSurfaces[i].age = 0;
    m_pSurfaces[i].used = false;

    // fill the surface in black, to avoid the "green screen" in case the first frame fails to decode.
    if (pDev) pDev->ColorFill(ppSurfaces[i], NULL, D3DCOLOR_XYUV(0, 128, 128));
  }

  // and done with the device
  SafeRelease(&pDev);

  DbgLog((LOG_TRACE, 10, L"-> Successfully created %d surfaces (%dx%d)", m_NumSurfaces, m_dwSurfaceWidth, m_dwSurfaceHeight));

  DXVA2_VideoDesc desc;
  ZeroMemory(&desc, sizeof(desc));
  desc.SampleWidth = m_pAVCtx->coded_width;
  desc.SampleHeight = m_pAVCtx->coded_height;
  desc.Format = output;

  hr = FindDecoderConfiguration(input, &desc, &m_DXVAVideoDecoderConfig);
  if (FAILED(hr)) {
    DbgLog((LOG_TRACE, 10, L"-> FindDecoderConfiguration failed with hr: %X", hr));
    return hr;
  }

  IDirectXVideoDecoder *decoder = nullptr;
  hr = m_pDXVADecoderService->CreateVideoDecoder(input, &desc, &m_DXVAVideoDecoderConfig, ppSurfaces, m_NumSurfaces, &decoder);
  if (FAILED(hr)) {
    DbgLog((LOG_TRACE, 10, L"-> CreateVideoDecoder failed with hr: %X", hr));
    return E_FAIL;
  }
  m_pDecoder = decoder;
  m_guidDecoderDevice = input;

  /* fill hwaccel_context */
  FillHWContext((dxva_context *)m_pAVCtx->hwaccel_context);

  memset(m_pRawSurface, 0, sizeof(m_pRawSurface));
  for (int i = 0; i < m_NumSurfaces; i++) {
    m_pRawSurface[i] = m_pSurfaces[i].d3d;
  }

  return S_OK;
}
Beispiel #13
0
unsigned int LoadSaveProblems(Client *client,
                              unsigned int load_problem_count,int mode)
{
  /* Some platforms need to stop asynchronously, for example, Win16 which
     gets an ENDSESSION message and has to exit then and there. So also
     win9x when running as a service where windows suspends all threads
     except the window thread. For these (and perhaps other platforms)
     we save our last state so calling with (0,0,0) will save the
     problem states (without hanging). see 'abortive_action' below.
  */
  static Client *previous_client = 0;
  static unsigned int previous_load_problem_count = 0, reentrant_count = 0;
  static int abortive_action = 0;

  unsigned int retval = 0;
  int changed_flag, first_time;

  int allclosed, prob_step,bufupd_pending;
  unsigned int cont_i, prob_for, prob_first, prob_last;
  unsigned int loaded_problems_count[CONTEST_COUNT];
  unsigned int saved_problems_count[CONTEST_COUNT];
  unsigned long totalBlocksDone; /* all contests */

  unsigned int total_problems_loaded, total_problems_saved;
  unsigned int norandom_count, getbuff_errs, empty_problems;

  allclosed = 0;
  norandom_count = getbuff_errs = empty_problems = 0;
  changed_flag = (previous_load_problem_count == 0);
  total_problems_loaded = 0;
  total_problems_saved = 0;
  bufupd_pending = 0;
  totalBlocksDone = 0;

  /* ============================================================= */

  if (abortive_action) /* already aborted once */
  {                    /* no probfill action can happen again */
    return 0;
  }
  if (!client)             /* abnormal end */
  {
    client = previous_client;
    if (!client)
      return 0;
    abortive_action = 1;
    mode = PROBFILL_UNLOADALL;
  }
  previous_client = client;
  if ((++reentrant_count) > 1)
  {
    --reentrant_count;
    return 0;
  }

  /* ============================================================= */

  prob_first = 0;
  prob_step  = 0;
  prob_last  = 0;
  first_time = 0;

  if (load_problem_count == 0) /* only permitted if unloading all */
  {
    if (mode != PROBFILL_UNLOADALL || previous_load_problem_count == 0)
    {
      --reentrant_count;
      return 0;
    }
    load_problem_count = previous_load_problem_count;
  }
  if (previous_load_problem_count == 0) /* must be initial load */
  {            /* [0 ... (load_problem_count - 1)] */
    prob_first = 0;
    prob_last  = (load_problem_count - 1);
    prob_step  = 1;
    first_time = 1;
  }
  else if (mode == PROBFILL_RESIZETABLE)
  {            /* [(previousload_problem_count-1) ... load_problem_count] */
    prob_first = load_problem_count;
    prob_last  = (previous_load_problem_count - 1);
    prob_step  = -1;
  }
  else /* PROBFILL_UNLOADALL, PROBFILL_REFRESH */
  {            /* [(load_problem_count - 1) ... 0] */
    prob_first = 0;
    prob_last  = (load_problem_count - 1);
    prob_step  = -1;
  }

  TRACE_BUFFUPD((+1, "LoadSaveProblems(%d)\n", mode));

  /* ============================================================= */

  for (cont_i = 0; cont_i < CONTEST_COUNT; cont_i++)
  {
    unsigned int blocksdone;
    if (CliGetContestInfoSummaryData( cont_i, &blocksdone, NULL, NULL, NULL, NULL )==0)
      totalBlocksDone += blocksdone;
    loaded_problems_count[cont_i] = 0;
    saved_problems_count[cont_i] = 0;
  }

  /* ============================================================= */

  ClientEventSyncPost(CLIEVENT_PROBLEM_TFILLSTARTED, &load_problem_count,
                                                sizeof(load_problem_count));

  for (prob_for = 0; prob_for <= (prob_last - prob_first); prob_for++)
  {
    Problem *thisprob;
    int load_needed;
    unsigned int prob_i = prob_for + prob_first;
    if ( prob_step < 0 )
      prob_i = prob_last - prob_for;

    thisprob = GetProblemPointerFromIndex( prob_i );
    if (thisprob == 0)
    {
      if (prob_step < 0)
        continue;
      break;
    }

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

    load_needed = 0;
    if (__IndividualProblemSave( thisprob, prob_i, client,
        &load_needed, load_problem_count, &cont_i, &bufupd_pending,
        (mode == PROBFILL_UNLOADALL || mode == PROBFILL_RESIZETABLE ),
        abortive_action ))
    {
      changed_flag = 1;
      total_problems_saved++;
      saved_problems_count[cont_i]++;
      totalBlocksDone++;
    }
    if (load_needed)
      empty_problems++;

    TRACE_BUFFUPD((0, "__IndividualProblemSave ==> bufupd_pending = %d\n", bufupd_pending));

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

    if (load_needed && mode!=PROBFILL_UNLOADALL && mode!=PROBFILL_RESIZETABLE)
    {
      // Bug #3672 (all clients running at least 2 cores).
      // Take the number of still active crunchers into account to determine
      // whether we can load another problem.

      // Bug #4018: It will not work for initial load: this 'if' will load
      // packet to LAST cruncher while main loop will start FIRST cruncher.
      // So here is a second 'if' for inital load (when mode==0), it will
      // load cruncher from start up to block count. (I wonder can old 'if'
      // be completely replaced with new one.)

      if (client->blockcount > 0)
      {
          if (mode == 0)
          {
              /* Load from beginning to up max. count, skip last crunchers */
              if (totalBlocksDone+total_problems_loaded >= (unsigned long)client->blockcount)
                  load_needed = 0;
          }
          else
          {
              /* Skip first crunchers, load from middle to last */
              if (totalBlocksDone+load_problem_count-empty_problems>=((unsigned long)(client->blockcount)))
                  load_needed = 0;
          }
      }
      if (load_needed)
      {
        load_needed = 0;
        if (__IndividualProblemLoad( thisprob, prob_i, client,
            &load_needed, load_problem_count, &cont_i, &bufupd_pending ))
        {
          empty_problems--;
          total_problems_loaded++;
          loaded_problems_count[cont_i]++;
          changed_flag = 1;
        }
        TRACE_BUFFUPD((0, "__IndividualProblemLoad ==> bufupd_pending = %d\n", bufupd_pending));
        if (load_needed)
        {
          getbuff_errs++;
          if (load_needed == NOLOAD_ALLCONTESTSCLOSED)
          {
            allclosed = 1;
            break; /* the for ... prob_i ... loop */
          }
          else if (load_needed == NOLOAD_NORANDOM)
            norandom_count++;
        }
      }
    } //if (load_needed)
  } //for (prob_i = 0; prob_i < load_problem_count; prob_i++ )

  ClientEventSyncPost(CLIEVENT_PROBLEM_TFILLFINISHED,
     ((previous_load_problem_count==0)?(&total_problems_loaded):(&total_problems_saved)),
     sizeof(total_problems_loaded));

  /* ============================================================= */

  if (mode == PROBFILL_UNLOADALL)
  {
    previous_load_problem_count = 0;
    if (client->nodiskbuffers == 0)
    {
      // close checkpoint file immediately after saving the problems to disk
      CheckpointAction( client, CHECKPOINT_CLOSE, 0 );
    }
    else if (!CheckRestartRequestTrigger()) /* no disk buffers */
    {
      TRACE_BUFFUPD((0, "BufferUpdate: reason = LoadSaveProblem && unload all && membuffers\n"));
      BufferUpdate(client,BUFFERUPDATE_FLUSH,0);
      /* in case the flush fails, empty the membuf table manually */
      for (cont_i = 0; cont_i < CONTEST_COUNT; cont_i++)
      {
        WorkRecord data;
        while (GetBufferCount(client, cont_i, 0, 0)>0)
          GetBufferRecord( client, &data, cont_i, 0 );
        while (GetBufferCount(client, cont_i, 0, 0)>0)
          GetBufferRecord( client, &data, cont_i, 1);
      }
    }
    retval = total_problems_saved;
  }
  else /* if (mode != PROBFILL_UNLOADALL) */
  {
    /*
    =============================================================
    // save the number of active problems, so that we can bail out
    // in an "emergency". Some platforms call us asynchronously when they
    // need to abort [win16/win32 for example]
    -------------------------------------------------------------
    */

    previous_load_problem_count = load_problem_count;

    if (bufupd_pending && client->blockcount >= 0)
    {
      int req = MODEREQ_FLUSH; // always flush while fetching
      if (!CheckExitRequestTriggerNoIO()) //((bufupd_pending & BUFFERUPDATE_FETCH)!=0)
        req |= MODEREQ_FETCH;
      TRACE_BUFFUPD((0, "ModeReqSet(flush=%d, fetch=%d, fquiet=1)\n",
                        (req & MODEREQ_FLUSH) != 0, (req & MODEREQ_FETCH) != 0));
      ModeReqSet( req|MODEREQ_FQUIET ); /* delegate to the client.run loop */
    }

    if (!allclosed && mode != PROBFILL_RESIZETABLE)
    {
      /*
       =============================================================
       if we are running a limited number of blocks then check if we have
       exceeded that number. If we have, but one or more crunchers are
       still at work, bump the limit.
       -------------------------------------------------------------
      */
      if (client->blockcount < 0 || (client->blockcount > 0
                  && totalBlocksDone >= (unsigned long)(client->blockcount)))
      {
        if (empty_problems >= load_problem_count)
        {
          Log( "Shutdown - packet limit exceeded.\n" );
          RaiseExitRequestTrigger();
        }
        // Bug #3672 (all clients running at least 2 cores).
        // The following two lines prevent the client from stopping as
        // instructed by option "-n" when running at least two crunchers
        // simultaneously.
        //else
        //  client->blockcount = ((u32)(totalBlocksDone))+1;
      }
    }

    if (mode == PROBFILL_RESIZETABLE)
      retval = total_problems_saved;
    else if (mode == PROBFILL_GETBUFFERRS)
      retval = getbuff_errs;
    else if (mode == PROBFILL_ANYCHANGED)
      retval = changed_flag;
    else
      retval = total_problems_loaded;
  }

  /* ============================================================= */

  for ( cont_i = 0; cont_i < CONTEST_COUNT; cont_i++) //once for each contest
  {
    int show_totals = 0;
    if (loaded_problems_count[cont_i] || saved_problems_count[cont_i])
      show_totals = 1;

    if (first_time || show_totals)
    {
      unsigned int inout;
      const char *cont_name = CliGetContestNameFromID(cont_i);

      if (loaded_problems_count[cont_i] && load_problem_count > COMBINEMSG_THRESHOLD )
      {
        Log( "%s: Loaded %u packet%s from %s\n",
              cont_name, loaded_problems_count[cont_i],
              ((loaded_problems_count[cont_i]==1)?(""):("s")),
              (client->nodiskbuffers ? "(memory-in)" :
              BufferGetDefaultFilename( cont_i, 0,
                                        client->in_buffer_basename )) );
      }

      if (saved_problems_count[cont_i] && load_problem_count > COMBINEMSG_THRESHOLD
       && (client->nodiskbuffers == 0 || (mode != PROBFILL_UNLOADALL)))
      {
        Log( "%s: Saved %u packet%s to %s\n",
              cont_name, saved_problems_count[cont_i],
              ((saved_problems_count[cont_i]==1)?(""):("s")),
              (mode == PROBFILL_UNLOADALL)?
                (client->nodiskbuffers ? "(memory-in)" :
                BufferGetDefaultFilename( cont_i, 0,
                                          client->in_buffer_basename ) ) :
                (client->nodiskbuffers ? "(memory-out)" :
                BufferGetDefaultFilename( cont_i, 1,
                                          client->out_buffer_basename )) );
      }

      if (show_totals && totalBlocksDone > 0)
      {
        // To suppress "odd" problem completion count summaries (and not be
        // quite so verbose) we only display summaries if the number of
        // completed problems is even divisible by the number of processors.
        // Requires a working GetNumberOfDetectedProcessors() [cpucheck.cpp]
        #if 0
        int cpustmp; unsigned int cpus = 1;
        if ((cpustmp = GetNumberOfDetectedProcessors()) > 1)
          cpus = (unsigned int)cpustmp;
        if (load_problem_count > cpus)
          cpus = load_problem_count;
        if ((totalBlocksDone%cpus) == 0 )
        #endif
        {
          __post_summary_for_contest(cont_i);
        }
      }

      /* -------------------------------------------------------------- */

      for (inout=0;inout<=1;inout++)
      {
        unsigned long stats_count;
        long block_count = GetBufferCount( client, cont_i, inout, &stats_count );

        if (show_totals && block_count >= 0) /* no error */
        {
          char buffer[(3*80)+sizeof(client->in_buffer_basename)];
          int len;

          len = sprintf(buffer, "%s: %ld packet%s ",
                cont_name, block_count, ((block_count == 1)?(""):("s")) );
          if (stats_count)
            len += sprintf( &buffer[len], "(%lu.%02lu stats units) ",
                            stats_count/100,stats_count%100);
          len += sprintf( &buffer[len], "%s in\n%s",
              ((inout!= 0 || mode == PROBFILL_UNLOADALL)?
                 ((block_count==1)?("is"):("are")):
                 ((block_count==1)?("remains"):("remain"))),
              ((inout== 0)?
                  (client->nodiskbuffers ? "(memory-in)" :
                   BufferGetDefaultFilename( cont_i, 0,
                   client->in_buffer_basename ) ) :
                   (client->nodiskbuffers ? "(memory-out)":
                   BufferGetDefaultFilename( cont_i, 1,
                   client->out_buffer_basename ) ))
             );
          if (len < 55) /* fits on a single line, so unwrap */
          {
            char *nl = strrchr( buffer, '\n' );
            if (nl) *nl = ' ';
          }
          if (inout != 0) /* out-buffer */
          {
            /* adjust bufupd_pending if outthresh has been crossed */
            /* we don't check in-buffer here since we need cumulative count */
            if (__check_outbufthresh_limit( client, cont_i, block_count,
                                            stats_count, &bufupd_pending ))
            {
              //Log("5. bufupd_pending |= BUFFERUPDATE_FLUSH;\n");
            }
          }
          else /*in*/ if (stats_count && (mode!=PROBFILL_UNLOADALL))
          {
            timeval tv;
            tv.tv_sec = __get_thresh_secs(client, cont_i, 0, stats_count, 0 );
            if (tv.tv_sec > 0)
            {
              tv.tv_usec = 0;
              len += sprintf(&buffer[len],
                       "\nProjected ideal time to completion: %s",
                       CliGetTimeString( &tv, 2));
            }
          }
          Log( "%s\n", buffer );
        } //if (block_count >= 0)

      } //  for (inout=0;inout<=1;inout++)
    } //if (loaded_problems_count[cont_i] || saved_problems_count[cont_i])
  } //for ( cont_i = 0; cont_i < CONTEST_COUNT; cont_i++)

  /* ============================================================ */

  if (mode == PROBFILL_UNLOADALL)
  {
    previous_load_problem_count = 0;
    previous_client = (Client *)0;
    if (!CheckRestartRequestTrigger())
      Log("Shutdown complete.\n");
  }
  --reentrant_count;

  TRACE_BUFFUPD((-1, "LoadSaveProblems => %d\n", retval));

  return retval;
}
Beispiel #14
0
STDMETHODIMP CDecD3D11::CreateD3D11Decoder()
{
  HRESULT hr = S_OK;
  AVD3D11VADeviceContext *pDeviceContext = (AVD3D11VADeviceContext *)((AVHWDeviceContext *)m_pDevCtx->data)->hwctx;

  // release the old decoder, it needs to be re-created
  SafeRelease(&m_pDecoder);

  // find a decoder configuration
  GUID profileGUID = GUID_NULL;
  DXGI_FORMAT surface_format = d3d11va_map_sw_to_hw_format(m_pAVCtx->sw_pix_fmt);
  hr = FindVideoServiceConversion(m_pAVCtx->codec_id, m_pAVCtx->profile, surface_format, &profileGUID);
  if (FAILED(hr))
  {
    DbgLog((LOG_ERROR, 10, L"-> No video service profile found"));
    return hr;
  }

  // get decoder configuration
  D3D11_VIDEO_DECODER_DESC desc = { 0 };
  desc.Guid = profileGUID;
  desc.OutputFormat = surface_format;
  desc.SampleWidth = m_pAVCtx->coded_width;
  desc.SampleHeight = m_pAVCtx->coded_height;

  D3D11_VIDEO_DECODER_CONFIG decoder_config = { 0 };
  hr = FindDecoderConfiguration(&desc, &decoder_config);
  if (FAILED(hr))
  {
    DbgLog((LOG_ERROR, 10, L"-> No valid video decoder configuration found"));
    return hr;
  }

  m_DecoderConfig = decoder_config;

  // update surface properties
  m_dwSurfaceWidth = dxva_align_dimensions(m_pAVCtx->codec_id, m_pAVCtx->coded_width);
  m_dwSurfaceHeight = dxva_align_dimensions(m_pAVCtx->codec_id, m_pAVCtx->coded_height);
  m_DecodePixelFormat = m_pAVCtx->sw_pix_fmt;
  m_SurfaceFormat = surface_format;

  if (m_bReadBackFallback == false && m_pAllocator)
  {
    ALLOCATOR_PROPERTIES properties;
    hr = m_pAllocator->GetProperties(&properties);
    if (FAILED(hr))
      return hr;

    m_dwSurfaceCount = properties.cBuffers;
  }
  else
  {
    m_dwSurfaceCount = GetBufferCount();
  }

  // allocate a new frames context for the dimensions and format
  hr = AllocateFramesContext(m_dwSurfaceWidth, m_dwSurfaceHeight, m_DecodePixelFormat, m_dwSurfaceCount, &m_pFramesCtx);
  if (FAILED(hr))
  {
    DbgLog((LOG_ERROR, 10, L"-> Error allocating frames context"));
    return hr;
  }

  // release any old output views and allocate memory for the new ones
  if (m_pOutputViews)
  {
    for (int i = 0; i < m_nOutputViews; i++)
    {
      SafeRelease(&m_pOutputViews[i]);
    }
    av_freep(&m_pOutputViews);
  }

  m_pOutputViews = (ID3D11VideoDecoderOutputView **)av_mallocz_array(m_dwSurfaceCount, sizeof(*m_pOutputViews));
  m_nOutputViews = m_dwSurfaceCount;

  // allocate output views for the frames
  AVD3D11VAFramesContext *pFramesContext = (AVD3D11VAFramesContext *)((AVHWFramesContext *)m_pFramesCtx->data)->hwctx;
  for (int i = 0; i < m_nOutputViews; i++)
  {
    D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC viewDesc = { 0 };
    viewDesc.DecodeProfile = profileGUID;
    viewDesc.ViewDimension = D3D11_VDOV_DIMENSION_TEXTURE2D;
    viewDesc.Texture2D.ArraySlice = i;

    hr = pDeviceContext->video_device->CreateVideoDecoderOutputView(pFramesContext->texture, &viewDesc, &m_pOutputViews[i]);
    if (FAILED(hr))
    {
      DbgLog((LOG_ERROR, 10, L"-> Failed to create video decoder output views"));
      return E_FAIL;
    }
  }

  // create the decoder
  hr = pDeviceContext->video_device->CreateVideoDecoder(&desc, &decoder_config, &m_pDecoder);
  if (FAILED(hr))
  {
    DbgLog((LOG_ERROR, 10, L"-> Failed to create video decoder object"));
    return E_FAIL;
  }

  FillHWContext((AVD3D11VAContext *)m_pAVCtx->hwaccel_context);

  return S_OK;
}