Esempio n. 1
0
// Basics
Audio::Audio(void)
{
	logger.addline("Trying to find analong input devices.", debug);
	HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
	if (SUCCEEDED(hr))
	{
		IEnumMoniker *pEnum;
		logger.addline("Analong input device(s) has been detected.", info);

		hr = EnumerateDevices(CLSID_VideoInputDeviceCategory, &pEnum);
		if (SUCCEEDED(hr))
		{
			logger.addline("Have found one or more video input devices", success);
			LogDeviceInformation(pEnum);
			pEnum->Release();
		}
		else { logger.addline("No video input device(s) have been detected.", info); }
		hr = EnumerateDevices(CLSID_AudioInputDeviceCategory, &pEnum);
		logger.addline("Finding out all audio input devices", debug);
		if (SUCCEEDED(hr))
		{
			LogDeviceInformation(pEnum);
			pEnum->Release();
		}
		else { logger.addline("No audio input device(s) have been detected.", info); }
		CoUninitialize();
	}
	else{ logger.addline("Have found no analong input devices", debug); }
	logger.addline("All devices as of the start of the program have been detected.", info);
}
Esempio n. 2
0
HRESULT OpenInterface(HWND hwnd, HINSTANCE hinst)
{
    char *videodriver[MAX_DEVICES];
    int  vcount=MAX_DEVICES;
    int  vsel=-1;

    HRESULT hr=NOERROR;
    lstrcpy(gszCaptureFilterName,"DBOXII Capture");
    

	hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void **)&gpIGraphBuilder);
	if (SUCCEEDED(hr)&&(gpIGraphBuilder!=NULL))
    	hr = CoCreateInstance(CLSID_CaptureGraphBuilder, NULL, CLSCTX_INPROC_SERVER, IID_ICaptureGraphBuilder, (void **)&gpICaptureGraphBuilder);
    if (SUCCEEDED(hr)&&(gpICaptureGraphBuilder!=NULL))
        hr=gpICaptureGraphBuilder->SetFiltergraph(gpIGraphBuilder);


    if (SUCCEEDED(hr))
        {
        int  i=0;
        for(i=0;i<MAX_DEVICES;i++)
	        videodriver[i]=(char *)malloc(264);

        hr =EnumerateDevices(videodriver, &vcount, gpIGraphBuilder, gpICaptureGraphBuilder, -1, NULL, TRUE);   
        for(i=0;i<=vcount;i++)
            {
            if (!lstrcmp(videodriver[i],gszCaptureFilterName))
                {
                vsel=i;
                break;
                }
            }
        if (vsel>=0)
            {
            hr =EnumerateDevices(videodriver, &vcount, gpIGraphBuilder, gpICaptureGraphBuilder, vsel, &gpVCap, TRUE);   
            if (SUCCEEDED(hr))
                hr=AddCaptureFilterToGraph(gpIGraphBuilder, gpVCap, gszCaptureFilterName);
            }

        else
            hr=E_FAIL;
        
        for(i=0;i<MAX_DEVICES;i++)
	        free(videodriver[i]);
        }

    return(hr);
}
Esempio n. 3
0
void MyFrame::OnChangeDevice(wxCommandEvent &event)
{
    int devicenumber = event.GetId() - ID_DEVICE0;

    int win_id = event.GetId();

    switch (win_id)
    {
        case ID_DEVICE_ENUMERATE :
        {
            EnumerateDevices();
            break;
        }
        case ID_DEVICENONE :
        {
            m_vidCapWin->DeviceDisconnect();
            m_videoMenu->Check(ID_DEVICENONE, true);
            break;
        }
        default :
        {
            m_vidCapWin->DeviceConnect(devicenumber);
            break;
        }
    }

    SetupVideoMenus();
}
Esempio n. 4
0
BOOL CLCDOutput::HasHardwareChanged(void)
{
    if(LGLCD_INVALID_DEVICE != m_hDevice)
    {
        // ping to see whether we're still alive
        DWORD dwButtonState = 0;
        
        DWORD res = lgLcdReadSoftButtons(m_hDevice, &dwButtonState);

        HandleErrorFromAPI(res);
    }

    // check for lcd devices
    if (LGLCD_INVALID_DEVICE == m_hDevice)
    {
        EnumerateDevices();
    }
    else
    {
        // we still have our device;
        return FALSE;
    }

    // we got a new device
    return LGLCD_INVALID_DEVICE != m_hDevice;
}
Esempio n. 5
0
GlobalState::GlobalState()
{
    pManager = *DeviceManager::Create();
    // Handle the DeviceManager's messages
    pManager->AddMessageHandler( this );
    EnumerateDevices();

    // PhoneSensors::Init();
}
Esempio n. 6
0
IBaseFilter*	Video::QueryMediaSourceDevice( int _DeviceIndex )
{
	__QueryDeviceStruct	Params;
	Params.DeviceIndex = _DeviceIndex;
	Params.pSourceDevice = NULL;
	EnumerateDevices( QueryDeviceEnumerator, &Params );
	ASSERT( Params.pSourceDevice != NULL, "Failed to query the proper source device!" );
	return Params.pSourceDevice;
}
Esempio n. 7
0
void CLCDOutput::Update(DWORD dwTimestamp)
{
    if (m_pActiveScreen)
    {
        m_pActiveScreen->Update(dwTimestamp);
    }

    // check for expiration
    if (m_pActiveScreen && m_pActiveScreen->HasExpired())
    {
        m_pActiveScreen = NULL;
        //m_nPriority = LGLCD_PRIORITY_FYI; -> needs to go so that if a 
		// program sets priority to LGLCD_PRIORITY_BACKGROUND, that 
		// priority sticks.

        OnScreenExpired(m_pActiveScreen);

        // Clear the bitmap
        ClearBitmap(m_pLastBitmap);

        // find the next active screen
        LCD_MGR_LIST::iterator it = m_LCDMgrList.begin();
        while(it != m_LCDMgrList.end())
        {
            CLCDManager *pMgr = *it;
            LCDUIASSERT(NULL != pMgr);

            if (!pMgr->HasExpired())
            {
                ActivateScreen(pMgr);
                //m_nPriority = LGLCD_PRIORITY_FYI;  -> needs to go so that if a 
				// program sets priority to LGLCD_PRIORITY_BACKGROUND, that 
				// priority sticks.
                break;
            }

            ++it;
        }

        // if no screen found, empty the screen at idle priority
        if (NULL == m_pActiveScreen)
        {
            if (LGLCD_INVALID_DEVICE != m_hDevice)
            {
                lgLcdUpdateBitmap(m_hDevice, &CLCDManager::GetLCDScreen()->hdr,
                    LGLCD_ASYNC_UPDATE(LGLCD_PRIORITY_IDLE_NO_SHOW));
            }
        }
    }

    // check for lcd devices
    if (LGLCD_INVALID_DEVICE == m_hDevice)
    {
        EnumerateDevices();
    }
}
Esempio n. 8
0
int _tmain(int argc, _TCHAR* argv[])
{
	TestWlanApi( argc, argv );

	HANDLE DeviceHandle = OpenHandle(pNdisProtDevice);

	if( DeviceHandle == INVALID_HANDLE_VALUE )
	{
		_tprintf((_T("Failed to open %s\n"), pNdisProtDevice));
		return -1;
	}

	wstring strDeviceName[256][2];
	int nCount = EnumerateDevices( DeviceHandle, strDeviceName );
	if( nCount == 0 )
	{
		puts( "no device bind." );
		return -1;
	}

	for( int i = 0; i < nCount; ++i )
	{
		printf( "%2d.%S\n	%S\n\n", i, strDeviceName[i][0].c_str(), strDeviceName[i][1].c_str() );
	}
	TCHAR szBuffer[256];
	DWORD dwRead = 0;
	//if( ReadConsole( GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL ) == FALSE )
	//{
	//	puts( "error input" );
	//	return -1;
	//}
	//szBuffer[dwRead] = 0;
	//int nChoice = _ttoi( szBuffer );

	int nChoice = 0;
	if( nChoice > nCount )
	{
		puts( "error input." );
		return -1;
	}

	InitializeDevice( DeviceHandle, strDeviceName[nChoice][0].c_str(), strDeviceName[nChoice][0].length()*sizeof(WCHAR) );

	for( int i = 0; i < 3; ++i )
	{
		if( ReadFile( DeviceHandle, szBuffer, sizeof(szBuffer), &dwRead, NULL ) )
		{

		}
	}
	TerminateDevice( DeviceHandle );
}
void CLCDOutput::Update(DWORD dwTimestamp)
{
    if (m_pActiveScreen)
    {
        m_pActiveScreen->Update(dwTimestamp);
    }

    // check for expiration
    if (m_pActiveScreen && m_pActiveScreen->HasExpired(dwTimestamp))
    {
        m_pActiveScreen = NULL;
        //m_nPriority = LGLCD_PRIORITY_FYI; -> needs to go so that if a 
		// program sets priority to LGLCD_PRIORITY_BACKGROUND, that 
		// priority sticks.

        OnScreenExpired(m_pActiveScreen);

        // find the next active screen
        LCD_MGR_LIST::iterator it = m_LCDMgrList.begin();
        while(it != m_LCDMgrList.end())
        {
            CLCDManager *pMgr = *it;
            LOGIASSERT(NULL != pMgr);

            if (!pMgr->HasExpired(dwTimestamp))
            {
                ActivateScreen(pMgr);
                //m_nPriority = LGLCD_PRIORITY_FYI;  -> needs to go so that if a 
				// program sets priority to LGLCD_PRIORITY_BACKGROUND, that 
				// priority sticks.
                break;
            }

            ++it;
        }
    }

    // check for lcd devices
    if (LGLCD_INVALID_DEVICE == m_hDevice)
    {
        EnumerateDevices();
    }
}
Esempio n. 10
0
//-----------------------------------------------------------------------------
// Name : EnumerateAdapters () (Private)
// Desc : Enumerates the individual adapters contained within the user machine.
//-----------------------------------------------------------------------------
HRESULT CD3DInitialize::EnumerateAdapters()
{
    HRESULT hRet;

    // Store the number of available adapters
    ULONG nAdapterCount = m_pD3D->GetAdapterCount();

    // Loop through each adapter
    for ( ULONG i = 0; i < nAdapterCount; i++ )
    {
        CD3DEnumAdapter * pAdapter = new CD3DEnumAdapter;
        if ( !pAdapter ) return E_OUTOFMEMORY;

        // Store adapter ordinal
        pAdapter->Ordinal = i;

        // Retrieve adapter identifier
        m_pD3D->GetAdapterIdentifier( i, 0, &pAdapter->Identifier );

        // Enumerate all display modes for this adapter
        if ( FAILED( hRet = EnumerateDisplayModes( pAdapter ) ) ||
             FAILED( hRet = EnumerateDevices( pAdapter ) )) 
        {
            delete pAdapter;
            if ( hRet == E_ABORT ) continue; else return hRet;
        
        } // End if Failed Code

        // Add this adapter the list
        try { m_vpAdapters.push_back( pAdapter ); } catch ( ... )
        {
            delete pAdapter;
            return E_OUTOFMEMORY;

        } // End Try / Catch Block

    } // Next Adapter

    // Success!
    return S_OK;

}
Esempio n. 11
0
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpszCmdParam, int nCmdShow)
{
	// 温度計・湿度計デバイスの初期化
	if(!usbmeter::LoadUSBMeterDLL()){
		return -1;
	}
	std::vector<boost::shared_ptr<OLECHAR> > devices;
	EnumerateDevices(&devices);
	if(devices.empty()){
		MessageBox(NULL, _T("No USB meter device found."), _T("Error"), MB_OK);
		return -1;
	}

	// WinSockの初期化
	WSADATA wsaData;
	if(WSAStartup(MAKEWORD(2,0), &wsaData) != 0){
		MessageBox(NULL, _T("WSAStartup failed."), _T("Error"), MB_OK);
		return -1;
	}

	// メインダイアログ作成
	MainDialogBox dlg(hInst, devices);
	HWND hWnd = dlg.Create();
	if(!hWnd){
		return -1;
	}
	
	// メッセージループ
	MSG msg;
	while(GetMessage(&msg, NULL, 0, 0) != 0){
		if(!IsDialogMessage(hWnd, &msg)){
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	// WinSockの解放
	WSACleanup();

	return (int)msg.wParam;
}
Esempio n. 12
0
/*
One and only Central thread - Killed by the destructor.
Loops forever with sleep_for(100) between iterations
Responds to requests to enumerate (DB initialization or System changed)
Responds to StartPolling requests (User selected OR post-enumeration)
Responds to StopPolling requests (User selected)
After each responce - Continue & Wait.
*/
void CvJoyMonitor::CentralThread()
{
    THREAD_NAME("CvJoyMonitor Central thread (Loop)");

    while (m_CentralKeepalive)
    {
        Sleep_For(100); // MilliSec

        // Need enumeration? - If enumeration counter is positive then yes
        // Kill all polling threads then start enumerating then decrement counter
		if (m_EnumerateCounter > 0)
		{
             EnumerateDevices();  // This decrements  m_EnumerateCounter
			 if (!m_EnumerateCounter)
				 SendMessageTimeout(m_ParentWnd, WMSPP_JMON_STRT, 0, 0, SMTO_ABORTIFHUNG, 1000, 0);
		}

        else
        {
            // Need to kill polling threads? - if m_quSuspend is not empty then yes
            lock_guard<recursive_mutex> lock_ctSuspend(m_mx_ctSuspend);
            if (!m_ctSuspend.empty())
            {
                SuspendPolling(*(m_ctSuspend.begin()));
                continue;
                //lock_ctSuspend;
            };

            // Need to create polling threads? - if m_mx_quPoll is not empty then yes
            lock_guard<recursive_mutex> lock_ctPoll(m_mx_ctPoll);
            if (!m_ctPoll.empty())
            {
                PollDevice(*(m_ctPoll.begin()));
                continue;
            };
        }
    }; // While

}
Esempio n. 13
0
// Code from http://msdn.microsoft.com/en-us/library/windows/desktop/dd377566(v=vs.85).aspx
void	Video::EnumerateDevices( EnumerateDelegate _pDeviceEnumerator, void* _pUserData )
{
	IEnumMoniker*	pEnumerator = NULL;
	ASSERT( SUCCEEDED( EnumerateDevices( CLSID_VideoInputDeviceCategory, &pEnumerator ) ), "Failed enumerating devices!" );

	VARIANT	varFriendlyName, varDevicePath;
	VariantInit( &varFriendlyName );
	VariantInit( &varDevicePath );

	int			DeviceIndex = 0;
	IMoniker*	pMoniker = NULL;
	while ( pEnumerator->Next( 1, &pMoniker, NULL ) == S_OK )
	{
		IPropertyBag*	pPropBag;
		HRESULT hr = pMoniker->BindToStorage( 0, 0, IID_PPV_ARGS( &pPropBag ) );
		if ( FAILED(hr) )
		{
			pMoniker->Release();
			continue;  
		} 

		// Get friendly name.
		hr = pPropBag->Read( L"FriendlyName", &varFriendlyName, 0 );
		if ( !SUCCEEDED(hr) )
			continue;

		hr = pPropBag->Read( L"DevicePath", &varDevicePath, 0 );
		if ( !SUCCEEDED(hr) )
			continue;

		// Notify delegate
		(*_pDeviceEnumerator)( DeviceIndex++, varFriendlyName.bstrVal, varDevicePath.bstrVal, pMoniker, _pUserData );

		pPropBag->Release();
		pMoniker->Release();
	}

	pEnumerator->Release();
}
BOOL CUsbtestDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时,框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO:  在此添加额外的初始化代码

    int devCount = 1;

    if (DEVCTRL_SUCCESS != EnumerateDevices(&devID, &devCount))
    {
        AfxMessageBox(_T("打开USB Slave失败,程序即将关闭!"));
        exit(-1);
    }

    waveSize = 8000;
    waveCount = 100;
    SetWaveParam(devID, waveSize, 1);    

    SendCommand(devID, CMD_SET_TEST, 1);
    SendCommand(devID, CMD_SET_TRIGWAVE_DELAY, 100);

    for (int i = 0; i < 10; i++)
    {
        unsigned char* buf = new unsigned char[waveSize*waveCount];
        AddBuffer(devID, buf, waveSize*waveCount);
    }

    HANDLE h = CreateThread(NULL, 0, ::WaitWaveProc, this, 0, &dwThreadID);

    StartDevice(devID);

	return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE
}
Esempio n. 15
0
//--------------------------------------------------------------------------------------
// Enumerates available D3D adapters, devices, modes, etc.
//--------------------------------------------------------------------------------------
HRESULT CD3DEnumeration::Enumerate( IDirect3D9* pD3D,
                                    LPDXUTCALLBACKISDEVICEACCEPTABLE IsDeviceAcceptableFunc,
                                    void* pIsDeviceAcceptableFuncUserContext )
{
    if( pD3D == NULL )
    {
        pD3D = DXUTGetD3DObject();
        if( pD3D == NULL )
            return DXUTERR_NODIRECT3D;
    }

    m_pD3D = pD3D;
    m_IsDeviceAcceptableFunc = IsDeviceAcceptableFunc;
    m_pIsDeviceAcceptableFuncUserContext = pIsDeviceAcceptableFuncUserContext;

    HRESULT hr;
    ClearAdapterInfoList();
    CGrowableArray<D3DFORMAT> adapterFormatList;

    const D3DFORMAT allowedAdapterFormatArray[] = 
    {   
        D3DFMT_X8R8G8B8, 
        D3DFMT_X1R5G5B5, 
        D3DFMT_R5G6B5, 
        D3DFMT_A2R10G10B10
    };
    const UINT allowedAdapterFormatArrayCount  = sizeof(allowedAdapterFormatArray) / sizeof(allowedAdapterFormatArray[0]);

    UINT numAdapters = pD3D->GetAdapterCount();
    for (UINT adapterOrdinal = 0; adapterOrdinal < numAdapters; adapterOrdinal++)
    {
        CD3DEnumAdapterInfo* pAdapterInfo = MEMALLOC_NEW(CD3DEnumAdapterInfo);
        if( pAdapterInfo == NULL )
            return E_OUTOFMEMORY;

        pAdapterInfo->AdapterOrdinal = adapterOrdinal;
        pD3D->GetAdapterIdentifier(adapterOrdinal, 0, &pAdapterInfo->AdapterIdentifier);

        // Get list of all display modes on this adapter.  
        // Also build a temporary list of all display adapter formats.
        adapterFormatList.RemoveAll();

        for( UINT iFormatList = 0; iFormatList < allowedAdapterFormatArrayCount; iFormatList++ )
        {
            D3DFORMAT allowedAdapterFormat = allowedAdapterFormatArray[iFormatList];
            UINT numAdapterModes = pD3D->GetAdapterModeCount( adapterOrdinal, allowedAdapterFormat );
            for (UINT mode = 0; mode < numAdapterModes; mode++)
            {
                D3DDISPLAYMODE displayMode;
                pD3D->EnumAdapterModes( adapterOrdinal, allowedAdapterFormat, mode, &displayMode );

                if( displayMode.Width < m_nMinWidth ||
                    displayMode.Height < m_nMinHeight || 
                    displayMode.Width > m_nMaxWidth ||
                    displayMode.Height > m_nMaxHeight || 
                    displayMode.RefreshRate < m_nRefreshMin ||
                    displayMode.RefreshRate > m_nRefreshMax )
                {
                    continue;
                }

                pAdapterInfo->displayModeList.Add( displayMode );
                
                if( !adapterFormatList.Contains(displayMode.Format) )
                    adapterFormatList.Add( displayMode.Format );
            }

        }

        D3DDISPLAYMODE displayMode;
        pD3D->GetAdapterDisplayMode( adapterOrdinal, &displayMode );
        if( !adapterFormatList.Contains(displayMode.Format) )
            adapterFormatList.Add( displayMode.Format );

        // Sort displaymode list
        ::qsort( pAdapterInfo->displayModeList.GetData(), 
               pAdapterInfo->displayModeList.GetSize(), sizeof( D3DDISPLAYMODE ),
               SortModesCallback );

        // Get info for each device on this adapter
        if( FAILED( EnumerateDevices( pAdapterInfo, &adapterFormatList ) ) )
        {
            delete pAdapterInfo;
            continue;
        }

        // If at least one device on this adapter is available and compatible
        // with the app, add the adapterInfo to the list
        if( pAdapterInfo->deviceInfoList.GetSize() > 0 )
        {
            hr = m_AdapterInfoList.Add( pAdapterInfo );
            if( FAILED(hr) )
                return hr;
        } else
            delete pAdapterInfo;
    }

    bool bUniqueDesc = true;
    CD3DEnumAdapterInfo* pAdapterInfo;
    for( NxI32 i=0; i<m_AdapterInfoList.GetSize(); i++ )
    {
        CD3DEnumAdapterInfo* pAdapterInfo1 = m_AdapterInfoList.GetAt(i);

        for( NxI32 j=i+1; j<m_AdapterInfoList.GetSize(); j++ )
        {
            CD3DEnumAdapterInfo* pAdapterInfo2 = m_AdapterInfoList.GetAt(j);
            if( _stricmp( pAdapterInfo1->AdapterIdentifier.Description, 
                          pAdapterInfo2->AdapterIdentifier.Description ) == 0 )
            {
                bUniqueDesc = false;
                break;
            }
        }

        if( !bUniqueDesc )
            break;
    }

    for( NxI32 i=0; i<m_AdapterInfoList.GetSize(); i++ )
    {
        pAdapterInfo = m_AdapterInfoList.GetAt(i);

        MultiByteToWideChar( CP_ACP, 0, 
                             pAdapterInfo->AdapterIdentifier.Description, -1, 
                             pAdapterInfo->szUniqueDescription, 100 );
        pAdapterInfo->szUniqueDescription[100] = 0;

        if( !bUniqueDesc )
        {
            WCHAR sz[100];
            StringCchPrintf( sz, 100, L" (#%d)", pAdapterInfo->AdapterOrdinal );
            StringCchCat( pAdapterInfo->szUniqueDescription, 256, sz );

        }
    }

    return S_OK;
}
Esempio n. 16
0
//-----------------------------------------------------------------------------
// Name: Enumerate
// Desc: Enumerates available D3D adapters, devices, modes, etc.
//-----------------------------------------------------------------------------
HRESULT CD3DEnumeration::Enumerate()
{
    HRESULT hr;
    CArrayList adapterFormatList( AL_VALUE, sizeof(D3DFORMAT) );

    if( m_pD3D == NULL )
        return E_FAIL;

    m_pAdapterInfoList = new CArrayList( AL_REFERENCE );
    if( m_pAdapterInfoList == NULL )
        return E_OUTOFMEMORY;

    m_pAllowedAdapterFormatList = new CArrayList( AL_VALUE, sizeof(D3DFORMAT) );
    if( m_pAllowedAdapterFormatList == NULL )
        return E_OUTOFMEMORY;
    D3DFORMAT fmt;
    if( FAILED( hr = m_pAllowedAdapterFormatList->Add( &( fmt = D3DFMT_X8R8G8B8 ) ) ) )
        return hr;
    if( FAILED( hr = m_pAllowedAdapterFormatList->Add( &( fmt = D3DFMT_X1R5G5B5 ) ) ) )
        return hr;
    if( FAILED( hr = m_pAllowedAdapterFormatList->Add( &( fmt = D3DFMT_R5G6B5 ) ) ) )
        return hr;
    if( FAILED( hr = m_pAllowedAdapterFormatList->Add( &( fmt = D3DFMT_A2R10G10B10 ) ) ) )
        return hr;

    D3DAdapterInfo* pAdapterInfo = NULL;
    UINT numAdapters = m_pD3D->GetAdapterCount();

    for (UINT adapterOrdinal = 0; adapterOrdinal < numAdapters; adapterOrdinal++)
    {
        pAdapterInfo = new D3DAdapterInfo;
        if( pAdapterInfo == NULL )
            return E_OUTOFMEMORY;
        pAdapterInfo->pDisplayModeList = new CArrayList( AL_VALUE, sizeof(D3DDISPLAYMODE)); 
        pAdapterInfo->pDeviceInfoList = new CArrayList( AL_REFERENCE );
        if( pAdapterInfo->pDisplayModeList == NULL ||
            pAdapterInfo->pDeviceInfoList == NULL )
        {
            delete pAdapterInfo;
            return E_OUTOFMEMORY;
        }
        pAdapterInfo->AdapterOrdinal = adapterOrdinal;
        m_pD3D->GetAdapterIdentifier(adapterOrdinal, 0, &pAdapterInfo->AdapterIdentifier);

        // Get list of all display modes on this adapter.  
        // Also build a temporary list of all display adapter formats.
        adapterFormatList.Clear();
        for( UINT iaaf = 0; iaaf < m_pAllowedAdapterFormatList->Count(); iaaf++ )
        {
            D3DFORMAT allowedAdapterFormat = *(D3DFORMAT*)m_pAllowedAdapterFormatList->GetPtr( iaaf );
            UINT numAdapterModes = m_pD3D->GetAdapterModeCount( adapterOrdinal, allowedAdapterFormat );
            for (UINT mode = 0; mode < numAdapterModes; mode++)
            {
                D3DDISPLAYMODE displayMode;
                m_pD3D->EnumAdapterModes( adapterOrdinal, allowedAdapterFormat, mode, &displayMode );
                if( displayMode.Width < AppMinFullscreenWidth ||
                    displayMode.Height < AppMinFullscreenHeight ||
                    ColorChannelBits(displayMode.Format) < AppMinColorChannelBits )
                {
                    continue;
                }
                pAdapterInfo->pDisplayModeList->Add(&displayMode);
                if( !adapterFormatList.Contains( &displayMode.Format ) )
                    adapterFormatList.Add( &displayMode.Format );
            }
        }

        // Sort displaymode list
        qsort( pAdapterInfo->pDisplayModeList->GetPtr(0), 
            pAdapterInfo->pDisplayModeList->Count(), sizeof( D3DDISPLAYMODE ),
            SortModesCallback );

        // Get info for each device on this adapter
        if( FAILED( hr = EnumerateDevices( pAdapterInfo, &adapterFormatList ) ) )
        {
            delete pAdapterInfo;
            return hr;
        }

        // If at least one device on this adapter is available and compatible
        // with the app, add the adapterInfo to the list
        if (pAdapterInfo->pDeviceInfoList->Count() == 0)
            delete pAdapterInfo;
        else
            m_pAdapterInfoList->Add(pAdapterInfo);
    }
    return S_OK;
}
Esempio n. 17
0
//--------------------------------------------------------------------------------------
// Enumerate for each adapter all of the supported display modes, 
// device types, adapter formats, back buffer formats, window/full screen support, 
// depth stencil formats, multisampling types/qualities, and presentations intervals.
//
// For each combination of device type (HAL/REF), adapter format, back buffer format, and
// IsWindowed it will call the app's ConfirmDevice callback.  This allows the app
// to reject or allow that combination based on its caps/etc.  It also allows the 
// app to change the BehaviorFlags.  The BehaviorFlags defaults non-pure HWVP 
// if supported otherwise it will default to SWVP, however the app can change this 
// through the ConfirmDevice callback.
//--------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc,
                                      void* pIsD3D11DeviceAcceptableFuncUserContext )
{
    CDXUTPerfEventGenerator eventGenerator( DXUT_PERFEVENTCOLOR, L"DXUT D3D11 Enumeration" );
    HRESULT hr;
    IDXGIFactory1* pFactory = DXUTGetDXGIFactory();
    if( !pFactory )
        return E_FAIL;

    m_bHasEnumerated = true;
    m_IsD3D11DeviceAcceptableFunc = IsD3D11DeviceAcceptableFunc;
    m_pIsD3D11DeviceAcceptableFuncUserContext = pIsD3D11DeviceAcceptableFuncUserContext;

    ClearAdapterInfoList();

    for( int index = 0; ; ++index )
    {
        IDXGIAdapter* pAdapter = nullptr;
        hr = pFactory->EnumAdapters( index, &pAdapter );
        if( FAILED( hr ) ) // DXGIERR_NOT_FOUND is expected when the end of the list is hit
            break;

        IDXGIAdapter2* pAdapter2 = nullptr;
        if ( SUCCEEDED( pAdapter->QueryInterface( __uuidof(IDXGIAdapter2), ( LPVOID* )&pAdapter2 ) ) )
        {
            // Succeeds on DirectX 11.1 Runtime systems
            DXGI_ADAPTER_DESC2 desc;
            hr = pAdapter2->GetDesc2( &desc );
            pAdapter2->Release();

            if ( SUCCEEDED(hr) && ( desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE ) )
            {
                // Skip "always there" Microsoft Basics Display Driver
                pAdapter->Release();
                continue;
            }
        }

        CD3D11EnumAdapterInfo* pAdapterInfo = new (std::nothrow) CD3D11EnumAdapterInfo;
        if( !pAdapterInfo )
        {
            SAFE_RELEASE( pAdapter );
            return E_OUTOFMEMORY;
        }
        pAdapterInfo->AdapterOrdinal = index;
        pAdapter->GetDesc( &pAdapterInfo->AdapterDesc );
        pAdapterInfo->m_pAdapter = pAdapter;

        // Enumerate the device driver types on the adapter.
        hr = EnumerateDevices( pAdapterInfo );
        if( FAILED( hr ) )
        {
            delete pAdapterInfo;
            continue;
        }

        hr = EnumerateOutputs( pAdapterInfo );
        if( FAILED( hr ) || pAdapterInfo->outputInfoList.empty() )
        {
            delete pAdapterInfo;
            continue;
        }

        // Get info for each devicecombo on this device
        if( FAILED( hr = EnumerateDeviceCombos( pAdapterInfo ) ) )
        {
            delete pAdapterInfo;
            continue;
        }

        m_AdapterInfoList.push_back( pAdapterInfo );
    }

    //  If we did not get an adapter then we should still enumerate WARP and Ref.
    if (m_AdapterInfoList.size() == 0)
    {
        CD3D11EnumAdapterInfo* pAdapterInfo = new (std::nothrow) CD3D11EnumAdapterInfo;
        if( !pAdapterInfo )
        {
            return E_OUTOFMEMORY;
        }
        pAdapterInfo->bAdapterUnavailable = true;

        hr = EnumerateDevices( pAdapterInfo );

        // Get info for each devicecombo on this device
        if( FAILED( hr = EnumerateDeviceCombosNoAdapter(  pAdapterInfo ) ) )
        {
            delete pAdapterInfo;
        }

        if (SUCCEEDED(hr)) m_AdapterInfoList.push_back( pAdapterInfo );
    }

    //
    // Check for 2 or more adapters with the same name. Append the name
    // with some instance number if that's the case to help distinguish
    // them.
    //
    bool bUniqueDesc = true;
    for( size_t i = 0; i < m_AdapterInfoList.size(); i++ )
    {
        auto pAdapterInfo1 = m_AdapterInfoList[ i ];

        for( size_t j = i + 1; j < m_AdapterInfoList.size(); j++ )
        {
            auto pAdapterInfo2 = m_AdapterInfoList[ j ];
            if( wcsncmp( pAdapterInfo1->AdapterDesc.Description,
                pAdapterInfo2->AdapterDesc.Description, DXGI_MAX_DEVICE_IDENTIFIER_STRING ) == 0 )
            {
                bUniqueDesc = false;
                break;
            }
        }

        if( !bUniqueDesc )
            break;
    }

    for( auto it = m_AdapterInfoList.begin(); it != m_AdapterInfoList.end(); ++it )
    {
        wcscpy_s( (*it)->szUniqueDescription, 100, (*it)->AdapterDesc.Description );
        if( !bUniqueDesc )
        {
            WCHAR sz[100];
            swprintf_s( sz, 100, L" (#%u)", (*it)->AdapterOrdinal );
            wcscat_s( (*it)->szUniqueDescription, DXGI_MAX_DEVICE_IDENTIFIER_STRING, sz );
        }
    }

    D3D_FEATURE_LEVEL fLvl[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1 };

    // Check WARP max feature level
    {
        ID3D11Device* pDevice = nullptr;
        hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, fLvl, _countof(fLvl),
                                             D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr );
        if ( hr == E_INVALIDARG )
        {
            // DirectX 11.0 runtime will not recognize FL 11.1, so try without it
            hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, &fLvl[1], _countof(fLvl) - 1,
                                                 D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr );
        }

        if ( SUCCEEDED(hr) )
        {
            pDevice->Release();
        }
        else
            m_warpFL = D3D_FEATURE_LEVEL_10_1;
    }

    // Check REF max feature level
    {
        ID3D11Device* pDevice = nullptr;
        hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_REFERENCE, 0, 0, fLvl, _countof(fLvl),
                                             D3D11_SDK_VERSION, &pDevice, &m_refFL, nullptr );
        if ( hr == E_INVALIDARG )
        {
            // DirectX 11.0 runtime will not recognize FL 11.1, so try without it
            hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_REFERENCE, 0, 0, &fLvl[1], _countof(fLvl) - 1,
                                                 D3D11_SDK_VERSION, &pDevice, &m_refFL, nullptr );
        }

        if ( SUCCEEDED(hr) )
        {
            pDevice->Release();
        }
        else
            m_refFL = D3D_FEATURE_LEVEL_11_0;
    }

    return S_OK;
}
static LRESULT CALLBACK WindowProc_InputOnly(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
    case WM_CREATE:
        {
            //
            // Register for joystick devices
            //
            
#ifdef IW_DEBUG
            // This is just for logging - doesnt actually do anything in release
            EnumerateDevices();            
#endif

            // See USB Serial BUS HID Usage Tables (http://www.usb.org/developers/devclass_docs/Hut1_12v2.pdf) for more info
            RAWINPUTDEVICE rid;
            const USHORT usageJoystick = 4;
            const USHORT usageGamePad = 5;
            USHORT usageToAttempt = usageGamePad; //todo: not used!

            // Try game-pad first
            rid.usUsagePage = 1;
            rid.usUsage     = usageGamePad;
            rid.dwFlags     = RIDEV_INPUTSINK;
            rid.hwndTarget  = hWnd;

            if(RegisterRawInputDevices(&rid, 1, sizeof(RAWINPUTDEVICE)))
            {
                g_GotDevice = TRUE;
                IwTrace(HIDCONTROLLER, ("%s: WM_CREATE: RegisterRawInputDevices SUCCEEDED for Usage Id %d!\n", __FUNCTION__, rid.usUsage));
            }
            else
            {
                // Try usage joystick next...if no game-pad found...this is for Logitech compatibility
                rid.usUsage = usageJoystick;
                IwTrace(HIDCONTROLLER, ("%s: WM_CREATE: RegisterRawInputDevices with usUsage %d failed, trying %d!\n", __FUNCTION__, usageGamePad, usageJoystick));
                
                if(RegisterRawInputDevices(&rid, 1, sizeof(RAWINPUTDEVICE)))
                {
                    g_GotDevice = TRUE;
                    IwTrace(HIDCONTROLLER, ("%s: WM_CREATE: RegisterRawInputDevices SUCCEEDED for Usage Id %d!\n", __FUNCTION__, rid.usUsage));
                }
                else
                {
                    g_GotDevice = FALSE;
                    IwTrace(HIDCONTROLLER, ("%s: WM_CREATE: RegisterRawInputDevices returned -1...attempted both %d and %d usages :(\n", __FUNCTION__, usageGamePad, usageJoystick));
                    return -1;
                }
            }
        }
        return 0;

    case WM_INPUT:
        {
            //
            // Get the pointer to the raw device data, process it and update the window
            //

            PRAWINPUT pRawInput;
            UINT      bufferSize;
            HANDLE    hHeap;

            GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &bufferSize, sizeof(RAWINPUTHEADER));

            hHeap     = GetProcessHeap();
            pRawInput = (PRAWINPUT)HeapAlloc(hHeap, 0, bufferSize);
            if(!pRawInput)
                return 0;

            GetRawInputData((HRAWINPUT)lParam, RID_INPUT, pRawInput, &bufferSize, sizeof(RAWINPUTHEADER));
            ParseRawInput(pRawInput);

            HeapFree(hHeap, 0, pRawInput);
        }
        return 0;

    default:
        break;
    }

    return DefWindowProc(hWnd, msg, wParam, lParam);
}
Esempio n. 19
0
void MyFrame::CreateMenus()
{
    //---- File menu --------------------------------------------------------
    m_fileMenu = new wxMenu;
#ifdef WXVIDCAP_AVI_SUPPORT
    m_fileMenu->Append(ID_SETCAPFILENAME,      wxT("Set Capture File&name..."), wxT("Set capture filename"));
    m_fileMenu->Append(ID_SETCAPFILESIZE,      wxT("Set Capture File&size..."), wxT("Set capture filesize"));
    m_fileMenu->Append(ID_SAVECAPTUREDVIDEOAS, wxT("&Extract video to file"),   wxT("After capture save video to new file"), wxITEM_CHECK);

    m_fileMenu->AppendSeparator();
#endif // WXVIDCAP_AVI_SUPPORT

#ifdef WXVIDCAP_LINUX_V4L
    m_fileMenu->Append(wxID_OPEN, wxT("&Open video device...\tAlt-O"), wxT("Open a video device by filename..."));
    m_fileMenu->AppendSeparator();
#endif //WXVIDCAP_LINUX_V4L
    m_fileMenu->Append(wxID_EXIT, wxT("E&xit\tAlt-X"), wxT("Quit this program"));

    //---- Image Processing menu ---------------------------------------------
    m_processMenu = new wxMenu;

    m_processMenu->Append(ID_IMGPROCESS_NEGATIVE, wxT("&Negative"),      wxT("Invert intensities"), wxITEM_CHECK);
    m_processMenu->Append(ID_IMGPROCESS_EDGE,     wxT("&Edge detector"), wxT("Very simple edge detector"), wxITEM_CHECK);
    m_processMenu->Append(ID_IMGPROCESS_MOTION,   wxT("&Motion"),        wxT("Simple motion detector"), wxITEM_CHECK);

    //---- Video menu -------------------------------------------------------
    m_videoMenu = new wxMenu;

    m_videoMenu->Append(ID_DEVICE_ENUMERATE, wxT("Resca&n for devices"), wxT("Enumerate devices found on the system"));
    m_videoMenu->AppendSeparator();

    m_videoMenu->Append(ID_DEVICENONE,      wxT("&Disconnect"),          wxT("Disconnect from all devices"), wxITEM_CHECK );

    EnumerateDevices();

    m_videoMenu->AppendSeparator();
    m_videoMenu->Append(ID_PREVIEW,         wxT("&Preview\tCtrl-P"),         wxT("Preview video"), wxITEM_CHECK);
    m_videoMenu->Append(ID_PREVIEWIMAGE,    wxT("Preview wx&Image\tCtrl-I"), wxT("Preview using wxImages"), wxITEM_CHECK);
    m_videoMenu->Append(ID_IMGPROCESS_MENU, wxT("P&rocess wxImage"), m_processMenu, wxT("Simple image processing of wxImages"));
    m_videoMenu->Append(ID_PREVIEWSCALED,   wxT("Preview &Scaling\tCtrl-U"), wxT("Fit video size to window"), wxITEM_CHECK);
    m_videoMenu->Append(ID_PREVIEWRATE,     wxT("Preview &Rate...\tCtrl-R"), wxT("Set preview rate"));
    m_videoMenu->Append(ID_OVERLAY,         wxT("&Overlay\tCtrl-O"),  wxT("Preview using hardware overlay"), wxITEM_CHECK);

    m_videoMenu->AppendSeparator();
    m_videoMenu->Append(ID_DLGSOURCE,       wxT("So&urce..."),        wxT("Set video source"));
    m_videoMenu->Append(ID_DLGFORMAT,       wxT("&Format..."),        wxT("Set video format"));
    m_videoMenu->Append(ID_DLGCUSTOMFORMAT, wxT("&Custom format..."), wxT("Set custom video format"));
    m_videoMenu->Append(ID_DLGDISPLAY,      wxT("&Display..."),       wxT("Set video display"));
    m_videoMenu->Append(ID_DLGPROPERTIES,   wxT("P&roperties..."),    wxT("Video properties"));

    //---- Capture menu ------------------------------------------------------
    m_captureMenu = new wxMenu;

    m_captureMenu->Append(ID_SNAPTOWINDOW,    wxT("Snapshot to &window\tCtrl-W"),      wxT("View the current frame"));
    m_captureMenu->Append(ID_SNAPTOCLIPBOARD, wxT("Snapshot to &clipboard\tCtrl-C"),   wxT("Capture a frame to the clipboard"));
    m_captureMenu->Append(ID_SNAPTOFILE,      wxT("Snapshot to &file...\tCtrl-F"),     wxT("Capture and save a frame to an image file"));
    m_captureMenu->Append(ID_SNAPTOBMP,       wxT("Snapshot to &BMP file...\tCtrl-B"), wxT("Capture and save a frame as a BMP file"));

#ifdef WXVIDCAP_AVI_SUPPORT
    m_captureMenu->Append(ID_CAPVIDEO,        wxT("Capture &video"),            wxT("Capture video"));
    m_captureMenu->Append(ID_CAPSINGLEFRAMES, wxT("Capture &single frames..."), wxT("Capture a series of single frames as video"));
#endif // WXVIDCAP_AVI_SUPPORT

    m_captureMenu->AppendSeparator();

    m_captureMenu->Append(ID_NOPREVIEWONCAP, wxT("&Stop preview on capture"), wxT("Stop previewing for any capture"), wxITEM_CHECK);
    m_captureMenu->Check( ID_NOPREVIEWONCAP, true);

#ifdef WXVIDCAP_AVI_SUPPORT
    m_captureMenu->Append(ID_DLGCAPPREFERENCES, wxT("Capture &preferences..."), wxT("Capture preferences dialog"));
    m_captureMenu->Append(ID_DLGCOMPRESSION,    wxT("&Compression..."),         wxT("Set recorded video compression"));
#endif // WXVIDCAP_AVI_SUPPORT

#ifdef WXVIDCAP_AUDIO_SUPPORT
    m_captureMenu->Append(ID_DLGAUDIO, wxT("&Audio Format..."), wxT("Set recorded audio format"));
#endif // WXVIDCAP_AUDIO_SUPPORT

    //---- Help menu --------------------------------------------------------
    m_helpMenu = new wxMenu;
    m_helpMenu->Append(wxID_ABOUT, wxT("&About...\tCtrl-A"), wxT("Show about dialog"));
    m_helpMenu->Append(ID_SHOWLOG, wxT("&Show log\tCtrl-L"), wxT("Show log window"), wxITEM_CHECK);


    // now append the freshly created menu to the menu bar...
    m_menubar->Append(m_fileMenu,    wxT("&File"));
    m_menubar->Append(m_videoMenu,   wxT("&Video"));
    m_menubar->Append(m_captureMenu, wxT("&Capture"));
    m_menubar->Append(m_helpMenu,    wxT("&Help"));
}
Esempio n. 20
0
//--------------------------------------------------------------------------------------
// Enumerate for each adapter all of the supported display modes, 
// device types, adapter formats, back buffer formats, window/full screen support, 
// depth stencil formats, multisampling types/qualities, and presentations intervals.
//
// For each combination of device type (HAL/REF), adapter format, back buffer format, and
// IsWindowed it will call the app's ConfirmDevice callback.  This allows the app
// to reject or allow that combination based on its caps/etc.  It also allows the 
// app to change the BehaviorFlags.  The BehaviorFlags defaults non-pure HWVP 
// if supported otherwise it will default to SWVP, however the app can change this 
// through the ConfirmDevice callback.
//--------------------------------------------------------------------------------------
HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc,
                                      void* pIsD3D11DeviceAcceptableFuncUserContext )
{
    CDXUTPerfEventGenerator eventGenerator( DXUT_PERFEVENTCOLOR, L"DXUT D3D11 Enumeration" );
    HRESULT hr;
    IDXGIFactory1* pFactory = DXUTGetDXGIFactory();
    if( pFactory == NULL )
        return E_FAIL;

    m_bHasEnumerated = true;
    m_IsD3D11DeviceAcceptableFunc = IsD3D11DeviceAcceptableFunc;
    m_pIsD3D11DeviceAcceptableFuncUserContext = pIsD3D11DeviceAcceptableFuncUserContext;

    ClearAdapterInfoList();

    for( int index = 0; ; ++index )
    {
        IDXGIAdapter* pAdapter = NULL;
        hr = pFactory->EnumAdapters( index, &pAdapter );
        if( FAILED( hr ) ) // DXGIERR_NOT_FOUND is expected when the end of the list is hit
            break;

        CD3D11EnumAdapterInfo* pAdapterInfo = new CD3D11EnumAdapterInfo;
        if( !pAdapterInfo )
        {
            SAFE_RELEASE( pAdapter );
            return E_OUTOFMEMORY;
        }
        ZeroMemory( pAdapterInfo, sizeof( CD3D11EnumAdapterInfo ) );
        pAdapterInfo->AdapterOrdinal = index;
        pAdapter->GetDesc( &pAdapterInfo->AdapterDesc );
        pAdapterInfo->m_pAdapter = pAdapter;

        // Enumerate the device driver types on the adapter.
        hr = EnumerateDevices( pAdapterInfo );
        if( FAILED( hr ) )
        {
            delete pAdapterInfo;
            continue;
        }

        hr = EnumerateOutputs( pAdapterInfo );
        if( FAILED( hr ) || pAdapterInfo->outputInfoList.GetSize() <= 0 )
        {
            delete pAdapterInfo;
            continue;
        }

        // Get info for each devicecombo on this device
        if( FAILED( hr = EnumerateDeviceCombos( pFactory, pAdapterInfo ) ) )
        {
            delete pAdapterInfo;
            continue;
        }

        hr = m_AdapterInfoList.Add( pAdapterInfo );
        if( FAILED( hr ) )
        {
            delete pAdapterInfo;
            return hr;
        }
    }


    //  If we did not get an adapter then we should still enumerate WARP and Ref.
    if (m_AdapterInfoList.GetSize() == 0) {


        CD3D11EnumAdapterInfo* pAdapterInfo = new CD3D11EnumAdapterInfo;
        if( !pAdapterInfo )
        {
            return E_OUTOFMEMORY;
        }
        ZeroMemory( pAdapterInfo, sizeof( CD3D11EnumAdapterInfo ) );
        pAdapterInfo->bAdapterUnavailable = true;

        hr = EnumerateDevices( pAdapterInfo );

        // Get info for each devicecombo on this device
        if( FAILED( hr = EnumerateDeviceCombosNoAdapter(  pAdapterInfo ) ) )
        {
            delete pAdapterInfo;
        }

        if (!FAILED(hr)) hr = m_AdapterInfoList.Add( pAdapterInfo );
    }

    //
    // Check for 2 or more adapters with the same name. Append the name
    // with some instance number if that's the case to help distinguish
    // them.
    //
    bool bUniqueDesc = true;
    CD3D11EnumAdapterInfo* pAdapterInfo;
    for( int i = 0; i < m_AdapterInfoList.GetSize(); i++ )
    {
        CD3D11EnumAdapterInfo* pAdapterInfo1 = m_AdapterInfoList.GetAt( i );

        for( int j = i + 1; j < m_AdapterInfoList.GetSize(); j++ )
        {
            CD3D11EnumAdapterInfo* pAdapterInfo2 = m_AdapterInfoList.GetAt( j );
            if( wcsncmp( pAdapterInfo1->AdapterDesc.Description,
                pAdapterInfo2->AdapterDesc.Description, DXGI_MAX_DEVICE_IDENTIFIER_STRING ) == 0 )
            {
                bUniqueDesc = false;
                break;
            }
        }

        if( !bUniqueDesc )
            break;
    }

    for( int i = 0; i < m_AdapterInfoList.GetSize(); i++ )
    {
        pAdapterInfo = m_AdapterInfoList.GetAt( i );

        wcscpy_s( pAdapterInfo->szUniqueDescription, 100, pAdapterInfo->AdapterDesc.Description );
        if( !bUniqueDesc )
        {
            WCHAR sz[100];
            swprintf_s( sz, 100, L" (#%d)", pAdapterInfo->AdapterOrdinal );
            wcscat_s( pAdapterInfo->szUniqueDescription, DXGI_MAX_DEVICE_IDENTIFIER_STRING, sz );
        }
    }

    return S_OK;
}
// ==============================================================================
GlSpectrumAnalyzerWindow::GlSpectrumAnalyzerWindow(SoundPlayController *ctrl)
	: BDirectGLWindow(
//		BRect(200,100,199+640,99+480),
//		BRect(200,100,199+640,99+480),
		BRect( 100.0, 100.0, 739.0, 579.0 ),	// 640x480
		"OpenGL"B_UTF8_REGISTERED" Spectrum Analyzer",
		B_TITLED_WINDOW,
		B_ASYNCHRONOUS_CONTROLS/*|B_NOT_RESIZABLE|B_NOT_ZOOMABLE*/),
	name(NULL),
	xrot(10.0),
	yrot(35.0),
	zrot(0.0),
	needResize(false),
	opengl_device(BGL_DEVICE_SOFTWARE)
{
	controller=ctrl;
	controller->AddWindow(this);	// let SoundPlay handle some hotkeys for this window

	bView=new BView(Bounds(),"view",B_FOLLOW_ALL_SIDES, 0);
	bView->SetViewColor(0.0, 0.0, 0.0);
	bView->SetFontSize(20);
	AddChild(bView);

	for(int x=0;x<20;x++)
	{
		peak[x]=0;
		lastpeak[x]=0;
		peakdelay[x]=0;
	}

	// Add a shortcut so Alt-F will toggle fullscreen.
	AddShortcut( 'f', 0, new BMessage( GO_FULLSCREEN ) );

	// Initialize OpenGL
	//
	// In theory you can also use single-buffering, s/DOUBLE/SINGLE/ in
	// these two.
	EnumerateDevices( BGL_MONITOR_PRIMARY, BGL_ANY | BGL_DOUBLE, BGL_ANY, BGL_NONE, BGL_NONE );
	InitializeGL( opengl_device, BGL_ANY | BGL_DOUBLE, BGL_ANY, BGL_NONE, BGL_NONE );

	keeprunning=true;
	// Magically, the window will now appear on-screen.
	Show();
	Sync();	// <- should prevent the thread from racing the window
	
	//gInit
	MakeCurrent();
	// Clear to black
	glClearColor( 0.0, 0.0, 0.0, 0.0 );
	
	// Set up the depth buffer
	glClearDepth( 1.0 );
	// The type of depth test
	glDepthFunc( GL_LEQUAL );
//	glDepthFunc( GL_LESS );
	// Enable depth testing
	glEnable( GL_DEPTH_TEST );
	
	// Set up perspective view

	// Enable smooth shading
	glShadeModel( GL_SMOOTH );

	// Really nice perspective calculations
	glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
	
	// Back face is solid, front face is outlined
	glPolygonMode( GL_BACK, GL_FILL );
	glPolygonMode( GL_FRONT, GL_LINE );

//	glMatrixMode( GL_PROJECTION );
	
#if 0
	float local_view[] = {0.0,0.0};
	float position[] = {0.0, 3.0, 3.0, 0.0};
	glLightfv(GL_LIGHT0, GL_POSITION, position);
	glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, local_view);

	float white[3] = {1.0,1.0,1.0};
	float dimWhite[3] = {0.25,0.25,0.25};

	glEnable(GL_LIGHT0);
	glLightfv(GL_LIGHT0, GL_SPECULAR, dimWhite);
	glLightfv(GL_LIGHT0, GL_DIFFUSE,white);
	glLightfv(GL_LIGHT0, GL_AMBIENT,white);

	glFrontFace(GL_CW);
	glEnable(GL_LIGHTING);
	glEnable(GL_AUTO_NORMAL);
	glEnable(GL_NORMALIZE);
	glMaterialf(GL_FRONT, GL_SHININESS, 0.6*128.0);

	glColor3f(1.0, 1.0, 1.0);

	glMatrixMode(GL_PROJECTION);
#endif

	glLoadIdentity();
	ReleaseCurrent();

	FrameResized(float(Bounds().IntegerWidth() + 1), float(Bounds().IntegerHeight() + 1));
}
// use cameraID 1 for first and so on
HRESULT VideoTexture::init(int cameraID)
{
	if (cameraID <= 0) return S_FALSE;

	glEnable(GL_TEXTURE_2D);

	// Texture -> This will be put into the camera module	
	glGenTextures(1, textures);					// Create The Texture
	// Typical Texture Generation Using Data From The Bitmap
	for (int i = 0; i < 1; i++)
	{
		//glActiveTexture(GL_TEXTURE0 + i);
		glBindTexture(GL_TEXTURE_2D, textures[i]);
		// Generate The Texture (640x480... make changeable!)
		//glTexImage2D(GL_TEXTURE_2D, 0, 3, 640, 480, 0, GL_RGB, GL_UNSIGNED_BYTE, ...THe data111!!!);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);	// Linear Filtering
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);	// Linear Filtering
		// Enable Texture Mapping
		glTexImage2D(GL_TEXTURE_2D, 0, 3, TEXTURE_WIDTH, TEXTURE_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
	}

	// Video stuff:
	// Create captue graph builder:
	HRESULT hr = InitCaptureGraphBuilder(&pGraph, &pBuild);
	if (FAILED(hr)) return hr;
	IEnumMoniker *enumerator;
	hr = EnumerateDevices(CLSID_VideoInputDeviceCategory, &enumerator);
	//DisplayDeviceInformation(enumerator);
	// Take the first camera:
	IMoniker *pMoniker = NULL;
	for (int i = 0; i < cameraID; i++)
	{
		enumerator->Next(1, &pMoniker, NULL);
	}
	IBaseFilter *pCap = NULL;
	hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&pCap);
	if (SUCCEEDED(hr))
	{
		hr = pGraph->AddFilter(pCap, L"Capture Filter");
		if (FAILED(hr)) return hr;
	}
	else return hr;

	// Create the Sample Grabber which we will use
	// To take each frame for texture generation
	hr = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER,
							IID_ISampleGrabber, (void **)&pGrabber);
	if (FAILED(hr)) return hr;
	hr = pGrabber->QueryInterface(IID_IBaseFilter, (void **)&pGrabberBase);
		// We have to set the 24-bit RGB desire here
	// So that the proper conversion filters
	// Are added automatically.
	AM_MEDIA_TYPE desiredType;
	memset(&desiredType, 0, sizeof(desiredType));
	desiredType.majortype = MEDIATYPE_Video;
	desiredType.subtype = MEDIASUBTYPE_RGB24;
	desiredType.formattype = FORMAT_VideoInfo;
	pGrabber->SetMediaType(&desiredType);
	pGrabber->SetBufferSamples(TRUE);
	// add to Graph
	pGraph->AddFilter(pGrabberBase, L"Grabber");

    /* Null render filter */
    hr = CoCreateInstance(CLSID_NullRenderer, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&pNullRender);
    if(FAILED(hr)) return hr;
	pGraph->AddFilter(pNullRender, L"Render");

	// Connect the graph
    hr = ConnectFilters(pGraph, pCap, pGrabberBase); 
    if(FAILED(hr)) return hr;
	hr = ConnectFilters(pGraph, pGrabberBase, pNullRender);

	// Set output format of capture:
	IAMStreamConfig *pConfig = NULL;
    hr = pBuild->FindInterface(
                &PIN_CATEGORY_CAPTURE, // Capture pin.
                0,    // Any media type.
                pCap, // Pointer to the capture filter.
                IID_IAMStreamConfig, (void**)&pConfig);
	if (FAILED(hr)) return hr;
	AM_MEDIA_TYPE *pmtConfig;
	hr = pConfig->GetFormat(&pmtConfig);
	if (FAILED(hr)) return hr;
		
	// Try and find a good video format
    int iCount = 0, iSize = 0;
    hr = pConfig->GetNumberOfCapabilities(&iCount, &iSize);               
    // Check the size to make sure we pass in the correct structure.
    if (iSize == sizeof(VIDEO_STREAM_CONFIG_CAPS))
    {
		// Use the video capabilities structure.               
        for (int iFormat = 0; iFormat < iCount; iFormat++)
        {
			VIDEO_STREAM_CONFIG_CAPS scc;
			AM_MEDIA_TYPE *pmtConfig;
			hr = pConfig->GetStreamCaps(iFormat, &pmtConfig, (BYTE*)&scc);
			if (SUCCEEDED(hr))
			{
				VIDEOINFOHEADER *hdr = (VIDEOINFOHEADER *)pmtConfig->pbFormat;
				if (hdr->bmiHeader.biWidth == CAM_WIDTH &&
					hdr->bmiHeader.biHeight == CAM_HEIGHT &&
					hdr->bmiHeader.biBitCount == 24)
				{
					pConfig->SetFormat(pmtConfig);
				}
			}
		}
	}
	pConfig->Release();

	// Set camera stuff
	IAMCameraControl *pCamControl = NULL;
	hr = pCap->QueryInterface(IID_IAMCameraControl, (void **)&pCamControl);
	if (FAILED(hr)) return hr;
	// Get the range and default value. 
	long Min, Max, Step, Default, Flags;
	// For getting: long Val;
	hr = pCamControl->GetRange(CameraControl_Focus, &Min, &Max, &Step, &Default, &Flags);
	if (SUCCEEDED(hr)) pCamControl->Set(CameraControl_Focus, 0, CameraControl_Flags_Manual);
#if 0
	hr = pCamControl->GetRange(CameraControl_Exposure, &Min, &Max, &Step, &Default, &Flags);
	if (SUCCEEDED(hr)) pCamControl->Set(CameraControl_Exposure, -4, CameraControl_Flags_Manual);
#endif
	pCamControl->Release();
	IAMVideoProcAmp *pProcAmp = 0;
	hr = pCap->QueryInterface(IID_IAMVideoProcAmp, (void**)&pProcAmp);
	if (FAILED(hr)) return hr;
#if 0
	hr = pProcAmp->GetRange(VideoProcAmp_Brightness, &Min, &Max, &Step, &Default, &Flags);
	if (SUCCEEDED(hr)) pProcAmp->Set(VideoProcAmp_Brightness, 30, VideoProcAmp_Flags_Manual);
	hr = pProcAmp->GetRange(VideoProcAmp_Gain, &Min, &Max, &Step, &Default, &Flags);
	if (SUCCEEDED(hr)) pProcAmp->Set(VideoProcAmp_Gain, 30, VideoProcAmp_Flags_Manual);
	hr = pProcAmp->GetRange(VideoProcAmp_WhiteBalance, &Min, &Max, &Step, &Default, &Flags);
	if (SUCCEEDED(hr)) pProcAmp->Set(VideoProcAmp_WhiteBalance, 4500, VideoProcAmp_Flags_Manual);
	hr = pProcAmp->GetRange(VideoProcAmp_Saturation, &Min, &Max, &Step, &Default, &Flags);
	if (SUCCEEDED(hr)) pProcAmp->Set(VideoProcAmp_Saturation, 100, VideoProcAmp_Flags_Manual);		
	hr = pProcAmp->GetRange(VideoProcAmp_Contrast, &Min, &Max, &Step, &Default, &Flags);
	if (SUCCEEDED(hr)) pProcAmp->Set(VideoProcAmp_Contrast, 6, VideoProcAmp_Flags_Manual);		
#endif
	pProcAmp->Release();

	hr = pMediaControl->Run();
	return hr;
}