bool VideoCapture::CreateMediaSource()
	{
		HRESULT hr;

		pin_ptr<IMFAttributes *> pConfig = &(this->Config);
		hr = MFCreateAttributes(pConfig, 1);
		if (hr != S_OK)
		{ 
			MFUtil::ShowErrorNameFromCode(hr);
			return false;
		}

		hr = this->Config->SetGUID(
			MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, 
			MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
		); 
		if (hr != S_OK)
		{ 
			MFUtil::ShowErrorNameFromCode(hr);
			return false;
		}

		pin_ptr<IMFActivate **> pDevices = &(this->Devices);
		pin_ptr<UINT32> pCount = &(this->DeviceCount);
		hr = MFEnumDeviceSources(this->Config, pDevices, pCount);
		if (hr != S_OK)
		{ 
			MFUtil::ShowErrorNameFromCode(hr);
			return false;
		}
		if (this->DeviceCount <= 0) 
		{ 
			MFUtil::ShowMessage(TEXT("Device Not Found."), ML_ERROR);
			return false;
		} 

		// Debug : 利用するデバイス(リストの先頭)の名前を確認
		LPWSTR devName = NULL;
		UINT32 devNameLen = 0;
		hr = this->Devices[0]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &devName, &devNameLen);
		if (hr != S_OK)
		{ 
			MFUtil::ShowErrorNameFromCode(hr);
			return false;
		}
		MFUtil::ShowMessage(devName, ML_DEBUG);

		pin_ptr<IMFMediaSource *> pSource = &(this->Source);
		hr = this->Devices[0]->ActivateObject(
			__uuidof(IMFMediaSource), 
			reinterpret_cast<void**>(pSource)
		);  
		if (hr != S_OK)
		{ 
			MFUtil::ShowErrorNameFromCode(hr);
			return false;
		}

		return true;
	}
    void OnChooseDevice(HWND hwnd)
    {
        ChooseDeviceParam param;

        IMFAttributes *pAttributes = NULL;

        HRESULT hr = MFCreateAttributes(&pAttributes, 1);
        if (FAILED(hr))
        {
            goto done;
        }

        // Ask for source type = video capture devices
        hr = pAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
                MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
        if (FAILED(hr))
        {
            goto done;
        }

        // Enumerate devices.
        hr = MFEnumDeviceSources(pAttributes, &param.ppDevices, &param.count);
        if (FAILED(hr))
        {
            goto done;
        }

        // Ask the user to select one.
        INT_PTR result = DialogBoxParam(GetModuleHandle(NULL),
            MAKEINTRESOURCE(IDD_CHOOSE_DEVICE), hwnd,
            ChooseDeviceDlgProc, (LPARAM)&param);

        if ((result == IDOK) && (param.selection != (UINT32)-1))
        {
            UINT iDevice = param.selection;

            if (iDevice >= param.count)
            {
                hr = E_UNEXPECTED;
                goto done;
            }

            hr = g_pEngine->InitializeCaptureManager(hPreview, param.ppDevices[iDevice]);
            if (FAILED(hr))
            {
                goto done;
            }
            SafeRelease(&pSelectedDevice);
            pSelectedDevice = param.ppDevices[iDevice];
            pSelectedDevice->AddRef();
        }

    done:
        SafeRelease(&pAttributes);
        if (FAILED(hr))
        {
            ShowError(hwnd, IDS_ERR_SET_DEVICE, hr);
        }
        UpdateUI(hwnd);
    }
Beispiel #3
0
    void MFPlayer::init(HWND handle)
    {
        HRESULT ret;

        // Initialize M$ bullshit
        //ret = CoInitializeEx(NULL, COINIT_MULTITHREADED);
        //assert(ret == S_OK);
        ret = MFStartup(MF_VERSION);
        assert(ret == S_OK);

        // Create factory
        IMFMediaEngineClassFactory *pMediaEngineClassFactory = nullptr;
        ret = CoCreateInstance(CLSID_MFMediaEngineClassFactory, nullptr, CLSCTX_ALL, IID_PPV_ARGS(&pMediaEngineClassFactory));
        assert(ret == S_OK);

        // Create notify
        m_pPlayerNodify = new MFPlayerNotify(shared_from_this());

        // Create attributes
        IMFAttributes *pAttributes = nullptr;
        ret = MFCreateAttributes(&pAttributes, 1);
        assert(ret == S_OK);
        ret = pAttributes->SetUnknown(MF_MEDIA_ENGINE_CALLBACK, m_pPlayerNodify);
        assert(ret == S_OK);
        ret = pAttributes->SetUINT64(MF_MEDIA_ENGINE_PLAYBACK_HWND, reinterpret_cast<UINT64>(handle));
        assert(ret == S_OK);

        // Create player
        ret = pMediaEngineClassFactory->CreateInstance(0, pAttributes, &m_pMediaEngine);
        assert(ret == S_OK);

        // Release bullshits
        pAttributes->Release();
        pMediaEngineClassFactory->Release();
    }
Beispiel #4
0
static int mf_enumerate_cameras(int (*callback)(IMFSourceReader* reader)) {
    com_t<IMFAttributes> config;
    if_failed_return_result(MFCreateAttributes(&config, 1));
    if_failed_return_result(config->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID));
    UINT32 num = 0;
    IMFActivate** factory = null;  // [count]
    if_failed_return_result(MFEnumDeviceSources(config, &factory, &num));
    if (num == 0) {
        return 0;
    }
    for (int i = 0; i < (int)num; i++) {
        const char* sl = "";
        const char* fn= "";
        WCHAR* symbolic_link = null;
        WCHAR* friendly_name = null;
        UINT32 size = 0;
        if (OK(factory[i]->GetAllocatedString(MF_SL, &symbolic_link, &size))) { sl = wcs2str(symbolic_link); }
        if (OK(factory[i]->GetAllocatedString(MF_FN, &friendly_name, &size))) { fn = wcs2str(friendly_name); }
        com_t<IMFMediaSource> source;
        if_failed_return_result(factory[i]->ActivateObject(IID_PPV_ARGS(&source)));
        com_t<IMFSourceReader> reader;
        if_failed_return_result(MFCreateSourceReaderFromMediaSource(source, null, &reader));
        print("\nMMF camera %d %s %s\n", i, fn, sl);
        callback(reader);
        com_release(factory[i]);
    }
    CoTaskMemFree(factory);
    return S_OK;
} 
Beispiel #5
0
//-------------------------------------------------------------------
// Initialise the source reader
//
HRESULT VidReader::initSourceReader(WCHAR *filename)
{
    HRESULT hr = S_OK;
    IMFAttributes *pAttributes = NULL;

    SafeRelease(&m_pReader);

	// Configure the source reader to perform video processing
    hr = MFCreateAttributes(&pAttributes, 1);
	if (FAILED(hr)) goto done;    
	hr = pAttributes->SetUINT32(MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, TRUE);
    if (FAILED(hr)) goto done;

    // Create the source reader from the URL
    hr = MFCreateSourceReaderFromURL(filename, pAttributes, &m_pReader);
    if (FAILED(hr)) goto done;

	// Attempt to find a video stream
    hr = selectVideoStream();
    if (FAILED(hr)) goto done;

	// Get the stream format
	hr = getVideoFormat();
    if (FAILED(hr)) goto done;

	// Get the duration
	hr = getDuration();

done:    
    return hr;
}
Beispiel #6
0
  bool MediaFoundationCaptureLibrary::BuildListOfDevices()
  {	
    HRESULT hr = S_OK;

    IMFAttributes *pAttributes = NULL;

    CoInitialize(NULL);

    hr = MFCreateAttributes(&pAttributes, 1);

    if (SUCCEEDED(hr))
    {
      hr = pAttributes->SetGUID(
        MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
        MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
        );
    }	

    if (SUCCEEDED(hr))
    {
      hr = MediaFoundationVideoDevices::GetInstance().InitDevices(pAttributes);
    }	
    else
    {
      LOG_ERROR("MEDIA FOUNDATION: The access to the video cameras denied.");
    }

    SafeRelease(&pAttributes);

    return (SUCCEEDED(hr));
  }
Beispiel #7
0
int CountCaptureDevices()
{
	HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

	if (FAILED(hr)) return 0;

	hr = MFStartup(MF_VERSION);

	if (FAILED(hr)) return 0;

	// choose device
	IMFAttributes *attributes = NULL;
	hr = MFCreateAttributes(&attributes, 1);
	ScopedRelease<IMFAttributes> attributes_s(attributes);

	if (FAILED(hr)) return 0;

	hr = attributes->SetGUID(
		MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
		MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
		);
	if (FAILED(hr)) return 0;

	ChooseDeviceParam param = { 0 };
	hr = MFEnumDeviceSources(attributes, &param.mDevices, &param.mCount);

	if (FAILED(hr)) return 0;

	return param.mCount;
}
HRESULT CCapture::OpenMediaSource(IMFMediaSource *pSource)
{
    HRESULT hr = S_OK;

    IMFAttributes *pAttributes = NULL;

    hr = MFCreateAttributes(&pAttributes, 2);

    if (SUCCEEDED(hr))
    {
        hr = pAttributes->SetUnknown(MF_SOURCE_READER_ASYNC_CALLBACK, this);
    }

    if (SUCCEEDED(hr))
    {
        hr = MFCreateSourceReaderFromMediaSource(
            pSource,
            pAttributes,
            &m_pReader
            );
    }

    SafeRelease(&pAttributes);
    return hr;
}
// Initialize Device List
HRESULT DeviceList::EnumerateDevices()
{
	HRESULT hr = S_OK;
	IMFAttributes *pAttributes = NULL;

	Clear();

	// Initialize an attribute store. We will use this to
	// specify the enumeration parameters.

	hr = MFCreateAttributes(&pAttributes, 1);

	// Ask for source type = video capture devices
	if (SUCCEEDED(hr))
	{
		hr = pAttributes->SetGUID(
			MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
			MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
			);
	}

	// Enumerate devices.
	if (SUCCEEDED(hr))
	{
		hr = MFEnumDeviceSources(pAttributes, &m_ppDevices, &m_cDevices);
	}

	SafeRelease(&pAttributes);

	return hr;
}
	bool VideoCapture::CreateSourceReaderAsync()
	{
		HRESULT hr;

		HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
		if (hEvent == NULL)
		{
			MFUtil::ShowMessage(TEXT("CreateEvent Failed."), ML_ERROR);
			return false;
		}

		this->CallBack = new SourceReaderCallBack(hEvent);
		if (this->CallBack == NULL)
		{
			MFUtil::ShowMessage(TEXT("CreateCallBack Failed."), ML_ERROR);
			return false;
		}
	
		IMFAttributes *pAttributes = NULL;

		hr = MFCreateAttributes(&pAttributes, 1);
		if (hr != S_OK)
		{
			MFUtil::ShowMessage(TEXT("CreateAttributes Failed."), ML_ERROR);
			this->ReleaseDevices();
			return false;
		}

		hr = pAttributes->SetUnknown(MF_SOURCE_READER_ASYNC_CALLBACK, this->CallBack);
		if (hr != S_OK)
		{
			MFUtil::ShowMessage(TEXT("AttributeSetting Failed."), ML_ERROR);
			this->ReleaseDevices();
			return false;
		}

		pin_ptr<IMFSourceReader *> pSourceReader = &(this->SourceReader);
		hr = MFCreateSourceReaderFromMediaSource(this->Source, pAttributes, pSourceReader);
		if (hr != S_OK)
		{
			MFUtil::ShowMessage(TEXT("CreateSourceReader Failed."), ML_ERROR);
			this->ReleaseDevices();
			return false;
		}

		hr = this->ConfigureSourceReader();
		if (hr != S_OK)
		{
			MFUtil::ShowMessage(TEXT("ConfigureDecoder Failed."), ML_ERROR);
			MFUtil::ShowErrorNameFromCode(hr);
			return false;
		}

		// 二回目以降の ReadSample() はコールバック内で呼ぶため、
		// SourceReaderCallBack クラスにも SourceReader が必要。
		this->CallBack->SourceReader = this->SourceReader;

		return true;
	}
Beispiel #11
0
void GetCaptureDeviceName(int aDevice, char * aNamebuffer, int aBufferlength)
{
	int i;
	if (!aNamebuffer || aBufferlength <= 0)
		return;

	aNamebuffer[0] = 0;

	HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

	if (FAILED(hr)) return;

	hr = MFStartup(MF_VERSION);

	if (FAILED(hr)) return;

	// choose device
	IMFAttributes *attributes = NULL;
	hr = MFCreateAttributes(&attributes, 1);
	ScopedRelease<IMFAttributes> attributes_s(attributes);

	if (FAILED(hr)) return;

	hr = attributes->SetGUID(
		MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
		MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
		);

	if (FAILED(hr)) return;

	ChooseDeviceParam param = { 0 };
	hr = MFEnumDeviceSources(attributes, &param.mDevices, &param.mCount);

	if (FAILED(hr)) return;

	if (aDevice < (signed)param.mCount)
	{
		WCHAR *name = 0;
		UINT32 namelen = 255;
		hr = param.mDevices[aDevice]->GetAllocatedString(
			MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME,
			&name,
			&namelen
			);
		if (SUCCEEDED(hr) && name)
		{
			i = 0;
			while (i < aBufferlength - 1 && i < (signed)namelen && name[i] != 0)
			{
				aNamebuffer[i] = (char)name[i];
				i++;
			}
			aNamebuffer[i] = 0;

			CoTaskMemFree(name);
		}
	}
}
HRESULT CTranscoder::ConfigureVideoOutput()
{
    assert (m_pProfile);

    HRESULT hr = S_OK;

    IMFAttributes* pVideoAttrs = NULL;

    // Configure the video stream

    // Create a new attribute store.
    if (SUCCEEDED(hr))
    {
        hr = MFCreateAttributes( &pVideoAttrs, 5 );
    }

    // Set the encoder to be Windows Media video encoder, so that the appropriate MFTs are added to the topology.
    if (SUCCEEDED(hr))
    {
        hr = pVideoAttrs->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_WMV3);
    }

    // Set the frame rate.
    if (SUCCEEDED(hr))
    {
        hr = MFSetAttributeRatio(pVideoAttrs, MF_MT_FRAME_RATE, 30, 1);
    }

    //Set the frame size.
    if (SUCCEEDED(hr))
    {
        hr = MFSetAttributeSize(pVideoAttrs, MF_MT_FRAME_SIZE, 320, 240);   
    }

    //Set the pixel aspect ratio
    if (SUCCEEDED(hr))
    {
        hr = MFSetAttributeRatio(pVideoAttrs, MF_MT_PIXEL_ASPECT_RATIO, 1, 1);
    }

    // Set the bit rate.
    if (SUCCEEDED(hr))
    {
        hr = pVideoAttrs->SetUINT32(MF_MT_AVG_BITRATE, 300000);
    }

    // Set the attribute store on the transcode profile.
    if (SUCCEEDED(hr))
    {
        hr = m_pProfile->SetVideoAttributes( pVideoAttrs );
    }

    SafeRelease(&pVideoAttrs);
    return hr;
}
Beispiel #13
0
    void MFPlayer::init(const OTextureRef& pRenderTarget)
    {
        m_pRenderTarget = pRenderTarget;
        auto pRendererD3D11 = std::dynamic_pointer_cast<ORendererD3D11>(oRenderer);

        HRESULT ret;

        // Initialize M$ bullshit
        //ret = CoInitializeEx(NULL, COINIT_MULTITHREADED);
        //assert(ret == S_OK);
        ret = MFStartup(MF_VERSION);
        assert(ret == S_OK);

        // Create factory
        IMFMediaEngineClassFactory *pMediaEngineClassFactory = nullptr;
        ret = CoCreateInstance(CLSID_MFMediaEngineClassFactory, nullptr, CLSCTX_ALL, IID_PPV_ARGS(&pMediaEngineClassFactory));
        assert(ret == S_OK);

        // Create notify
        m_pPlayerNodify = new MFPlayerNotify(shared_from_this());

        // Create attributes
        IMFAttributes *pAttributes = nullptr;
        ret = MFCreateAttributes(&pAttributes, 1);
        assert(ret == S_OK);
        ret = pAttributes->SetUnknown(MF_MEDIA_ENGINE_CALLBACK, m_pPlayerNodify);
        assert(ret == S_OK);

        ID3D10Multithread *pMultithread = nullptr;
        ID3D11Device *pDevice = pRendererD3D11->getDevice();
        ret = pDevice->QueryInterface(IID_PPV_ARGS(&pMultithread));
        assert(ret == S_OK);
        pMultithread->SetMultithreadProtected(TRUE);
        pMultithread->Release();

        UINT resetToken = 0;
        ret = MFCreateDXGIDeviceManager(&resetToken, &m_pDXGIManager);
        assert(ret == S_OK);
        ret = m_pDXGIManager->ResetDevice(pRendererD3D11->getDevice(), resetToken);
        assert(ret == S_OK);
        ret = pAttributes->SetUnknown(MF_MEDIA_ENGINE_DXGI_MANAGER, m_pDXGIManager);
        assert(ret == S_OK);

        ret = pAttributes->SetUINT32(MF_MEDIA_ENGINE_VIDEO_OUTPUT_FORMAT, DXGI_FORMAT_R8G8B8A8_UNORM);
        assert(ret == S_OK);

        // Create player
        ret = pMediaEngineClassFactory->CreateInstance(MF_MEDIA_ENGINE_WAITFORSTABLE_STATE, pAttributes, &m_pMediaEngine);
        assert(ret == S_OK);

        // Release bullshits
        pAttributes->Release();
        pMediaEngineClassFactory->Release();
    }
HRESULT ConfigureAudioEncoding(IMFCaptureSource *pSource, IMFCaptureRecordSink *pRecord, REFGUID guidEncodingType)
{
    IMFCollection *pAvailableTypes = NULL;
    IMFMediaType *pMediaType = NULL;
    IMFAttributes *pAttributes = NULL;

    // Configure the audio format for the recording sink.

    HRESULT hr = MFCreateAttributes(&pAttributes, 1);
    if(FAILED(hr))
    {
        goto done;
    }

    // Enumerate low latency media types
    hr = pAttributes->SetUINT32(MF_LOW_LATENCY, TRUE);
    if(FAILED(hr))
    {
        goto done;
    }


    // Get a list of encoded output formats that are supported by the encoder.
    hr = MFTranscodeGetAudioOutputAvailableTypes(guidEncodingType, MFT_ENUM_FLAG_ALL | MFT_ENUM_FLAG_SORTANDFILTER,
        pAttributes, &pAvailableTypes);
    if (FAILED(hr))
    {
        goto done;
    }

    // Pick the first format from the list.
    hr = GetCollectionObject(pAvailableTypes, 0, &pMediaType); 
    if (FAILED(hr))
    {
        goto done;
    }

    // Connect the audio stream to the recording sink.
    DWORD dwSinkStreamIndex;
    hr = pRecord->AddStream((DWORD)MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_AUDIO, pMediaType, NULL, &dwSinkStreamIndex);
    if(hr == MF_E_INVALIDSTREAMNUMBER)
    {
        //If an audio device is not present, allow video only recording
        hr = S_OK;
    }
done:
    SafeRelease(&pAvailableTypes);
    SafeRelease(&pMediaType);
    SafeRelease(&pAttributes);
    return hr;
}
/*static */ComPtr_t<IMFAttributes> MFMovieSource::CreateSourceReaderAttribute()
{
  ComPtr_t<IMFAttributes> attr;
  MFCreateAttributes( &attr, 0 );
  // https://msdn.microsoft.com/ja-jp/library/windows/desktop/dd757760(v=vs.85).aspx
  //
  attr->SetUINT32( MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, TRUE );

  // https://msdn.microsoft.com/ja-jp/library/windows/desktop/dd375764(v=vs.85).aspx
  //
  attr->SetUINT32( MF_READWRITE_DISABLE_CONVERTERS, FALSE );
  // https://msdn.microsoft.com/ja-jp/library/windows/desktop/dd375772(v=vs.85).aspx
  //
  //attr->SetUINT32( MF_SOURCE_READER_D3D_MANAGER, FALSE );
  return std::move( attr );
}
Beispiel #16
0
IMFActivate* WinCaptureDevice::ChooseFirst(std::string& error)
{
	IMFActivate* result = NULL;
	HRESULT hr = S_OK;
	UINT iDevice = 0;   // Index into the array of devices
	BOOL bCancel = FALSE;

	// Initialize an attribute store to specify enumeration parameters.
	IMFAttributes* pAttributes = NULL;
	hr = MFCreateAttributes(&pAttributes, 1);

	if (FAILED(hr)) { goto done; }

	// Ask for source type = video capture devices.

	hr = pAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);

	if (FAILED(hr)) { goto done; }

	// Enumerate devices.
	IMFActivate **devices = NULL;
	uint numDevices = 0;
	hr = MFEnumDeviceSources(pAttributes, &devices, &numDevices);

	if (FAILED(hr)) { goto done; }

	if (numDevices > 0)
		result = devices[0];

done:

	SafeRelease(&pAttributes);

	for (uint i = 0; i < numDevices; i++)
	{
		if (devices[i] != result)
			SafeRelease(&devices[i]);
	}
	CoTaskMemFree(devices);

	if (FAILED(hr))
	{
		//ShowErrorMessage(L"Cannot create a video capture device", hr);
	}

	return result;
}
Beispiel #17
0
HRESULT CMFCamCapture::enumVideoDevices()
{
    IMFAttributes *pAttributes = NULL;
    IMFActivate **ppDevices = NULL;

    // Create an attribute store to specify the enumeration parameters.
    HRESULT hr = MFCreateAttributes(&pAttributes, 1);
    if (FAILED(hr)) {
        goto done;
    }

    // Source type: video capture devices
    hr = pAttributes->SetGUID(
        MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
        MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
        );
    if (FAILED(hr)) {
        goto done;
    }

    // Enumerate devices.
    UINT32 count;
    hr = MFEnumDeviceSources(pAttributes, &ppDevices, &count);
    if (FAILED(hr)) {
        goto done;
    }

    if (count == 0) {
        hr = E_FAIL;
        goto done;
    }

    // cache the devices.
    m_deviceActivateObjects.clear();
    for (DWORD i = 0; i < count; i++) {
        m_deviceActivateObjects.push_back(CComPtr<IMFActivate>(ppDevices[i]));
    }
    
done:
    SafeRelease(&pAttributes);
    for (DWORD i = 0; i < count; i++) {
        SafeRelease(&ppDevices[i]);
    }
    CoTaskMemFree(ppDevices);
    return hr;
}
HRESULT CTedPlayer::InitProtected()
{
    HRESULT hr;
    
    if(m_spSession)
    {
        if(m_bIsPlaying)
        {
            m_bIsPlaying = false;
            m_spSession->Stop();
        }
        
        m_spSession.Release();
    }

    if(m_fPendingProtectedCustomTopoloader && m_spProtectedSession.p)
    {
        m_spProtectedSession->Shutdown();
        m_spProtectedSession.Release();
    }

    if(m_spProtectedSession.p == NULL)
    {
        CComPtr<IMFAttributes> spAttr;
        IFC( MFCreateAttributes(&spAttr, 1) );          
        IFC( spAttr->SetUnknown(MF_SESSION_CONTENT_PROTECTION_MANAGER, m_pCPM) );

        if(m_fPendingProtectedCustomTopoloader && GUID_NULL != m_gidCustomTopoloader)
        {
            IFC( spAttr->SetGUID(MF_SESSION_TOPOLOADER, m_gidCustomTopoloader) );
        }

        IFC( MFCreatePMPMediaSession( 0, spAttr, &m_spProtectedSession, NULL ) );
        
        IFC( m_spProtectedSession->BeginGetEvent(&m_xOnProtectedSessionEvent, NULL) );

        m_fPendingProtectedCustomTopoloader = false;
    }
    
    m_spSession = m_spProtectedSession;
    
    IFC( InitFromSession() );
    
Cleanup:
    return hr;
}
Beispiel #19
0
	audio_reader::audio_reader(std::wstring& source)
	{
		{
			IMFByteStreamPtr stream;
			CHK(MFCreateFile(MF_FILE_ACCESSMODE::MF_ACCESSMODE_READ, MF_FILE_OPENMODE::MF_OPENMODE_FAIL_IF_NOT_EXIST, MF_FILE_FLAGS::MF_FILEFLAGS_NONE, source.c_str(), &stream));

			IMFAttributesPtr attr;
			CHK(MFCreateAttributes(&attr, 10));
			CHK(attr->SetUINT32(MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, true));
			IMFSourceReaderPtr reader;
			CHK(MFCreateSourceReaderFromByteStream(stream.Get(), attr.Get(), &reader));

			//      CHK(MFCreateSourceReaderFromURL(source.c_str(),attr.Get(), &reader));
			CHK(reader.As(&reader_));
			QWORD length;
			CHK(stream->GetLength(&length));
			fileSize_ = length;
		}

		//CHK(reader_->GetServiceForStream(0, MF_WRAPPED_OBJECT, __uuidof(IMFByteStream), &stream));

		CHK(reader_->GetNativeMediaType(0, 0, &native_media_type_));
		CHK(MFCreateMediaType(&current_media_type_));
		CHK(current_media_type_->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio));
		CHK(current_media_type_->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM));
		CHK(current_media_type_->SetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE,
			MFGetAttributeUINT32(native_media_type_.Get(), MF_MT_AUDIO_BITS_PER_SAMPLE, bits_per_sample)
			)
			);
		CHK(current_media_type_->SetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND,
			MFGetAttributeUINT32(native_media_type_.Get(), MF_MT_AUDIO_SAMPLES_PER_SECOND, samples_per_second)
			));
		CHK(current_media_type_->SetUINT32(MF_MT_AUDIO_NUM_CHANNELS,
			MFGetAttributeUINT32(native_media_type_.Get(), MF_MT_AUDIO_NUM_CHANNELS, channel_count)
			));
		//DWORD blockAlign;
		//CHK(native_media_type_->GetUINT32(MF_MT_AUDIO_BLOCK_ALIGNMENT, &blockAlign));
		//CHK(current_media_type_->SetUINT32(MF_MT_AUDIO_BLOCK_ALIGNMENT,blockAlign ));
		CHK(reader_->SetCurrentMediaType(0, nullptr, current_media_type_.Get()));
		CHK(reader_->GetCurrentMediaType(0, current_media_type_.ReleaseAndGetAddressOf()));
		UINT32 blockAlign;
		CHK(current_media_type_->GetUINT32(MF_MT_AUDIO_BLOCK_ALIGNMENT, &blockAlign));

		DOUT(boost::wformat(L"Block Align: %10d %10x") % blockAlign % blockAlign);

	}
IMFMediaType* MFDecoderSourceReader::setSource(IMFMediaSource *source, const QAudioFormat &audioFormat)
{
    IMFMediaType *mediaType = NULL;
    if (m_source == source)
        return mediaType;
    if (m_source) {
        m_source->Release();
        m_source = NULL;
    }
    if (m_sourceReader) {
        m_sourceReader->Release();
        m_sourceReader = NULL;
    }
    if (!source)
        return mediaType;
    IMFAttributes *attr = NULL;
    MFCreateAttributes(&attr, 1);
    if (SUCCEEDED(attr->SetUnknown(MF_SOURCE_READER_ASYNC_CALLBACK, this))) {
        if (SUCCEEDED(MFCreateSourceReaderFromMediaSource(source, attr, &m_sourceReader))) {
            m_source = source;
            m_source->AddRef();
            m_sourceReader->SetStreamSelection(DWORD(MF_SOURCE_READER_ALL_STREAMS), FALSE);
            m_sourceReader->SetStreamSelection(DWORD(MF_SOURCE_READER_FIRST_AUDIO_STREAM), TRUE);
            IMFMediaType *pPartialType = NULL;
            MFCreateMediaType(&pPartialType);
            pPartialType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio);

            if (audioFormat.sampleType() == QAudioFormat::Float) {
                pPartialType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_Float);
            } else {
                pPartialType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM);
            }

            m_sourceReader->SetCurrentMediaType(DWORD(MF_SOURCE_READER_FIRST_AUDIO_STREAM), NULL, pPartialType);
            pPartialType->Release();
            m_sourceReader->GetCurrentMediaType(DWORD(MF_SOURCE_READER_FIRST_AUDIO_STREAM), &mediaType);
            // Ensure the stream is selected.
            m_sourceReader->SetStreamSelection(DWORD(MF_SOURCE_READER_FIRST_AUDIO_STREAM), TRUE);
        }
        attr->Release();
    }
    return mediaType;
}
HRESULT CTedPlayer::InitClear()
{
    HRESULT hr;
    
    if(m_spSession)
    {
        if(m_bIsPlaying)
        {
            m_bIsPlaying = false;
            m_spSession->Stop();
        }
        
        m_spSession.Release();
    }
    
	if(m_fPendingClearCustomTopoloader && m_spClearSession.p)
	{
        m_spClearSession->Shutdown();
        m_spClearSession.Release();
	}

    if(m_spClearSession.p == NULL)
    {
        CComPtr<IMFAttributes> spConfiguration = NULL;
        if(m_fPendingClearCustomTopoloader && GUID_NULL != m_gidCustomTopoloader)
        {
            IFC( MFCreateAttributes(&spConfiguration, 1) );
            IFC( spConfiguration->SetGUID(MF_SESSION_TOPOLOADER, m_gidCustomTopoloader) );
        }

        IFC( MFCreateMediaSession(spConfiguration, &m_spClearSession) );
        IFC( m_spClearSession->BeginGetEvent(&m_xOnClearSessionEvent, NULL) );

        m_fPendingClearCustomTopoloader = false;
    }
    
    m_spSession = m_spClearSession;
    
    IFC( InitFromSession() );
    
Cleanup:
    return hr;
}
HRESULT CTranscoder::ConfigureContainer()
{
    assert (m_pProfile);
    
    HRESULT hr = S_OK;
    
    IMFAttributes* pContainerAttrs = NULL;

    //Set container attributes
    hr = MFCreateAttributes( &pContainerAttrs, 2 );

    //Set the output container to be ASF type
    if (SUCCEEDED(hr))
    {
        hr = pContainerAttrs->SetGUID(
            MF_TRANSCODE_CONTAINERTYPE, 
            MFTranscodeContainerType_ASF
            );
    }

    // Use the default setting. Media Foundation will use the stream 
    // settings set in ConfigureAudioOutput and ConfigureVideoOutput.

    if (SUCCEEDED(hr))
    {
        hr = pContainerAttrs->SetUINT32(
            MF_TRANSCODE_ADJUST_PROFILE, 
            MF_TRANSCODE_ADJUST_PROFILE_DEFAULT
            );
    }

    //Set the attribute store on the transcode profile.
    if (SUCCEEDED(hr))
    {
        hr = m_pProfile->SetContainerAttributes(pContainerAttrs);
    }

    SafeRelease(&pContainerAttrs);
    return hr;
}
Beispiel #23
0
static void test_MFCreateAttributes(void)
{
    IMFAttributes *attributes;
    HRESULT hr;
    UINT32 count;

    hr = MFCreateAttributes( &attributes, 3 );
    ok(hr == S_OK, "got 0x%08x\n", hr);

    count = 88;
    hr = IMFAttributes_GetCount(attributes, &count);
    todo_wine ok(hr == S_OK, "got 0x%08x\n", hr);
    ok(count == 0, "got %d\n", count);

    hr = IMFAttributes_SetUINT32(attributes, &MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, 0);
    todo_wine ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IMFAttributes_GetCount(attributes, &count);
    todo_wine ok(hr == S_OK, "got 0x%08x\n", hr);
    todo_wine ok(count == 1, "got %d\n", count);

    IMFAttributes_Release(attributes);
}
Beispiel #24
0
    void GetCameraDevices(IMFActivate*** pppDevices, UINT32* pnCount)
    {
        HRESULT hr = S_OK;
        IMFAttributes* pAttributes = NULL;
        WCHAR* pszFriendlyName = NULL;
        UINT32 cchName = 0;

        hr = MFCreateAttributes(&pAttributes, 1);
        if (FAILED(hr))
            goto END;

        hr = pAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
        if (FAILED(hr))
            goto END;

        hr = MFEnumDeviceSources(pAttributes, pppDevices, pnCount);
        if (FAILED(hr))
            goto END;

END:
        SafeRelease(&pAttributes);

        return;
    }
  //----------------------------------------------------------------------------
  long MediaFoundationVideoDevice::InitDevice()
  {
    HRESULT hr = S_OK;
    IMFAttributes *pAttributes = NULL;
    IMFActivate * vd_pActivate = NULL;
    CoInitialize(NULL);

    if (SUCCEEDED(hr))
    {
      hr = MFCreateAttributes(&pAttributes, 1);
    }
    if (SUCCEEDED(hr))
    {
      hr = pAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
      if (!SUCCEEDED(hr))
      {
        LOG_ERROR("MediaFoundationVideoDevice::InitDevice failed: device  " << this->DeviceIndex << ": The attribute of the capture device cannot be retrieved");
      }
    }
    if (SUCCEEDED(hr))
    {
      hr = CheckDevice(pAttributes, &vd_pActivate);
      if (SUCCEEDED(hr) && vd_pActivate)
      {
        SafeRelease(&this->Source);
        hr = vd_pActivate->ActivateObject(__uuidof(IMFMediaSource), (void**)&this->Source);
        SafeRelease(&vd_pActivate);
      }
      else
      {
        LOG_ERROR("MediaFoundationVideoDevice::InitDevice failed: device  " << this->DeviceIndex << ": Cannot activate device");
      }
    }
    SafeRelease(&pAttributes);
    return hr;
  }
HRESULT
CaptureManager::InitializeCaptureManager(HWND hwndPreview, IUnknown* pUnk)
{
    HRESULT                         hr = S_OK;
    IMFAttributes*                  pAttributes = NULL;
    IMFCaptureEngineClassFactory*   pFactory = NULL;

    DestroyCaptureEngine();

    m_hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (NULL == m_hEvent)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        goto Exit;
    }

    m_pCallback = new (std::nothrow) CaptureEngineCB(m_hwndEvent);
    if (m_pCallback == NULL)
    {
        hr = E_OUTOFMEMORY;
        goto Exit;
    }

    m_pCallback->m_pManager = this;
    m_hwndPreview = hwndPreview;

    //Create a D3D Manager
    hr = CreateD3DManager();
    if (FAILED(hr))
    {
        goto Exit;
    }
    hr = MFCreateAttributes(&pAttributes, 1); 
    if (FAILED(hr))
    {
        goto Exit;
    }
    hr = pAttributes->SetUnknown(MF_CAPTURE_ENGINE_D3D_MANAGER, g_pDXGIMan);
    if (FAILED(hr))
    {
        goto Exit;
    }

    // Create the factory object for the capture engine.
    hr = CoCreateInstance(CLSID_MFCaptureEngineClassFactory, NULL, 
        CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pFactory));
    if (FAILED(hr))
    {
        goto Exit;
    }

    // Create and initialize the capture engine.
    hr = pFactory->CreateInstance(CLSID_MFCaptureEngine, IID_PPV_ARGS(&m_pEngine));
    if (FAILED(hr))
    {
        goto Exit;
    }
    hr = m_pEngine->Initialize(m_pCallback, pAttributes, NULL, pUnk);
    if (FAILED(hr))
    {
        goto Exit;
    }

Exit:
    if (NULL != pAttributes)
    {
        pAttributes->Release();
        pAttributes = NULL;
    }
    if (NULL != pFactory)
    {
        pFactory->Release();
        pFactory = NULL;
    }
    return hr;
}
Beispiel #27
0
HRESULT InitMFStreamer()
{
	printf("InitMFStreamer.\n");

	CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

	CHECK_HR(InitVPXEncoder(&_vpxConfig, &_vpxCodec, WIDTH, HEIGHT), L"Failed to intialise the VPX encoder.\n");

	// Create an attribute store to hold the search criteria.
	CHECK_HR(MFCreateAttributes(&videoConfig, 1), L"Error creating video configuation.");
	//CHECK_HR(MFCreateAttributes(&audioConfig, 1), L"Error creating audio configuation.");;

	// Request video capture devices.
	CHECK_HR(videoConfig->SetGUID(
		MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
		MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID), L"Error initialising video configuration object.");

	// Request audio capture devices.
	/*CHECK_HR(audioConfig->SetGUID(
	MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
	MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_GUID), L"Error initialising audio configuration object.");*/

	// Enumerate the devices,
	CHECK_HR(MFEnumDeviceSources(videoConfig, &videoDevices, &videoDeviceCount), L"Error enumerating video devices.");
	//CHECK_HR(MFEnumDeviceSources(audioConfig, &audioDevices, &audioDeviceCount), L"Error enumerating audio devices.");

	//printf("Video device Count: %i, Audio device count: %i.\n", videoDeviceCount, audioDeviceCount);
	printf("Video device Count: %i.\n", videoDeviceCount);

	CHECK_HR(videoDevices[0]->ActivateObject(IID_PPV_ARGS(&videoSource)), L"Error activating video device.");
	//CHECK_HR(audioDevices[0]->ActivateObject(IID_PPV_ARGS(&audioSource)), L"Error activating audio device.");

	// Initialize the Media Foundation platform.
	CHECK_HR(MFStartup(MF_VERSION), L"Error on Media Foundation startup.");

	/*WCHAR *pwszFileName = L"sample.mp4";
	IMFSinkWriter *pWriter;*/

	/*CHECK_HR(MFCreateSinkWriterFromURL(
	pwszFileName,
	NULL,
	NULL,
	&pWriter), L"Error creating mp4 sink writer.");*/

	// Create the source readers.
	CHECK_HR(MFCreateSourceReaderFromMediaSource(
		videoSource,
		videoConfig,
		&videoReader), L"Error creating video source reader.");

	//ListModes(videoReader);

	/*CHECK_HR(MFCreateSourceReaderFromMediaSource(
	audioSource,
	audioConfig,
	&audioReader), L"Error creating audio source reader.");*/

	FindVideoMode(videoReader, MF_INPUT_FORMAT, WIDTH, HEIGHT, desiredInputVideoType);

	if (desiredInputVideoType == NULL) {
		printf("The specified media type could not be found for the MF video reader.\n");
	}
	else {
		CHECK_HR(videoReader->SetCurrentMediaType((DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, NULL, desiredInputVideoType),
			L"Error setting video reader media type.\n");

		CHECK_HR(videoReader->GetCurrentMediaType(
			(DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,
			&videoType), L"Error retrieving current media type from first video stream.");
		CMediaTypeTrace *videoTypeMediaTrace = new CMediaTypeTrace(videoType);

		printf("Video input media type: %s.\n", videoTypeMediaTrace->GetString());

		LONG pStride = 0;
		GetDefaultStride(videoType, &pStride);
		printf("Stride %i.\n", pStride);
			
		/*printf("Press any key to continue...");
		getchar();*/

		/*audioReader->GetCurrentMediaType(
		(DWORD)MF_SOURCE_READER_FIRST_AUDIO_STREAM,
		&audioType);*/
		//CMediaTypeTrace *audioTypeMediaTrace = new CMediaTypeTrace(audioType);
		//printf("Audio input media type: %s.\n", audioTypeMediaTrace->GetString());

		//printf("Configuring H.264 sink.\n");

		// Set up the H.264 sink.
		/*CHECK_HR(ConfigureEncoder(videoType, &videoStreamIndex, &audioStreamIndex, pWriter), L"Error configuring encoder.");
		printf("Video stream index %i, audio stream index %i.\n", videoStreamIndex, audioStreamIndex);*/

		// Register the color converter DSP for this process, in the video 
		// processor category. This will enable the sink writer to enumerate
		// the color converter when the sink writer attempts to match the
		// media types.
		CHECK_HR(MFTRegisterLocalByCLSID(
			__uuidof(CColorConvertDMO),
			MFT_CATEGORY_VIDEO_PROCESSOR,
			L"",
			MFT_ENUM_FLAG_SYNCMFT,
			0,
			NULL,
			0,
			NULL
			), L"Error registering colour converter DSP.");

		// Add the input types to the H.264 sink writer.
		/*CHECK_HR(pWriter->SetInputMediaType(videoStreamIndex, videoType, NULL), L"Error setting the sink writer video input type.");
		videoType->Release();
		CHECK_HR(pWriter->SetInputMediaType(audioStreamIndex, audioType, NULL), L"Error setting the sink writer audio input type.");
		audioType->Release();*/

		//CHECK_HR(pWriter->BeginWriting(), L"Failed to begin writing on the H.264 sink.");

		//InitializeCriticalSection(&critsec);
	}
}
Beispiel #28
0
unsigned char *BBWin8Game::LoadAudioData( String path,int *length,int *channels,int *format,int *hertz ){

	String url=PathToFilePath( path );
	
	DXASS( MFStartup( MF_VERSION ) );
	
	IMFAttributes *attrs;
	DXASS( MFCreateAttributes( &attrs,1 ) );
	DXASS( attrs->SetUINT32( MF_LOW_LATENCY,TRUE ) );
	
	IMFSourceReader *reader;
	DXASS( MFCreateSourceReaderFromURL( url.ToCString<wchar_t>(),attrs,&reader ) );
	
	attrs->Release();

	IMFMediaType *mediaType;
	DXASS( MFCreateMediaType( &mediaType ) );
	DXASS( mediaType->SetGUID( MF_MT_MAJOR_TYPE,MFMediaType_Audio ) );
	DXASS( mediaType->SetGUID( MF_MT_SUBTYPE,MFAudioFormat_PCM ) );

	DXASS( reader->SetCurrentMediaType( MF_SOURCE_READER_FIRST_AUDIO_STREAM,0,mediaType ) );
    
	mediaType->Release();

	IMFMediaType *outputMediaType;
	DXASS( reader->GetCurrentMediaType( MF_SOURCE_READER_FIRST_AUDIO_STREAM,&outputMediaType ) );
	
	WAVEFORMATEX *wformat;
	uint32 formatByteCount=0;
	DXASS( MFCreateWaveFormatExFromMFMediaType( outputMediaType,&wformat,&formatByteCount ) );

	*channels=wformat->nChannels;
	*format=wformat->wBitsPerSample/8;
	*hertz=wformat->nSamplesPerSec;

	CoTaskMemFree( wformat );
    
	outputMediaType->Release();
/*    
	PROPVARIANT var;
	DXASS( reader->GetPresentationAttribute( MF_SOURCE_READER_MEDIASOURCE,MF_PD_DURATION,&var ) );
	LONGLONG duration=var.uhVal.QuadPart;
	float64 durationInSeconds=(duration / (float64)(10000 * 1000));
	m_maxStreamLengthInBytes=(uint32)( durationInSeconds * m_waveFormat.nAvgBytesPerSec );
*/
	std::vector<unsigned char*> bufs;
	std::vector<uint32> lens;
	uint32 len=0;
    
	for( ;; ){
		uint32 flags=0;
		IMFSample *sample;
		DXASS( reader->ReadSample( MF_SOURCE_READER_FIRST_AUDIO_STREAM,0,0,reinterpret_cast<DWORD*>(&flags),0,&sample ) );
		
		if( flags & MF_SOURCE_READERF_ENDOFSTREAM ){
			break;
		}
		if( sample==0 ){ 
			abort();
		}
		
		IMFMediaBuffer *mediaBuffer;
		DXASS( sample->ConvertToContiguousBuffer( &mediaBuffer ) );

		uint8 *audioData=0;
		uint32 sampleBufferLength=0;
		DXASS( mediaBuffer->Lock( &audioData,0,reinterpret_cast<DWORD*>( &sampleBufferLength ) ) );
		
		unsigned char *buf=(unsigned char*)malloc( sampleBufferLength );
		memcpy( buf,audioData,sampleBufferLength );
		
		bufs.push_back( buf );
		lens.push_back( sampleBufferLength );
		len+=sampleBufferLength;
		
		DXASS( mediaBuffer->Unlock() );
		mediaBuffer->Release();
		
		sample->Release();
	}
	
	reader->Release();
	
	*length=len/(*channels * *format);

	unsigned char *data=(unsigned char*)malloc( len );
	unsigned char *p=data;
	
	for( int i=0;i<bufs.size();++i ){
		memcpy( p,bufs[i],lens[i] );
		free( bufs[i] );
		p+=lens[i];
	}
	
	gc_force_sweep=true;
	
	return data;
}	
Beispiel #29
0
HRESULT CaptureClass::initCapture(int aDevice)
{
	mWhoAmI = aDevice;
	HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

	DO_OR_DIE;

	hr = MFStartup(MF_VERSION);

	DO_OR_DIE;

	// choose device
	IMFAttributes *attributes = NULL;
	hr = MFCreateAttributes(&attributes, 1);
	ScopedRelease<IMFAttributes> attributes_s(attributes);

	DO_OR_DIE;

	hr = attributes->SetGUID(
		MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
		MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
		);

	DO_OR_DIE;

	ChooseDeviceParam param = { 0 };
	hr = MFEnumDeviceSources(attributes, &param.mDevices, &param.mCount);

	DO_OR_DIE;

	if ((signed)param.mCount > aDevice)
	{
		// use param.ppDevices[0]
		IMFAttributes   *attributes = NULL;
		IMFMediaType    *type = NULL;
		EnterCriticalSection(&mCritsec);

		hr = param.mDevices[aDevice]->ActivateObject(
			__uuidof(IMFMediaSource),
			(void**)&mSource
			);

		DO_OR_DIE_CRITSECTION;

		hr = MFCreateAttributes(&attributes, 3);
		ScopedRelease<IMFAttributes> attributes_s(attributes);

		DO_OR_DIE_CRITSECTION;

		hr = attributes->SetUINT32(MF_READWRITE_DISABLE_CONVERTERS, TRUE);

		DO_OR_DIE_CRITSECTION;

		hr = attributes->SetUnknown(
			MF_SOURCE_READER_ASYNC_CALLBACK,
			this
			);

		DO_OR_DIE_CRITSECTION;

		hr = MFCreateSourceReaderFromMediaSource(
			mSource,
			attributes,
			&mReader
			);

		DO_OR_DIE_CRITSECTION;

		int preferredmode = scanMediaTypes(gParams[mWhoAmI].mWidth, gParams[mWhoAmI].mHeight);
		mUsedIndex = preferredmode;

		hr = mReader->GetNativeMediaType(
			(DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,
			preferredmode,
			&type
			);
		ScopedRelease<IMFMediaType> type_s(type);

		DO_OR_DIE_CRITSECTION;

		hr = setVideoType(type);

		DO_OR_DIE_CRITSECTION;

		hr = mReader->SetCurrentMediaType(
			(DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,
			NULL,
			type
			);

		DO_OR_DIE_CRITSECTION;

		hr = mReader->ReadSample(
			(DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,
			0,
			NULL,
			NULL,
			NULL,
			NULL
			);

		DO_OR_DIE_CRITSECTION;

		LeaveCriticalSection(&mCritsec);
	}
	else
	{
		return MF_E_INVALIDINDEX;
	}

	/*
	for (i = 0; i < 16; i++)
	{
	char temp[128];
	float v;
	int f;
	int r = GetProperty(i, v, f);
	sprintf(temp, "%d: %3.3f %d (%d)\n", i, v, f, r);
	OutputDebugStringA(temp);
	}
	*/

	return 0;
}
Beispiel #30
0
camera_t * camera_open(const char *portname, int highres)
{
	camera_internal_t *camera = (camera_internal_t*)malloc(sizeof(camera_internal_t));
	camera->reader = NULL;

	if (highres)
	{
		console_printf("camera: highres is not supported on windows (yet).\n");
		highres = 0;
	}

	HRESULT hr = S_OK;

	// Initialize Media Foundation
	if (SUCCEEDED(hr))
	{
		hr = MFStartup(MF_VERSION);
	}
	///////////////////////////////////////////
	IMFAttributes *pAttributes = NULL;
	UINT32 m_cDevices = 0;
	IMFActivate **m_ppDevices = NULL;

	// Initialize an attribute store. We will use this to
	// specify the enumeration parameters.

	hr = MFCreateAttributes(&pAttributes, 1);

	// Ask for source type = video capture devices
	if (SUCCEEDED(hr))
	{
		hr = pAttributes->SetGUID(
			MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
			MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
			);
	}

	// Enumerate devices.
	if (SUCCEEDED(hr))
	{
		hr = MFEnumDeviceSources(pAttributes, &m_ppDevices, &m_cDevices);
	}

	SafeRelease(&pAttributes);

	/////////////////////////////////////////////////
	IMFActivate *pActivate = NULL;
	if (m_cDevices)
	{
		console_printf("camera: there are %d camera devices connected (0..%d).\n", m_cDevices, m_cDevices > 0 ? m_cDevices - 1 : 0);
		int device = strtol(portname, 0, 10);
		if (device < 0 || device >= m_cDevices)
			console_printf("camera: device %d does not exist.\n", device);
		else
			pActivate = m_ppDevices[device];
	}
	else
	{
		console_printf("camera: could not find a device\n");
	}
	/////////////////////////////////////////////////

	IMFMediaSource *pSource = NULL;

	//EnterCriticalSection(&m_critsec);

	// Create the media source for the device.
	hr = pActivate->ActivateObject(
		__uuidof(IMFMediaSource),
		(void**)&pSource
		);
	///////////////////////////////////////////

	//IMFAttributes *pAttributes = NULL;

	/*hr = MFCreateAttributes(&pAttributes, 2);

	if (SUCCEEDED(hr))
	{
	hr = pAttributes->SetUnknown(MF_SOURCE_READER_ASYNC_CALLBACK, this);
	}*/

	if (SUCCEEDED(hr))
	{
		hr = MFCreateSourceReaderFromMediaSource(
			pSource,
			NULL,//pAttributes,
			&camera->reader
			);
	}

	//SafeRelease(&pAttributes);

	////////////////////////////////////////////////////
	// The list of acceptable types.
	GUID subtypes[] = {
		MFVideoFormat_NV12, MFVideoFormat_YUY2, MFVideoFormat_UYVY,
		MFVideoFormat_RGB32, MFVideoFormat_RGB24, MFVideoFormat_IYUV
	};

	//HRESULT hr = S_OK;
	BOOL bUseNativeType = FALSE;

	GUID subtype = { 0 };

	IMFMediaType *pType = NULL;

	UINT32 width = 0, height = 0;
	int selectedSubtype = -1;

	// If the source's native format matches any of the formats in
	// the list, prefer the native format.

	// Note: The camera might support multiple output formats,
	// including a range of frame dimensions. The application could
	// provide a list to the user and have the user select the
	// camera's output format. That is outside the scope of this
	// sample, however.

	DWORD selectedStreamIndex = MF_SOURCE_READER_FIRST_VIDEO_STREAM;

	//while (true)
	//{
		hr = camera->reader->GetNativeMediaType(
			selectedStreamIndex,
			0,  // Type index
			&pType
			);

		if (FAILED(hr)) { console_printf("camera: could not get media type\n"); goto done; }

		hr = ::MFGetAttributeSize(pType, MF_MT_FRAME_SIZE, &width, &height);

		if (FAILED(hr)) { console_printf("camera: could not get resolution\n"); goto done; }

		//if (width != 1280 || height != 960)
		//{
			console_printf("camera: found resolution %dx%d\n", width, height);
			//selectedStreamIndex++;
			//continue;
		//}

		camera->size.width = width;
		camera->size.height = height;
		//break;
	//}


	/*UINT32 num = 0, denom = 0;
	hr = ::MFGetAttributeRatio(pType, MF_MT_FRAME_RATE_RANGE_MAX, &num, &denom);

	if (FAILED(hr)) { goto done; }*/

	//hr = ::MFSetAttributeSize(pType, MF_MT_FRAME_SIZE, 1280, 960);

	//if (FAILED(hr)) { goto done; }

	/*hr = ::MFSetAttributeRatio(pType, MF_MT_FRAME_RATE, num, denom);

	if (FAILED(hr)) { goto done; }*/

	hr = pType->GetGUID(MF_MT_SUBTYPE, &subtype);

	if (FAILED(hr)) { console_printf("camera: could not get stream type(1)\n"); goto done; }

	for (UINT32 i = 0; i < ARRAYSIZE(subtypes); i++)
	{
		if (subtype == subtypes[i])
		{
			hr = camera->reader->SetCurrentMediaType(
				(DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,
				NULL,
				pType
				);

			bUseNativeType = TRUE;
			selectedSubtype = i;
			break;
		}
	}

	if (!bUseNativeType)
	{
		// None of the native types worked. The camera might offer
		// output a compressed type such as MJPEG or DV.

		// Try adding a decoder.

		for (UINT32 i = 0; i < ARRAYSIZE(subtypes); i++)
		{
			hr = pType->SetGUID(MF_MT_SUBTYPE, subtypes[i]);

			if (FAILED(hr)) { console_printf("camera: could not get stream type(2)\n"); goto done; }

			hr = camera->reader->SetCurrentMediaType(
				(DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,
				NULL,
				pType
				);

			if (SUCCEEDED(hr))
			{
				selectedSubtype = i;
				break;
			}
		}
	}

/*	hr = ::MFGetAttributeSize(pType, MF_MT_FRAME_SIZE, &width, &height);
	WIDTH = width;
	HEIGHT = height;*/

	if (FAILED(hr)) { console_printf("camera: could not find stream type\n"); goto done; }

done:
	SafeRelease(&pType);

	console_printf("camera: selected type: %d, native: %s, resolution: %dx%d\n",
		selectedSubtype, bUseNativeType ? "yes" : "no", camera->size.width, camera->size.height);

	///////////////////////////////////////
	/*if (SUCCEEDED(hr))
	{
	hr = camera->reader->GetCurrentMediaType(
	(DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,
	&pType
	);
	}

	if (SUCCEEDED(hr))
	{
	// Register the color converter DSP for this process, in the video
	// processor category. This will enable the sink writer to enumerate
	// the color converter when the sink writer attempts to match the
	// media types.

	hr = MFTRegisterLocalByCLSID(
	__uuidof(CColorConvertDMO),
	MFT_CATEGORY_VIDEO_PROCESSOR,
	L"",
	MFT_ENUM_FLAG_SYNCMFT,
	0,
	NULL,
	0,
	NULL
	);
	}*/

	/////////////////////////////////////////////////

/*	IMFSample *pSample = NULL;
	DWORD streamIndex = 0, flags = 0;
	LONGLONG llTimeStamp = 0;

	hr = camera->reader->ReadSample(
		(DWORD)MF_SOURCE_READER_ANY_STREAM,    // Stream index.
		0,                              // Flags.
		&streamIndex,                   // Receives the actual stream index.
		&flags,                         // Receives status flags.
		&llTimeStamp,                   // Receives the time stamp.
		&pSample                        // Receives the sample or NULL.
		);*/

	if (selectedSubtype != 4)
	{
		console_printf("camera: unexpected stream type.\n");
		SafeRelease(&camera->reader);
		free(camera);
		return 0;
	}
	return (camera_t*)camera;
}