コード例 #1
0
HRESULT
ComObjBase::InternalQueryInterface(REFIID riid, void** ppv)
{
  LOGCALL(("%s::InternalQueryInterface(%s)\n", typeid(*this).name(), StringFromGuid(riid)));

  if (ppv == NULL)
    return E_INVALIDARG;
  *ppv = NULL;

  IUnknown* pUnknown = NULL;
  if (riid == IID_IUnknown)
    pUnknown = static_cast<IUnknown*>(this);
  else
    {
      HRESULT hr = GetInterface(riid, &pUnknown);
      if (FAILED(hr))
	return hr;
      assert(pUnknown != NULL);
    }

  pUnknown->AddRef();
  *ppv = pUnknown;
  return S_OK;
}
コード例 #2
0
// @pymethod |PyIBackgroundCopyJob|SetNotifyInterface|Description of SetNotifyInterface.
PyObject *PyIBackgroundCopyJob::SetNotifyInterface(PyObject *self, PyObject *args)
{
	IBackgroundCopyJob *pIBCJ = GetI(self);
	if ( pIBCJ == NULL )
		return NULL;
	// @pyparm <o PyIUnknown *>|Val||Description for Val
	PyObject *obVal;
	IUnknown *Val;
	if ( !PyArg_ParseTuple(args, "O:SetNotifyInterface", &obVal) )
		return NULL;
	BOOL bPythonIsHappy = TRUE;
	if (!PyCom_InterfaceFromPyInstanceOrObject(obVal, IID_IUnknown, (void **)&Val, TRUE /* bNoneOK */))
		return NULL;
	HRESULT hr;
	PY_INTERFACE_PRECALL;
	hr = pIBCJ->SetNotifyInterface( Val );
	if (Val) Val->Release();
	PY_INTERFACE_POSTCALL;
	if ( FAILED(hr) )
		return PyCom_BuildPyException(hr, pIBCJ, IID_IBackgroundCopyJob );
	Py_INCREF(Py_None);
	return Py_None;

}
コード例 #3
0
ファイル: clthndlr.cpp プロジェクト: mingpen/OpenNT
//+---------------------------------------------------------------------------
//
//  Method:     CClientSiteHandler::SetClientSiteDelegate
//
//  Synopsis:
//
//  Arguments:  [dwId] --
//              [pUnk] --
//
//  Returns:
//
//  History:    11-17-95   JohannP (Johann Posch)   Created
//
//  Notes:
//
//----------------------------------------------------------------------------
void CClientSiteHandler::SetClientSiteDelegate(DWORD dwId, IUnknown *pUnk)
{
    HdlDebugOut((DEB_CLIENTHANDLER_UNKNOWN, "%p _IN CClientSiteHandler::SetClientSiteDelegate\n", this));
    HdlAssert(( dwId > 0 && dwId <= ID_Container));

    if (( dwId > 0 && dwId <= ID_Container))
    {
        IUnknown *pUnkOld = GetPUnkClientSiteDelegate(dwId);
        if (pUnk)
        {
            pUnk->AddRef();
        }
        if (pUnkOld)
        {
            pUnkOld->Release();
        }
    }

    switch (dwId)
    {
    case ID_ClientSite:
        _pOCS = (IOleClientSite *) pUnk;
        break;
    case ID_ClientSiteActive:
        _pOCSActive = (IOleClientSite *) pUnk;
        break;
    case ID_InPlaceSite:
        _pOIPS = (IOleInPlaceSite *) pUnk;
        break;
    case ID_Container:
        _pOCont = (IOleContainer *) pUnk;
        break;
    default:
        HdlAssert((FALSE  && "Invalid ID for delegate"));
    }
}
コード例 #4
0
//
//  Function: DllGetClassObject
//
//  Summary:  The standard exported function that the COM service library
//            uses to obtain an object class of the class factory for a
//            specified component provided by this server DLL.
//
//  Args:     REFCLSID rclsid,
//              [in] The CLSID of the requested Component.
//            REFIID riid,
//              [in] GUID of the requested interface on the Class Factory.
//            LPVOID* ppv)
//              [out] Address of the caller's pointer variable that will
//              receive the requested interface pointer.
//
//  Returns:  HRESULT
//              E_FAIL if requested component isn't supported.
//              E_OUTOFMEMORY if out of memory.
//              Error code out of the QueryInterface.
//  ***********************************************************************************************
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
{
	HRESULT hError = CLASS_E_CLASSNOTAVAILABLE;
	IUnknown* pCob = NULL;
	CaComServer* pServer = theApp.GetServer();

	if (CLSID_IMPxEXPxASSISTANCT == rclsid)
	{
		hError = E_OUTOFMEMORY;
		pCob = new CaFactoryImportExport(NULL, pServer);
	}

	if (NULL != pCob)
	{
		hError = pCob->QueryInterface(riid, ppv);
		if (FAILED(hError))
		{
			delete pCob;
			pCob = NULL;
		}
	}

	return hError;
}
コード例 #5
0
bool msado::command_event::enable_event(bool enable/* = true*/)
{
	if (enable)
	{
		if (!pconnPointer)return false;

		IUnknown* pEvent;
		HRESULT hr = this->QueryInterface(IID_IUnknown, (void**)&pEvent);
		if (FAILED(hr))return false;

		hr = pconnPointer->Advise(pEvent, &dw_event_);
		if (FAILED(hr))return false;
		pEvent->Release();

		return hr == S_OK;
	}
	else
	{
		if (dw_event_ == 0)return false;
		if (!pconnPointer)return false;
		HRESULT hr = pconnPointer->Unadvise(dw_event_);
		return hr == S_OK;
	}
}
コード例 #6
0
void MFStream::doRead()
{
    bool readDone = true;
    IUnknown *pUnk = NULL;
    HRESULT    hr = m_currentReadResult->GetObject(&pUnk);
    if (SUCCEEDED(hr)) {
        //do actual read
        AsyncReadState *state =  static_cast<AsyncReadState*>(pUnk);
        ULONG cbRead;
        Read(state->pb(), state->cb() - state->bytesRead(), &cbRead);
        pUnk->Release();

        state->setBytesRead(cbRead + state->bytesRead());
        if (state->cb() > state->bytesRead() && !m_stream->atEnd()) {
            readDone = false;
        }
    }

    if (readDone) {
        //now inform the original caller
        m_currentReadResult->SetStatus(hr);
        MFInvokeCallback(m_currentReadResult);
    }
}
コード例 #7
0
// @pymethod |PyIFileOperation|DeleteItems|Adds multiple delete operations to the configuration
PyObject *PyIFileOperation::DeleteItems(PyObject *self, PyObject *args)
{
    IFileOperation *pIFO = GetI(self);
    if ( pIFO == NULL )
        return NULL;
    // @pyparm <o PyIUnknown>|Items||<o PyIShellItemArray>, <o PyIDataObject>, or <o PyIEnumShellItems> containing the items to be deleted
    PyObject *obItems;
    IUnknown * pItems;
    if ( !PyArg_ParseTuple(args, "O:DeleteItems", &obItems) )
        return NULL;
    if (!PyCom_InterfaceFromPyInstanceOrObject(obItems, IID_IUnknown, (void **)&pItems, FALSE))
        return NULL;

    HRESULT hr;
    PY_INTERFACE_PRECALL;
    hr = pIFO->DeleteItems(pItems);
    pItems->Release();
    PY_INTERFACE_POSTCALL;

    if ( FAILED(hr) )
        return PyCom_BuildPyException(hr, pIFO, IID_IFileOperation );
    Py_INCREF(Py_None);
    return Py_None;
}
コード例 #8
0
HRESULT
CVDevParallelQueue::Initialize()
{
    HRESULT hr;


    {
        IUnknown *callback = QueryIUnknown();

        hr = m_FxDevice->CreateIoQueue (
            callback,
            true,                       // This is the default queue object
            WdfIoQueueDispatchParallel,
            true,                       // Let the Framework handle PowMgmt.
            true,
            &m_FxQueue);

        callback->Release();
    }

    if (FAILED (hr))
    {
        return hr;
    }
    else
    {
        m_FxQueue->Release();
    }
    
    if (!InitializeCriticalSectionAndSpinCount(&m_Crit,0x80000400))
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
    }

    return hr;
}
コード例 #9
0
HRESULT
DispatchForwarder::QueryInterface(REFIID riid, void** ppv)
{
  if (!ppv) {
    return E_INVALIDARG;
  }

  // Since this class implements a tearoff, any interfaces that are not
  // IDispatch must be routed to the original object's QueryInterface.
  // This is especially important for IUnknown since COM uses that interface
  // to determine object identity.
  if (riid != IID_IDispatch) {
    return mInterceptor->QueryInterface(riid, ppv);
  }

  IUnknown* punk = static_cast<IDispatch*>(this);
  *ppv = punk;
  if (!punk) {
    return E_NOINTERFACE;
  }

  punk->AddRef();
  return S_OK;
}
コード例 #10
0
ULONG      CProxyDirect3D9::Release                     ( VOID )
{
    ULONG       ulRefCount;
    IUnknown *  pDestroyedDevice;

    // Check to see if we should self-destruct
    if ( --m_dwRefCount == 0 )
    {
        // Save device so we can destroy it after.
        pDestroyedDevice = m_pDevice;

        delete this;  

        // Call device's AddRef routine and get the current refcount.
        ulRefCount = pDestroyedDevice->Release( );

        return ulRefCount;
    }

    // Call device's AddRef routine and get the current refcount.
    ulRefCount = m_pDevice->Release( );

    return ulRefCount;          
}
コード例 #11
0
static HRESULT
VBoxSafeArrayCopyOutIfaceParamHelper(IUnknown ***ppaObj, ULONG *pcObj, SAFEARRAY *psa)
{
    ULONG mypcb;
    HRESULT rc = VBoxSafeArrayCopyOutParamHelper((void **)ppaObj, &mypcb, VT_UNKNOWN, psa);
    if (FAILED(rc))
        return rc;
    ULONG cElements = mypcb / sizeof(void *);
    if (pcObj)
        *pcObj = cElements;
#ifndef VBOX_WITH_XPCOM
    /* Do this only for COM, as there the SAFEARRAY destruction will release
     * the contained references automatically. XPCOM doesn't do that, which
     * means that copying implicitly transfers ownership. */
    IUnknown **paObj = *ppaObj;
    for (ULONG i = 0; i < cElements; i++)
    {
        IUnknown *pObj = paObj[i];
        if (pObj)
            pObj->AddRef();
    }
#endif /* VBOX_WITH_XPCOM */
    return S_OK;
}
コード例 #12
0
ファイル: TODOCTL.CPP プロジェクト: Jichao/comtut
//=--------------------------------------------------------------------------=
// CToDoControl::InternalQueryInterface
//=--------------------------------------------------------------------------=
// qi for things only we support.
//
// Parameters:
// Parameters:
//    REFIID        - [in]  interface they want
//    void **       - [out] where they want to put the resulting object ptr.
//
// Output:
//    HRESULT       - S_OK, E_NOINTERFACE
//
// Notes:
//
HRESULT CToDoControl::InternalQueryInterface
(
    REFIID  riid,
    void  **ppvObjOut
)
{
    IUnknown *pUnk;

    *ppvObjOut = NULL;

    // TODO: if you want to support any additional interrfaces, then you should
    // indicate that here.  never forget to call the base class version in the
    // case where you don't support the given interface.
    //
    if (DO_GUIDS_MATCH(riid, IID_IToDo)) {
        pUnk = (IUnknown *)(IToDo *)this;
    } else {
        return CDocumentObject::InternalQueryInterface(riid, ppvObjOut);
    }

    pUnk->AddRef();
    *ppvObjOut = (void *)pUnk;
    return S_OK;
}
コード例 #13
0
// @pymethod |PyIObjectCollection|AddObject|Adds a single object to the collection
PyObject *PyIObjectCollection::AddObject(PyObject *self, PyObject *args)
{
	IObjectCollection *pIOC = GetI(self);
	if ( pIOC == NULL )
		return NULL;
	IUnknown *punk;
	PyObject *obpunk;
	// @pyparm <o PyIUnknown>|punk||Object to be added
	if ( !PyArg_ParseTuple(args, "O:AddObject", &obpunk) )
		return NULL;
	if (!PyCom_InterfaceFromPyObject(obpunk, IID_IUnknown, (void **)&punk, FALSE))
		return NULL;
	HRESULT hr;
	PY_INTERFACE_PRECALL;
	hr = pIOC->AddObject( punk );
	punk->Release();
	PY_INTERFACE_POSTCALL;

	if ( FAILED(hr) )
		return PyCom_BuildPyException(hr, pIOC, IID_IObjectCollection );
	Py_INCREF(Py_None);
	return Py_None;

}
コード例 #14
0
//----------------------------- FUNCTION -------------------------------------*
void CSheetConfigGSD::InitErrorPage()
{
    CComQIPtr<IDP_Station, &IID_IDP_Station>    pStation;
    pStation = m_pUnknown;

	if (pStation)	{
		LONG lErrors;
        HRESULT hr = pStation->get_ErrorCount(&lErrors);
        if (SUCCEEDED(hr) && (lErrors > 0)) {
			AddPage(m_pErrorPage);				// show ErrorPage if there are some errors
			m_pErrorPage->SetErrorCount(lErrors);
			IUnknown* pUnk = NULL;
			hr = pStation->get_ErrorStrings(&pUnk);
			if (SUCCEEDED(hr)) {
				CComQIPtr<IEnumString, &IID_IEnumString>    pEnum;
				pEnum = pUnk;
				pUnk->Release();
				if (pEnum == NULL) {
					return;
				}
				ULONG   ulFetched = 0;
				LPOLESTR  pText = NULL;
				HRESULT hr = S_FALSE;
				USES_CONVERSION;
				// enumerate thru ext user params!
				while (pEnum->Next(1, &pText, &ulFetched) == S_OK)
				{
					CString strError = pText;
					m_pErrorPage->AddErrorString(strError);
					::CoTaskMemFree(pText);
				}
			}// end if
			SetActivePage(m_pErrorPage);
        }// end if
	}// end if
}
コード例 #15
0
ファイル: regmeta.cpp プロジェクト: 0-wiz-0/coreclr
//*****************************************************************************
// This function returns the requested public interface based on the given
// internal import interface.
// A common path to call this is updating the matedata for dynamic modules.
//*****************************************************************************
STDAPI MDReOpenMetaDataWithMemoryEx(
    void        *pImport,               // [IN] Given scope. public interfaces
    LPCVOID     pData,                  // [in] Location of scope data.
    ULONG       cbData,                 // [in] Size of the data pointed to by pData.
    DWORD       dwReOpenFlags)          // [in] Flags for ReOpen
{
    HRESULT             hr = S_OK;
    IUnknown            *pUnk = (IUnknown *) pImport;
    IMetaDataImport2    *pMDImport = NULL;
    RegMeta             *pRegMeta = NULL;
   
    _ASSERTE(pImport);

    IfFailGo( pUnk->QueryInterface(IID_IMetaDataImport2, (void **) &pMDImport) );
    pRegMeta = (RegMeta*) pMDImport;

    IfFailGo( pRegMeta->ReOpenWithMemory(pData, cbData, dwReOpenFlags) );

ErrExit:
    if (pMDImport)
        pMDImport->Release();
   
    return hr;
} // MDReOpenMetaDataWithMemoryEx
コード例 #16
0
ファイル: trifiltr.cpp プロジェクト: 0anion0/IBN
HRESULT
CSite::HrFilterOutStream(LPSTREAM pSourceStream, LPSTREAM &pOutputStream, DWORD dwFlags)
{
	HRESULT hr = S_OK;
//	IStream* pOutputStream = NULL;
	ITriEditDocument* pTriEditDoc = NULL;
	IUnknown* lpUnk = NULL;
	IUnknown* lpStreamUnk = NULL;
	
	lpUnk = GetObjectUnknown();

	if (NULL == lpUnk)
		return E_FAIL;

	// get ITriEditDoc
	if (FAILED(hr = lpUnk->QueryInterface(IID_ITriEditDocument, (LPVOID*) &pTriEditDoc)))
		return hr;

	if (FAILED(hr = pTriEditDoc->FilterOut(pSourceStream, &lpStreamUnk, dwFlags, NULL)))
		goto cleanup;

	if (FAILED(hr = lpStreamUnk->QueryInterface(IID_IStream, (LPVOID*) &pOutputStream)))
		goto cleanup;

//	if (FAILED(hr = HrStreamToFile(pOutputStream, fileName)))
//		goto cleanup;



cleanup:

	ReleaseInterface(pTriEditDoc);
	ReleaseInterface(lpStreamUnk);
//	ReleaseInterface(pOutputStream);
	return hr;
}
コード例 #17
0
void displayProperties( IBaseFilter *pFilter ){
	ISpecifyPropertyPages *pProp;
	
	HRESULT hr = pFilter->QueryInterface(IID_ISpecifyPropertyPages, (void **)&pProp);
	
	if (SUCCEEDED(hr)) 
	{
		// Get the filter's name and IUnknown pointer.
		FILTER_INFO FilterInfo;
		hr = pFilter->QueryFilterInfo(&FilterInfo); 
		IUnknown *pFilterUnk;
		pFilter->QueryInterface(IID_IUnknown, (void **)&pFilterUnk);

		// Show the page. 
		CAUUID caGUID;
		pProp->GetPages(&caGUID);
		pProp->Release();
		OleCreatePropertyFrame(
        0,                   // Parent window
        0, 0,                   // Reserved
        FilterInfo.achName,     // Caption for the dialog box
        1,                      // Number of objects (just the filter)
        &pFilterUnk,            // Array of object pointers. 
        caGUID.cElems,          // Number of property pages
        caGUID.pElems,          // Array of property page CLSIDs
        0,                      // Locale identifier
        0, NULL                 // Reserved
    );

    // Clean up.
    pFilterUnk->Release();
    FilterInfo.pGraph->Release(); 
    CoTaskMemFree(caGUID.pElems);
}

}
コード例 #18
0
ファイル: AudioDevice_X28 .hpp プロジェクト: Siv3D/OpenSiv3D
		void release()
		{
			if (pXAPO)
			{
				pXAPO->Release();
				pXAPO = nullptr;
			}

			if (masteringVoice)
			{
				masteringVoice->DestroyVoice();
				masteringVoice = nullptr;
			}

			if (xAudio2)
			{
				xAudio2->Release();
				xAudio2 = nullptr;
			}
		}
コード例 #19
0
HRESULT CAMVfwCompressDialogs::GetPropertyWindow(VfwCompressDialogs iDialog, const ACamstudioFilter *pFilter)
{
	if(!pFilter)
		return E_FAIL;
	if(!pFilter->GetFilter())
		return E_FAIL;
	
	IAMVfwCompressDialogs *pCompDialog = NULL;
	HRESULT hr = pFilter->GetFilter()->QueryInterface(IID_IAMVfwCompressDialogs, (void**)& pCompDialog);
	if(SUCCEEDED(hr))
	{
		hr = pCompDialog->ShowDialog(iDialog, m_hWnd);
		return hr;
	}
	if(iDialog == VfwCompressDialog_QueryAbout || iDialog == VfwCompressDialog_About)
	{
		return E_FAIL;
	}

	ISpecifyPropertyPages *pProp;
	hr = pFilter->GetFilter()->QueryInterface(IID_ISpecifyPropertyPages, (void **)&pProp);
	if (SUCCEEDED(hr)) 
	{
		if(VfwCompressDialog_QueryConfig == iDialog || VfwCompressDialog_QueryAbout == iDialog)
		{
			return hr;
		}
		// Get the filter's name and IUnknown pointer.
		FILTER_INFO FilterInfo;
		hr = pFilter->GetFilter()->QueryFilterInfo(&FilterInfo);
		if(FAILED(hr))
			return E_FAIL;
		IUnknown *pFilterUnk = 0;

		if(SUCCEEDED(pFilter->GetFilter()->QueryInterface(IID_IUnknown, (void **)&pFilterUnk)))
		{
			// Show the page. 
			CAUUID caGUID;
			pProp->GetPages(&caGUID);
			pProp->Release();
			OleCreatePropertyFrame(
				m_hWnd,                 // Parent window
				0, 0,                   // Reserved
				FilterInfo.achName,     // Caption for the dialog box
				1,                      // Number of objects (just the filter)
				&pFilterUnk,            // Array of object pointers. 
				caGUID.cElems,          // Number of property pages
				caGUID.pElems,          // Array of property page CLSIDs
				0,                      // Locale identifier
				0, NULL                 // Reserved
				);

			// Clean up.
			if(pFilterUnk)
				pFilterUnk->Release();
			if(FilterInfo.pGraph)
				FilterInfo.pGraph->Release(); 
			if(caGUID.pElems)
				CoTaskMemFree(caGUID.pElems);
		}
	}
	return hr;
}
コード例 #20
0
ファイル: HbgEngine.cpp プロジェクト: plantrue/Hambugger
BOOL CHbgEngine::Initialize(LPCWSTR pathDebuggee, DWORD pidDebuggee)
{
	HRESULT hr = E_FAIL;
	std::wstring strErr;
	m_bRun = TRUE;

	// 기존에 동작하고 있었다면 종료
	if (m_pIHbgDebug && m_pIUnkCallback)
		m_pIHbgDebug->Uninitialize(TRUE);

	if (!m_pIUnkCallback) {
		// 1) HbgMain 컴포넌트 생성
		CLSID clsid_hbgmain;
		hr = ::CLSIDFromProgID(HBG_HBGMAIN_PROGID, &clsid_hbgmain);
		if (SUCCEEDED(hr))
			hr = ::CoCreateInstance(clsid_hbgmain, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (LPVOID*)&m_pIUnkCallback);
		else
			strErr = L"등록 필요";
	} else {
		// IHbgCallback 인터페이스가 이미 존재
		hr = S_OK;
	}

	if (SUCCEEDED(hr) && m_pIUnkCallback) {
		if (!m_pIHbgDebug) {
			// 2) HbgServ 컴포넌트 생성
			CLSID clsid_hbgserv;
			hr = ::CLSIDFromProgID(HBG_HBGSERV_PROGID, &clsid_hbgserv);
			if (SUCCEEDED(hr)) {
				MULTI_QI mqi[] = { { &IID_IUnknown, NULL, S_OK }, };
				COSERVERINFO csi = { 0, NULL, NULL, 0 };
				hr = ::CoCreateInstanceEx(clsid_hbgserv, NULL, CLSCTX_ALL, &csi, sizeof(mqi) / sizeof(mqi[0]), mqi);
				if (SUCCEEDED(hr)) {
					IUnknown* pIUnkServ = mqi[0].pItf;
					hr = pIUnkServ->QueryInterface(IID_IHbgDebug, (LPVOID*)&m_pIHbgDebug);
					pIUnkServ->Release();
				}
			} else {
				strErr = L"등록 필요";
			}
		} else {
			// IHbgDebug 인터페이스가 이미 존재
			hr = S_OK;
		}

		if (SUCCEEDED(hr) && m_pIHbgDebug) {

#ifdef _DEBUG
			::AfxMessageBox(L"디버거 연결", MB_ICONINFORMATION|MB_OK);
#endif _DEBUG

			// 3) 컴포넌트 초기화
			if (pathDebuggee)
				hr = m_pIHbgDebug->Initialize(pathDebuggee, IID_IUnknown, m_pIUnkCallback);
			else if (pidDebuggee)
				hr = m_pIHbgDebug->InitializeEx(pidDebuggee, IID_IUnknown, m_pIUnkCallback);
			else
				hr = E_FAIL;
		}
	}

	BOOL bSucceeded = SUCCEEDED(hr);
	if (!bSucceeded) {
		if (strErr.empty())
			strErr = L"연결 실패";
		::AfxMessageBox(strErr.c_str(), MB_ICONEXCLAMATION|MB_OK);
	}

	return bSucceeded;
}
コード例 #21
0
// Process any pending output from the decoder (until all output is
// processed).
//
// Thread context: decoder thread
bool DecoderMF::DoProcessOutput()
{
	bool						ret = false;
	HRESULT						hr;
	MFT_OUTPUT_DATA_BUFFER		mftDataBuffer;
	DWORD						mftStatus;
	bool						moreOutput;

	if (m_outputSample == NULL)
	{
		if (! CreateOutputSample())
			return false;
	}

	do
	{
		// Since we could be looping inside this method for a while,
		// if a whole stack of frames arrive at once, we want to exit
		// if the thread has been asked to die. So check on each
		// iteration of the loop.
		if (! m_decoderThreadRunning)
			return true;

		moreOutput = false;

		mftDataBuffer.dwStreamID = 0;
		mftDataBuffer.pSample = m_outputSample;
		mftDataBuffer.dwStatus = 0;
		mftDataBuffer.pEvents = NULL;
		mftStatus = 0;

		// Looks like we have to reset the sample before use:
		IMFMediaBuffer* mediaBuffer;
		hr = m_outputSample->GetBufferByIndex(0, &mediaBuffer);
		if (FAILED(hr))
			goto bail;

		hr = mediaBuffer->SetCurrentLength(0);
		if (FAILED(hr))
			goto bail;

		mediaBuffer->Release();

		hr = m_h264Decoder->ProcessOutput(0, 1, &mftDataBuffer, &mftStatus);

		// Check return code
		if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT)
			break;
		EnterCriticalSection(&m_criticalSection);
		if (hr == MF_E_TRANSFORM_STREAM_CHANGE || !m_previewConfigured)
		{
			// If the output format has changed, we need to handle
			// the stream change. This will happen after the first
			// few packets have been delivered.
			moreOutput = HandleStreamChange();
			LeaveCriticalSection(&m_criticalSection);
			if (!moreOutput)
				goto bail;
			continue;
		}
		LeaveCriticalSection(&m_criticalSection);
		if (FAILED(hr))
			goto bail;

		if (mftDataBuffer.dwStatus == MFT_OUTPUT_DATA_BUFFER_INCOMPLETE)
			moreOutput = true;

		// Process each event:
		if (mftDataBuffer.pEvents != NULL)
		{
			DWORD numElements;
			hr = mftDataBuffer.pEvents->GetElementCount(&numElements);
			if (SUCCEEDED(hr))
			{
				for (DWORD i = 0; i < numElements; i++)
				{
					IUnknown* iunk = NULL;

					hr = mftDataBuffer.pEvents->GetElement(i, &iunk);
					if (SUCCEEDED(hr))
					{
						IMFMediaEvent* mediaEvent = NULL;
						hr = iunk->QueryInterface(IID_IMFMediaEvent, (void**)&mediaEvent);

						if (SUCCEEDED(hr))
						{
							OutputDebugString(_T("FIXME: process event!\n"));

							mediaEvent->Release();
						}

						iunk->Release();
					}
				}
			}

			mftDataBuffer.pEvents = NULL;
		}

		// Process sample:
		if (mftDataBuffer.pSample != NULL)
		{
			IMFMediaBuffer* mediaBuffer;
			hr = mftDataBuffer.pSample->GetBufferByIndex(0, &mediaBuffer);
			if (FAILED(hr))
				goto bail;

			EnterCriticalSection(&m_criticalSection);

				if (m_previewWindow != NULL && m_previewConfigured)
					m_previewWindow->DrawFrame(mediaBuffer);

			LeaveCriticalSection(&m_criticalSection);

			mediaBuffer->Release();
		}
	} while(moreOutput);

	ret = true;

bail:
	if (ret == false)
		OutputDebugString(_T("ERROR: failed to process output...\n"));

	return ret;
}
コード例 #22
0
/*
========================
idSoundHardware_XAudio2::Init
========================
*/
void idSoundHardware_XAudio2::Init()
{

	cmdSystem->AddCommand( "listDevices", listDevices_f, 0, "Lists the connected sound devices", NULL );
	
	DWORD xAudioCreateFlags = 0;
	
// RB: not available on Windows 8 SDK
#if !defined(USE_WINRT) && defined(_DEBUG) // (_WIN32_WINNT < 0x0602 /*_WIN32_WINNT_WIN8*/) && defined(_DEBUG)
	xAudioCreateFlags |= XAUDIO2_DEBUG_ENGINE;
#endif
// RB end

	XAUDIO2_PROCESSOR xAudioProcessor = XAUDIO2_DEFAULT_PROCESSOR;
	
// RB: not available on Windows 8 SDK
	if( FAILED( XAudio2Create( &pXAudio2, xAudioCreateFlags, xAudioProcessor ) ) )
	{
#if !defined(USE_WINRT) && defined(_DEBUG) // (_WIN32_WINNT < 0x0602 /*_WIN32_WINNT_WIN8*/) && defined(_DEBUG)
		if( xAudioCreateFlags & XAUDIO2_DEBUG_ENGINE )
		{
			// in case the debug engine isn't installed
			xAudioCreateFlags &= ~XAUDIO2_DEBUG_ENGINE;
			if( FAILED( XAudio2Create( &pXAudio2, xAudioCreateFlags, xAudioProcessor ) ) )
			{
				idLib::FatalError( "Failed to create XAudio2 engine.  Try installing the latest DirectX." );
				return;
			}
		}
		else
#endif
// RB end
		{
			idLib::FatalError( "Failed to create XAudio2 engine.  Try installing the latest DirectX." );
			return;
		}
	}
#ifdef _DEBUG
	XAUDIO2_DEBUG_CONFIGURATION debugConfiguration = { 0 };
	debugConfiguration.TraceMask = XAUDIO2_LOG_WARNINGS;
	debugConfiguration.BreakMask = XAUDIO2_LOG_ERRORS;
	pXAudio2->SetDebugConfiguration( &debugConfiguration );
#endif
	
	// Register the sound engine callback
	pXAudio2->RegisterForCallbacks( &soundEngineCallback );
	soundEngineCallback.hardware = this;
	UINT32 deviceCount = 0;
	DWORD outputSampleRate = 44100; // Max( (DWORD)XAUDIO2FX_REVERB_MIN_FRAMERATE, Min( (DWORD)XAUDIO2FX_REVERB_MAX_FRAMERATE, deviceDetails.OutputFormat.Format.nSamplesPerSec ) );
	
	// RB: not available on Windows 8 SDK
#if defined(USE_WINRT) //(_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/)
	
	IMMDeviceEnumerator*     immDevEnum       = nullptr;
	IMMDeviceCollection*     immDevCollection = nullptr;
	IMMDevice*               immDev           = nullptr;
	std::vector<AudioDevice> vAudioDevices;
	
	HRESULT hResult = CoCreateInstance(
						  __uuidof( MMDeviceEnumerator ), NULL,
						  CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ), ( void** ) &immDevEnum );
						  
	if( FAILED( hResult ) )
	{
		idLib::Warning( "Failed to get audio enumerator" );
		pXAudio2->Release();
		pXAudio2 = NULL;
		return;
	}
	
	hResult = immDevEnum->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &immDevCollection );
	if( FAILED( hResult ) )
	{
		idLib::Warning( "Failed to get audio endpoints" );
		pXAudio2->Release();
		pXAudio2 = NULL;
		return;
	}
	
	hResult = immDevCollection->GetCount( &deviceCount );
	if( FAILED( hResult ) )
	{
		idLib::Warning( "No audio devices found" );
		pXAudio2->Release();
		pXAudio2 = NULL;
		return;
	}
	
	for( UINT i = 0; i < deviceCount; i++ )
	{
		IPropertyStore* propStore = nullptr;
		PROPVARIANT     varName;
		PROPVARIANT     varId;
		
		PropVariantInit( &varId );
		PropVariantInit( &varName );
		
		hResult = immDevCollection->Item( i, &immDev );
		if( SUCCEEDED( hResult ) )
		{
			hResult = immDev->OpenPropertyStore( STGM_READ, &propStore );
		}
		if( SUCCEEDED( hResult ) )
		{
			hResult = propStore->GetValue( PKEY_AudioEndpoint_Path, &varId );
		}
		
		if( SUCCEEDED( hResult ) )
		{
			hResult = propStore->GetValue( PKEY_Device_FriendlyName, &varName );
		}
		
		if( SUCCEEDED( hResult ) )
		{
			assert( varId.vt == VT_LPWSTR );
			assert( varName.vt == VT_LPWSTR );
			
			// Now save somewhere the device display name & id
			AudioDevice ad;
			ad.name = varName.pwszVal;
			ad.id   = varId.pwszVal;
			
			vAudioDevices.push_back( ad );
		}
		
		PropVariantClear( &varName );
		PropVariantClear( &varId );
		
		if( propStore != nullptr )
		{
			propStore->Release();
		}
		
		if( immDev != nullptr )
		{
			immDev->Release();
		}
	}
	
	
	immDevCollection->Release();
	immDevEnum->Release();
	
	int preferredDevice = s_device.GetInteger();
	if( !vAudioDevices.empty() )
	{
		if( SUCCEEDED( pXAudio2->CreateMasteringVoice( &pMasterVoice,
					   XAUDIO2_DEFAULT_CHANNELS,
					   outputSampleRate,
					   0,
					   vAudioDevices.at( 0 ).id.c_str(),
					   NULL,
					   AudioCategory_GameEffects ) ) )
		{
			XAUDIO2_VOICE_DETAILS deviceDetails;
			pMasterVoice->GetVoiceDetails( &deviceDetails );
			
			pMasterVoice->SetVolume( DBtoLinear( s_volume_dB.GetFloat() ) );
			
			outputChannels = deviceDetails.InputChannels;
			DWORD win8_channelMask;
			pMasterVoice->GetChannelMask( &win8_channelMask );
			
			channelMask = ( unsigned int )win8_channelMask;
			idLib::Printf( "Using device %s\n", vAudioDevices.at( 0 ).name );
		}
		else
		{
			idLib::Warning( "Failed to create master voice" );
			pXAudio2->Release();
			pXAudio2 = NULL;
			return;
		}
	}
	
#else
	if( pXAudio2->GetDeviceCount( &deviceCount ) != S_OK || deviceCount == 0 )
	{
		idLib::Warning( "No audio devices found" );
		pXAudio2->Release();
		pXAudio2 = NULL;
		return;
	}
	
	idCmdArgs args;
	listDevices_f( args );
	
	int preferredDevice = s_device.GetInteger();
	if( preferredDevice < 0 || preferredDevice >= ( int )deviceCount )
	{
		int preferredChannels = 0;
		for( unsigned int i = 0; i < deviceCount; i++ )
		{
			XAUDIO2_DEVICE_DETAILS deviceDetails;
			if( pXAudio2->GetDeviceDetails( i, &deviceDetails ) != S_OK )
			{
				continue;
			}
	
			if( deviceDetails.Role & DefaultGameDevice )
			{
				// if we find a device the user marked as their preferred 'game' device, then always use that
				preferredDevice = i;
				preferredChannels = deviceDetails.OutputFormat.Format.nChannels;
				break;
			}
	
			if( deviceDetails.OutputFormat.Format.nChannels > preferredChannels )
			{
				preferredDevice = i;
				preferredChannels = deviceDetails.OutputFormat.Format.nChannels;
			}
		}
	}
	
	idLib::Printf( "Using device %d\n", preferredDevice );
	
	XAUDIO2_DEVICE_DETAILS deviceDetails;
	if( pXAudio2->GetDeviceDetails( preferredDevice, &deviceDetails ) != S_OK )
	{
		// One way this could happen is if a device is removed between the loop and this line of code
		// Highly unlikely but possible
		idLib::Warning( "Failed to get device details" );
		pXAudio2->Release();
		pXAudio2 = NULL;
		return;
	}
	
	
	if( FAILED( pXAudio2->CreateMasteringVoice( &pMasterVoice, XAUDIO2_DEFAULT_CHANNELS, outputSampleRate, 0, preferredDevice, NULL ) ) )
	{
		idLib::Warning( "Failed to create master voice" );
		pXAudio2->Release();
		pXAudio2 = NULL;
		return;
	}
	pMasterVoice->SetVolume( DBtoLinear( s_volume_dB.GetFloat() ) );
	
	outputChannels = deviceDetails.OutputFormat.Format.nChannels;
	channelMask = deviceDetails.OutputFormat.dwChannelMask;
	
#endif // #if (_WIN32_WINNT < 0x0602 /*_WIN32_WINNT_WIN8*/)
	
	idSoundVoice::InitSurround( outputChannels, channelMask );
	
	// ---------------------
	// Create VU Meter Effect
	// ---------------------
	IUnknown* vuMeter = NULL;
	XAudio2CreateVolumeMeter( &vuMeter, 0 );
	
	XAUDIO2_EFFECT_DESCRIPTOR descriptor;
	descriptor.InitialState = true;
	descriptor.OutputChannels = outputChannels;
	descriptor.pEffect = vuMeter;
	
	XAUDIO2_EFFECT_CHAIN chain;
	chain.EffectCount = 1;
	chain.pEffectDescriptors = &descriptor;
	
	pMasterVoice->SetEffectChain( &chain );
	
	vuMeter->Release();
	
	// ---------------------
	// Create VU Meter Graph
	// ---------------------
	
	vuMeterRMS = console->CreateGraph( outputChannels );
	vuMeterPeak = console->CreateGraph( outputChannels );
	// DG: make sure they're not NULL (as it's currently the case with the cegui-based console)
	if( vuMeterRMS && vuMeterPeak )
	{
		vuMeterRMS->Enable( false );
		vuMeterPeak->Enable( false );
		
		memset( vuMeterPeakTimes, 0, sizeof( vuMeterPeakTimes ) );
		
		vuMeterPeak->SetFillMode( idDebugGraph::GRAPH_LINE );
		vuMeterPeak->SetBackgroundColor( idVec4( 0.0f, 0.0f, 0.0f, 0.0f ) );
		
		vuMeterRMS->AddGridLine( 0.500f, idVec4( 0.5f, 0.5f, 0.5f, 1.0f ) );
		vuMeterRMS->AddGridLine( 0.250f, idVec4( 0.5f, 0.5f, 0.5f, 1.0f ) );
		vuMeterRMS->AddGridLine( 0.125f, idVec4( 0.5f, 0.5f, 0.5f, 1.0f ) );
		
		const char* channelNames[] = { "L", "R", "C", "S", "Lb", "Rb", "Lf", "Rf", "Cb", "Ls", "Rs" };
		for( int i = 0, ci = 0; ci < sizeof( channelNames ) / sizeof( channelNames[0] ); ci++ )
		{
			if( ( channelMask & BIT( ci ) ) == 0 )
			{
				continue;
			}
			vuMeterRMS->SetLabel( i, channelNames[ci] );
			i++;
		}
	}
	
	// ---------------------
	// Create submix buffer
	// ---------------------
	if( FAILED( pXAudio2->CreateSubmixVoice( &pSubmixVoice, 1, outputSampleRate, 0, 0, NULL, NULL ) ) )
	{
		idLib::FatalError( "Failed to create submix voice" );
	}
	
	// XAudio doesn't really impose a maximum number of voices
	voices.SetNum( voices.Max() );
	freeVoices.SetNum( voices.Max() );
	zombieVoices.SetNum( 0 );
	for( int i = 0; i < voices.Num(); i++ )
	{
		freeVoices[i] = &voices[i];
	}
// RB end
}
コード例 #23
0
HRESULT
CMyDevice::Initialize(
    _In_ IWDFDriver           * FxDriver,
    _In_ IWDFDeviceInitialize * FxDeviceInit
    )
/*++
 
  Routine Description:

    This method initializes the device callback object and creates the
    partner device object.

    The method should perform any device-specific configuration that:
        *  could fail (these can't be done in the constructor)
        *  must be done before the partner object is created -or-
        *  can be done after the partner object is created and which aren't 
           influenced by any device-level parameters the parent (the driver
           in this case) might set.

  Arguments:

    FxDeviceInit - the settings for this device.

  Return Value:

    status.

--*/
{
    IWDFDevice *fxDevice = NULL;

    HRESULT hr = S_OK;

    //
    // TODO: If you're writing a filter driver then indicate that here. 
    //
    // FxDeviceInit->SetFilter();
    //

    //
    // Set no locking unless you need an automatic callbacks synchronization
    //

    FxDeviceInit->SetLockingConstraint(None);

    //
    // TODO: Any per-device initialization which must be done before 
    //       creating the partner object.
    //


    //
    // Create a new FX device object and assign the new callback object to 
    // handle any device level events that occur.
    //

    //
    // QueryIUnknown references the IUnknown interface that it returns
    // (which is the same as referencing the device).  We pass that to 
    // CreateDevice, which takes its own reference if everything works.
    //

    if (SUCCEEDED(hr)) 
    {
        IUnknown *unknown = this->QueryIUnknown();

        hr = FxDriver->CreateDevice(FxDeviceInit, unknown, &fxDevice);

        unknown->Release();
    }

    //
    // If that succeeded then set our FxDevice member variable.
    //

    if (SUCCEEDED(hr)) 
    {
        m_FxDevice = fxDevice;

        //
        // Drop the reference we got from CreateDevice.  Since this object
        // is partnered with the framework object they have the same 
        // lifespan - there is no need for an additional reference.
        //

        fxDevice->Release();
    }

    return hr;
}
コード例 #24
0
ファイル: chxmedpltfm.cpp プロジェクト: muromec/qtopia-ezx
STDMETHODIMP
CHXMediaPlatform::Reset(IUnknown* pContext, HXBOOL bPlatformOnly)
{
    HX_RESULT                   rc = HXR_OK;
    IHXBuffer*                  pPrefKey = NULL;
    IHXPreferences2*            pPref2 = NULL;
    IHXPreferences3*            pPref3 = NULL;
    IHXPreferenceEnumerator*    pPrefEnumerator = NULL;
    IHXPluginEnumerator*        pPluginEnumerator = NULL;

    if (!bPlatformOnly && m_pPluginHandlerUnkown)
    {
        if (HXR_OK == m_pPluginHandlerUnkown->QueryInterface(IID_IHXPluginEnumerator,
                                                             (void**)&pPluginEnumerator))
        {
            UINT32      ulIndex = 0;
            UINT32      ulNumOfPlugins = pPluginEnumerator->GetNumOfPlugins();
            IUnknown*   pPlugin = NULL;
            IHXPlugin2* pPlugin2 = NULL;

            for(ulIndex = 0; ulIndex < ulNumOfPlugins; ulIndex++)
            {
                if (SUCCEEDED(pPluginEnumerator->GetPlugin(ulIndex, pPlugin)))
                {
                    if (SUCCEEDED(pPlugin->QueryInterface(IID_IHXPlugin2, (void**)&pPlugin2)))
                    {
                        pPlugin2->Reset();
                    }
                    HX_RELEASE(pPlugin2);
                }
                HX_RELEASE(pPlugin);
            }
        }
        HX_RELEASE(pPluginEnumerator);   
    }

    // We reset the m_pPreferences if it's already initialized via Init()
    //
    // On the other hand, Reset() can be called without Init(), this can
    // happen when the app simply wants to reset the media platform
    // during its un-installation
    if (!m_pPreferences)
    {       
        if (!m_pExtContext ||
            HXR_OK != m_pExtContext->QueryInterface(IID_IHXPreferences, (void**)&m_pPreferences))
        {
            InitDefaultPreferences();
        }
    }

    // remove all the entries within m_pPreferences
    if (m_pPreferences &&
        HXR_OK == m_pPreferences->QueryInterface(IID_IHXPreferences2, (void**)&pPref2) &&
        HXR_OK == m_pPreferences->QueryInterface(IID_IHXPreferences3, (void**)&pPref3) &&
        HXR_OK == pPref2->GetPreferenceEnumerator(pPrefEnumerator))
    {
        while (HXR_OK == pPrefEnumerator->GetPrefKey(0, pPrefKey))
        {
            pPref3->DeletePref((const char*)pPrefKey->GetBuffer());
            HX_RELEASE(pPrefKey);
        }
        HX_RELEASE(pPrefEnumerator);
        HX_RELEASE(pPref3);
        HX_RELEASE(pPref2);
    }

    Close();

    return HXR_OK;
}
コード例 #25
0
/////////////////////
//
//  IMediaObjectInPlace::Clone
//
//  The Clone method creates a copy of the DMO in its current state.
//
//  Parameters
//
//      ppMediaObject
//          [out] Address of a pointer to receive the new DMO's
//          IMediaObjectInPlace interface.
//
//  Return Value
//      Returns S_OK if successful. Otherwise, returns an HRESULT value
//      indicating the cause of the error.
//
//  If the method succeeds, the IMediaObjectInPlace interface that it returns
//  has an outstanding reference count. Be sure to release the interface when
//  you are finished using it.
//
HRESULT CHXAudioDeviceHookBase::Clone(IMediaObjectInPlace **ppMediaObject)
{
    // Check the input pointer
    if (!ppMediaObject)
    {
        return E_POINTER;
    }

    // This will be cleaned up when client releases the newly created object
    // or if there's some error along the way
    CHXAudioDeviceHookBase * pNewHXAudioDeviceHook = new CComObject<CHXAudioDeviceHookBase>;
    if( !pNewHXAudioDeviceHook )
    {
        return E_OUTOFMEMORY;
    }

    HRESULT hr = S_OK;

    hr = pNewHXAudioDeviceHook->UpdateStatesInternal();

    IMediaObject * pCloned = NULL;
    if( SUCCEEDED( hr ) )
    {
        IUnknown *pUnk;
        hr = pNewHXAudioDeviceHook->QueryInterface( IID_IUnknown, (void **) &pUnk );
        if( SUCCEEDED( hr ) )
        {
            hr = pUnk->QueryInterface( IID_IMediaObject, (void **) &pCloned );
            HX_RELEASE(pUnk);
        }
    }


    // Copy the input and output types
    if (SUCCEEDED(hr))
    {
        DMO_MEDIA_TYPE mt;
        DWORD cInputStreams = 0;
        DWORD cOutputStreams = 0;
        GetStreamCount(&cInputStreams, &cOutputStreams);

        for (DWORD i = 0; i < cInputStreams && SUCCEEDED(hr); ++i)
        {
            hr = GetInputCurrentType(i, &mt);
            if (hr == DMO_E_TYPE_NOT_SET)
            {
                hr = S_OK; // great, don't need to set the cloned DMO
            }
            else if (SUCCEEDED(hr))
            {
                hr = pCloned->SetInputType(i, &mt, 0);
                MoFreeMediaType( &mt );
            }
        }

        for (DWORD i = 0; i < cOutputStreams && SUCCEEDED(hr); ++i)
        {
            hr = GetOutputCurrentType(i, &mt);
            if (hr == DMO_E_TYPE_NOT_SET)
            {
                hr = S_OK; // great, don't need to set the cloned DMO
            }
            else if (SUCCEEDED(hr))
            {
                hr = pCloned->SetOutputType(i, &mt, 0);
                MoFreeMediaType( &mt );
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = pCloned->QueryInterface(IID_IMediaObjectInPlace, (void**)ppMediaObject);
        }

        // Release the object's original ref.  If clone succeeded (made it through QI) then returned pointer
        // has one ref.  If we failed, refs drop to zero, freeing the object.
        HX_RELEASE(pCloned);
    }

    // Something went wrong, clean up for client
    if (FAILED(hr))
    {
        delete pNewHXAudioDeviceHook;
    }

    return hr;
}
コード例 #26
0
ファイル: Gargle.cpp プロジェクト: grakidov/Render3D
//////////////////////////////////////////////////////////////////////////////
//
// CGargle::Clone
//
HRESULT CGargle::Clone(IMediaObjectInPlace **ppCloned) 
{
    if (!ppCloned)
        return E_POINTER;

    HRESULT hr = S_OK;
    CGargle * pNewGargle = new CComObject<CGargle>;
    if( !pNewGargle )
        hr = E_OUTOFMEMORY;

    hr = pNewGargle->Init();

    IMediaObject * pCloned = NULL;
    if( SUCCEEDED( hr ) )
    {
        IUnknown *pUnk;
        hr = pNewGargle->QueryInterface( IID_IUnknown, (void **) &pUnk );
        if( SUCCEEDED( hr ) )
        {
            hr = pUnk->QueryInterface( IID_IMediaObject, (void **) &pCloned );
            pUnk->Release();
        }
    }
    else
    {
        return hr;
    }

    //
    // Copy parameter control information
    //
    if (SUCCEEDED(hr))
        hr = pNewGargle->CopyParamsFromSource((CParamsManager *) this);

    // Copy current parameter values
    GargleFX params;
    if (SUCCEEDED(hr))
        hr = GetAllParameters(&params);

    if (SUCCEEDED(hr))
        hr = pNewGargle->SetAllParameters(&params);

    if (SUCCEEDED(hr))
    {
        // Copy the input and output types
        DMO_MEDIA_TYPE mt;
        DWORD cInputStreams = 0;
        DWORD cOutputStreams = 0;
        GetStreamCount(&cInputStreams, &cOutputStreams);

        for (DWORD i = 0; i < cInputStreams && SUCCEEDED(hr); ++i)
        {
            hr = GetInputCurrentType(i, &mt);
            if (hr == DMO_E_TYPE_NOT_SET)
            {
                hr = S_OK; // great, don't need to set the cloned DMO
            }
            else if (SUCCEEDED(hr))
            {
                hr = pCloned->SetInputType(i, &mt, 0);
                MoFreeMediaType( &mt );
            }
        }

        for (i = 0; i < cOutputStreams && SUCCEEDED(hr); ++i)
        {
            hr = GetOutputCurrentType(i, &mt);
            if (hr == DMO_E_TYPE_NOT_SET)
            {
                hr = S_OK; // great, don't need to set the cloned DMO
            }
            else if (SUCCEEDED(hr))
            {
                hr = pCloned->SetOutputType(i, &mt, 0);
                MoFreeMediaType( &mt );
            }
        }

        if (SUCCEEDED(hr))
            hr = pCloned->QueryInterface(IID_IMediaObjectInPlace, (void**)ppCloned);

        // Release the object's original ref.  If clone succeeded (made it through QI) then returned pointer
        // has one ref.  If we failed, refs drop to zero, freeing the object.
        pCloned->Release();
    }
    return hr;
}
コード例 #27
0
ファイル: CommonAppUtils.cpp プロジェクト: ch3cooli/TSVNUtils
HRESULT CCommonAppUtils::EnableAutoComplete(HWND hWndEdit, LPWSTR szCurrentWorkingDirectory, AUTOCOMPLETELISTOPTIONS acloOptions, AUTOCOMPLETEOPTIONS acoOptions, REFCLSID clsid)
{
    IAutoComplete *pac;
    HRESULT hr = CoCreateInstance(CLSID_AutoComplete,
                                  NULL,
                                  CLSCTX_INPROC_SERVER,
                                  IID_PPV_ARGS(&pac));
    if (FAILED(hr))
    {
        return hr;
    }

    IUnknown *punkSource;
    hr = CoCreateInstance(clsid,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_PPV_ARGS(&punkSource));
    if (FAILED(hr))
    {
        pac->Release();
        return hr;
    }

    if ((acloOptions != ACLO_NONE) || (szCurrentWorkingDirectory != NULL))
    {
        IACList2 *pal2;
        hr = punkSource->QueryInterface(IID_PPV_ARGS(&pal2));
        if (SUCCEEDED(hr))
        {
            if (acloOptions != ACLO_NONE)
            {
                hr = pal2->SetOptions(acloOptions);
            }

            if (szCurrentWorkingDirectory != NULL)
            {
                ICurrentWorkingDirectory *pcwd;
                hr = pal2->QueryInterface(IID_PPV_ARGS(&pcwd));
                if (SUCCEEDED(hr))
                {
                    hr = pcwd->SetDirectory(szCurrentWorkingDirectory);
                    pcwd->Release();
                }
            }

            pal2->Release();
        }
    }

    hr = pac->Init(hWndEdit, punkSource, NULL, NULL);

    if (acoOptions != ACO_NONE)
    {
        IAutoComplete2 *pac2;
        hr = pac->QueryInterface(IID_PPV_ARGS(&pac2));
        if (SUCCEEDED(hr))
        {
            hr = pac2->SetOptions(acoOptions);
            pac2->Release();
        }
    }

    punkSource->Release();
    pac->Release();
    return hr;
}
コード例 #28
0
void CXunJianDlg::OnOK() 
{
	try{
	pList= (CListBox *)GetDlgItem(IDC_HOSTLIST);
	/*if( pList->GetTextLen(0)>15 || pList->GetTextLen(0)<7 )
	{
		MessageBox("主机列表文件未加载,请重新选择!");
		return;
	}*/

	_GUID clsid;
	IUnknown *pUnk;
	IDispatch *pDisp;
	LPDISPATCH lpDisp;

	_Application app;
	Workbooks xj_books;
	_Workbook xj_book;
	Worksheets xj_sheets;
	_Worksheet xj_sheet;
	Range range;
	Range unionRange;
	Range cols;

	Font font;
//	COleVariant background;

	COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);

	::CLSIDFromProgID(L"Excel.Application",&clsid); // from registry
	if(GetActiveObject(clsid, NULL,&pUnk) == S_OK)
	{
		VERIFY(pUnk->QueryInterface(IID_IDispatch,(void**) &pDisp) == S_OK);
		app.AttachDispatch(pDisp);
		pUnk->Release();
	} 
	else
	{  
		if(!app.CreateDispatch("Excel.Application"))
		{
			MessageBox("Excel program not found");     
			app.Quit();     
			return;
		}
	}

	xj_books=app.GetWorkbooks();
	xj_book=   xj_books.Add(covOptional);
	xj_sheets= xj_book.GetSheets();
	xj_sheet=  xj_sheets.GetItem(COleVariant((short)1));

	int i;
	Range item;
	range=xj_sheet.GetRange(COleVariant("A1"),COleVariant("F1"));
	for(i= 0; i < 6; i++)
	{
		item.AttachDispatch(range.GetItem(COleVariant((long)1),COleVariant((long)i+1)).pdispVal);
		item.SetValue2(COleVariant(PROJ[i]));
	}  //描绘第一行目录

	//range=xj_sheet.GetRange(COleVariant("A1"),COleVariant("F1"));
	lpDisp=range.GetInterior();
	Interior   cellinterior;
	cellinterior.AttachDispatch(lpDisp);
	cellinterior.SetColor(COleVariant((long)0xc0c0c0));  //设置背景色为灰色
	cellinterior.ReleaseDispatch();
	//range=xj_sheet.GetRange(COleVariant("A1"),COleVariant("F1"));
	range.SetHorizontalAlignment(COleVariant((long)-4108)); //全部居中
	Borders bord;
	bord=range.GetBorders();
	bord.SetLineStyle(COleVariant((short)1));  //设置边框
	//range=xj_sheet.GetRange(COleVariant("A1"),COleVariant("F1"));
	cols=range.GetEntireColumn();
	cols.AutoFit();  //自动调整

/**************************表格初始绘画完成************************************/

	long usedRowNum; //行计数
	CString handleFile;
	CString hostFileName,hostip;
	bool error = false;
	CString infos,info;
	ExcelFile excelFile;
	ReadTxt xj_txt;
	xj_HostCount=pList->GetCount();
	for(int n_host=0;n_host<xj_HostCount;n_host++)  //主循环,一个文件一次循环。
	{		
		pList->GetText(n_host,hostFileName);
		hostip = hostFileName;
		handleFile = hostFileName + _T(" 正在处理...");
		pList->DeleteString(n_host);
		pList->InsertString(n_host,handleFile);
		pList->SetCurSel(n_host);
		pList->UpdateWindow();

		hostFileName = xj_FilePath + hostFileName;
		hostFileName += _T(".txt");
		CStdioFile hostFile;
		if(!hostFile.Open(hostFileName,CFile::modeRead,0))
		{  //记录不存在文件名
			handleFile.Replace("正在处理...","失败!");
			error = true;
			pList->DeleteString(n_host);
			pList->InsertString(n_host,handleFile);
			pList->UpdateWindow();
			continue;
		}
		usedRowNum = excelFile.GetRowCount(xj_sheet);
		range.AttachDispatch(xj_sheet.GetCells());

		//info.Format( _T("%d"), n_host+1);
		info = xj_txt.ReadHostName(&hostFile,COMMAND[0],COMMAND[1]);  //获取节点名称
		range.SetItem(COleVariant(usedRowNum+1),COleVariant(long(1)),COleVariant(info));

		int portCount = 0;   //端口数目,不包括7/1
		CString nSend, nRecv;
		float n_Send,n_Recv;

		while(hostFile.ReadString(info))
			if(info.Find( COMMAND[4]) > -1) break;
		while( hostFile.ReadString(info) && info.Find( "[local]" ) == -1 )  //端口号和流量
		{
			if( info.Find( "/" ) == -1 || info.Find( "7/1" ) > -1 ) continue;

			info.Replace( "ethernet","");
			info = _T("'") + info;
			infos = info;

			while( hostFile.ReadString(info) )
				if( info.Find( "send bit rate" ) > -1 ) break;
			nSend = info.Mid( 60 );
			hostFile.ReadString(info);
			nRecv = info.Mid( 60 );
			nSend.Trim();
			nRecv.Trim();
			n_Send = (float)atof(nSend);
			n_Recv = (float)atof(nRecv);

			if( n_Send < 1000 && n_Recv < 1000 ) continue;
			portCount++;
			range.SetItem(COleVariant(usedRowNum+portCount),COleVariant(long(2)),COleVariant(infos.Trim()));
			range.SetItem(COleVariant(usedRowNum+portCount),COleVariant(long(4)),COleVariant((n_Send>n_Recv)?nSend:nRecv));
		}

		hostFile.SeekToBegin();
		infos = xj_txt.ReadLine(&hostFile,"ubscriber Address");  //历史在线最大用户数
		if( infos == _T("") ) info = _T("0");
		else
		{
			int token = 0;
			for(i = 0; i < 5 ; i++) info = infos.Tokenize(" ",token);
		}
		range.SetItem(COleVariant(usedRowNum+1),COleVariant(long(6)),COleVariant(info.Trim()));  

		hostFile.Close();

		if(portCount > 1)
		{
			unionRange.AttachDispatch(range.GetItem(COleVariant(usedRowNum+1),COleVariant((long)1)).pdispVal);
			unionRange.AttachDispatch(unionRange.GetResize(COleVariant((long)portCount),COleVariant((long)1)));
			unionRange.Merge(COleVariant((long)0));  //节点名称单元格合并

			unionRange.AttachDispatch(range.GetItem(COleVariant(usedRowNum+1),COleVariant((long)6)).pdispVal);
			unionRange.AttachDispatch(unionRange.GetResize(COleVariant((long)portCount),COleVariant((long)1)));
			unionRange.Merge(COleVariant((long)0)); 			
			//历史最大用户数合并
		}

		unionRange.AttachDispatch(range.GetItem(COleVariant(usedRowNum+1),COleVariant((long)1)).pdispVal);
		unionRange.AttachDispatch(unionRange.GetResize(COleVariant((long)portCount),COleVariant((long)6)));
		unionRange.SetRowHeight(COleVariant(13.5));
		bord = unionRange.GetBorders();
		bord.SetLineStyle(COleVariant((short)1));  //设置边框



		handleFile.Replace("正在处理...","已完成");
		pList->DeleteString(n_host);
		pList->InsertString(n_host,handleFile);
		pList->UpdateWindow();
	}

	CTime time;
	time = time.GetCurrentTime();
	infos = time.Format("%Y%m%d%H%M%S");  //time.Format();
	info = _T("巡检报表") + infos + _T(".xlsx");
	info = xj_FilePath + info;
	info.Replace("\\\\","\\");

	xj_book.SaveAs(COleVariant(info),covOptional,covOptional,covOptional,covOptional,covOptional,0,covOptional,covOptional,covOptional,covOptional,covOptional);
	
	if(error == true )
	{
		MessageBox("巡检报表已完成,已保存到\r\n" + info + "\r\n有文件打开错误,点击\"确定\"返回查看","有文件打开错误!",MB_OK|MB_ICONWARNING);
		app.Quit();
	}
	else 
	{
		if(MessageBox("巡检报表已完成,已保存到\r\n" + info + "\r\n点击\"确定\"打开文件查看","生成报表完成",MB_OKCANCEL) == IDOK)
		{
			app.SetVisible(TRUE);
			app.SetUserControl(TRUE);
		}
		else app.Quit();
	}
}
catch (CFileException* e)
    {
        e->ReportError();
        e->Delete();
    }
	//CDialog::OnOK();
}
コード例 #29
0
//
//  ActivateCompleted()
//
//  Callback implementation of ActivateAudioInterfaceAsync function.  This will be called on MTA thread
//  when results of the activation are available.
//
HRESULT WASAPIRenderer::ActivateCompleted( IActivateAudioInterfaceAsyncOperation *operation )
{
    HRESULT hr = S_OK;
    HRESULT hrActivateResult = S_OK;
    IUnknown *punkAudioInterface = nullptr;

    if (m_DeviceStateChanged->GetState() != DeviceStateUnInitialized)
    {
        hr = E_NOT_VALID_STATE;
        goto exit;
    }

    // Check for a successful activation result
    hr = operation->GetActivateResult( &hrActivateResult, &punkAudioInterface );
    if (SUCCEEDED( hr ) && SUCCEEDED( hrActivateResult ))
    {
        m_DeviceStateChanged->SetState( DeviceStateActivated, S_OK, false );

        // Get the pointer for the Audio Client
        punkAudioInterface->QueryInterface( IID_PPV_ARGS(&m_AudioClient) );
        if( nullptr == m_AudioClient )
        {
            hr = E_FAIL;
            goto exit;
        }

        // Configure user defined properties
        hr = ConfigureDeviceInternal();
        if (FAILED( hr ))
        {
            goto exit;
        }

        // Initialize the AudioClient in Shared Mode with the user specified buffer
        hr = m_AudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
                                        AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_NOPERSIST,
                                        m_DeviceProps.hnsBufferDuration,
                                        m_DeviceProps.hnsBufferDuration,
                                        m_MixFormat,
                                        nullptr );
        if (FAILED( hr ))
        {
            goto exit;
        }

        // Get the maximum size of the AudioClient Buffer
        hr = m_AudioClient->GetBufferSize( &m_BufferFrames );
        if (FAILED( hr ))
        {
            goto exit;
        }

        // Get the render client
        hr = m_AudioClient->GetService( __uuidof(IAudioRenderClient), (void**) &m_AudioRenderClient );
        if (FAILED( hr ))
        {
            goto exit;
        }

        // Create Async callback for sample events
        hr = MFCreateAsyncResult( nullptr, &m_xSampleReady, nullptr, &m_SampleReadyAsyncResult );
        if (FAILED( hr ))
        {
            goto exit;
        }

        // Sets the event handle that the system signals when an audio buffer is ready to be processed by the client
        hr = m_AudioClient->SetEventHandle( m_SampleReadyEvent );
        if (FAILED( hr ))
        {
            goto exit;
        }

        // Everything succeeded
        m_DeviceStateChanged->SetState( DeviceStateInitialized, S_OK, true );

    }

exit:
    SAFE_RELEASE( punkAudioInterface );

    if (FAILED( hr ))
    {
        m_DeviceStateChanged->SetState( DeviceStateInError, hr, true );
        SAFE_RELEASE( m_AudioClient );
        SAFE_RELEASE( m_AudioRenderClient );
        SAFE_RELEASE( m_SampleReadyAsyncResult );
    }

	SetEvent(m_EventHandle);
    
    // Need to return S_OK
    return S_OK;
}
コード例 #30
0
ファイル: CEnumAAFLoadedPlugins.cpp プロジェクト: UIKit0/aaf
HRESULT STDMETHODCALLTYPE
    CEnumAAFLoadedPlugins::Clone (IEnumAAFLoadedPlugins ** ppEnum)
{
  HRESULT hr;

  ImplEnumAAFLoadedPlugins * ptr;
  ImplAAFRoot * pO;
  pO = GetRepObject ();
  assert (pO);
  ptr = static_cast<ImplEnumAAFLoadedPlugins*> (pO);
  assert (ptr);

  //
  // set up for ppEnum
  //
  ImplEnumAAFLoadedPlugins * internalppEnum = NULL;
  ImplEnumAAFLoadedPlugins ** pinternalppEnum = NULL;
  if (ppEnum)
    {
      pinternalppEnum = &internalppEnum;
    }

  try
    {
      hr = ptr->Clone
       (pinternalppEnum);
    }
  catch (OMException& e)
    {
      // OMExceptions should be handled by the impl code. However, if an
      // unhandled OMException occurs, control reaches here. We must not
      // allow the unhandled exception to reach the client code, so we
      // turn it into a failure status code.
      //
      // If the OMException contains an HRESULT, it is returned to the
      // client, if not, AAFRESULT_UHANDLED_EXCEPTION is returned.
      //
      hr = OMExceptionToResult(e, AAFRESULT_UNHANDLED_EXCEPTION);
    }
  catch (OMAssertionViolation &)
    {
      // Control reaches here if there is a programming error in the
      // impl code that was detected by an assertion violation.
      // We must not allow the assertion to reach the client code so
      // here we turn it into a failure status code.
      //
      hr = AAFRESULT_ASSERTION_VIOLATION;
    }
  catch (...)
    {
      // We CANNOT throw an exception out of a COM interface method!
      // Return a reasonable exception code.
      //
      hr = AAFRESULT_UNEXPECTED_EXCEPTION;
    }

  //
  // cleanup for ppEnum
  //
  if (SUCCEEDED(hr))
    {
      IUnknown *pUnknown;
      HRESULT hStat;

      if (internalppEnum)
        {
          pUnknown = static_cast<IUnknown *> (internalppEnum->GetContainer());
          hStat = pUnknown->QueryInterface(IID_IEnumAAFLoadedPlugins, (void **)ppEnum);
          assert (SUCCEEDED (hStat));
          //pUnknown->Release();
          internalppEnum->ReleaseReference(); // We are through with this pointer.
        }
    }
  return hr;
}