提供少量输入样本后,英特尔图形硬件H264 MFT ProcessInput调用失败,在Nvidia硬件MFT上也可以正常工作


9

我正在使用DesktopDuplication API捕获桌面,并将示例从RGBA转换为GPU中的NV12,并将其提供给MediaFoundation硬件H264 MFT。这在Nvidia图形以及软件编码器上都可以正常工作,但是在只有Intel图形硬件MFT可用时失败。如果我退回到Software MFT,该代码在同一台Intel图形计算机上也可以正常工作。我还确保了编码实际上是在Nvidia图形计算机上的硬件中完成的。

在Intel图形上,MFT返回MEError(“未指定错误”),仅在馈入第一个样本后才发生,随后对ProcessInput的调用(当事件生成器触发METransformNeedInput时)返回“被调用方当前不接受进一步的输入”。MFT很少会在返回这些错误之前消耗更多的样本。这种行为令人困惑,仅当事件生成器通过IMFAsyncCallback异步触发METransformNeedInput时,我才提供示例,并且还应检查提供示例后是否立即触发METransformHaveOutput。当相同的异步逻辑与Nvidia硬件MFT和Microsoft软件编码器一起正常工作时,这真让我感到困惑。

也有类似的 英特尔论坛本身未解决问题。我的代码类似于intel线程中提到的代码,除了我还将d3d设备管理器设置为如下所示的编码器这一事实。

并且,还有其他三个堆栈溢出线程报告了类似的问题,但没有给出解决方案(MFTransform编码器-> ProcessInput返回E_FAIL如何从D11纹理为Intel MFT编码器创建IMFSample异步MFT没有发送MFTransformHaveOutput事件(Intel硬件MJPEG解码器MFT))。我尝试了所有可能的选择,对此没有任何改进。

颜色转换器代码取自intel media sdk示例。我也在这里上传了完整的代码。

设置d3d管理器的方法:

void SetD3dManager() {

    HRESULT hr = S_OK;

    if (!deviceManager) {

        // Create device manager
        hr = MFCreateDXGIDeviceManager(&resetToken, &deviceManager);
    }

    if (SUCCEEDED(hr)) 
    {
        if (!pD3dDevice) {

            pD3dDevice = GetDeviceDirect3D(0);
        }
    }

    if (pD3dDevice) {

        // NOTE: Getting ready for multi-threaded operation
        const CComQIPtr<ID3D10Multithread> pMultithread = pD3dDevice;
        pMultithread->SetMultithreadProtected(TRUE);

        hr = deviceManager->ResetDevice(pD3dDevice, resetToken);
        CHECK_HR(_pTransform->ProcessMessage(MFT_MESSAGE_SET_D3D_MANAGER, reinterpret_cast<ULONG_PTR>(deviceManager.p)), "Failed to set device manager.");
    }
    else {
        cout << "Failed to get d3d device";
    }
}

getd3ddevice:

CComPtr<ID3D11Device> GetDeviceDirect3D(UINT idxVideoAdapter)
{
    // Create DXGI factory:
    CComPtr<IDXGIFactory1> dxgiFactory;
    DXGI_ADAPTER_DESC1 dxgiAdapterDesc;

    // Direct3D feature level codes and names:

    struct KeyValPair { int code; const char* name; };

    const KeyValPair d3dFLevelNames[] =
    {
        KeyValPair{ D3D_FEATURE_LEVEL_9_1, "Direct3D 9.1" },
        KeyValPair{ D3D_FEATURE_LEVEL_9_2, "Direct3D 9.2" },
        KeyValPair{ D3D_FEATURE_LEVEL_9_3, "Direct3D 9.3" },
        KeyValPair{ D3D_FEATURE_LEVEL_10_0, "Direct3D 10.0" },
        KeyValPair{ D3D_FEATURE_LEVEL_10_1, "Direct3D 10.1" },
        KeyValPair{ D3D_FEATURE_LEVEL_11_0, "Direct3D 11.0" },
        KeyValPair{ D3D_FEATURE_LEVEL_11_1, "Direct3D 11.1" },
    };

    // Feature levels for Direct3D support
    const D3D_FEATURE_LEVEL d3dFeatureLevels[] =
    {
        D3D_FEATURE_LEVEL_11_1,
        D3D_FEATURE_LEVEL_11_0,
        D3D_FEATURE_LEVEL_10_1,
        D3D_FEATURE_LEVEL_10_0,
        D3D_FEATURE_LEVEL_9_3,
        D3D_FEATURE_LEVEL_9_2,
        D3D_FEATURE_LEVEL_9_1,
    };

    constexpr auto nFeatLevels = static_cast<UINT> ((sizeof d3dFeatureLevels) / sizeof(D3D_FEATURE_LEVEL));

    CComPtr<IDXGIAdapter1> dxgiAdapter;
    D3D_FEATURE_LEVEL featLevelCodeSuccess;
    CComPtr<ID3D11Device> d3dDx11Device;

    std::wstring_convert<std::codecvt_utf8<wchar_t>> transcoder;

    HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory));
    CHECK_HR(hr, "Failed to create DXGI factory");

    // Get a video adapter:
    dxgiFactory->EnumAdapters1(idxVideoAdapter, &dxgiAdapter);

    // Get video adapter description:
    dxgiAdapter->GetDesc1(&dxgiAdapterDesc);

    CHECK_HR(hr, "Failed to retrieve DXGI video adapter description");

    std::cout << "Selected DXGI video adapter is \'"
        << transcoder.to_bytes(dxgiAdapterDesc.Description) << '\'' << std::endl;

    // Create Direct3D device:
    hr = D3D11CreateDevice(
        dxgiAdapter,
        D3D_DRIVER_TYPE_UNKNOWN,
        nullptr,
        (0 * D3D11_CREATE_DEVICE_SINGLETHREADED) | D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
        d3dFeatureLevels,
        nFeatLevels,
        D3D11_SDK_VERSION,
        &d3dDx11Device,
        &featLevelCodeSuccess,
        nullptr
    );

    // Might have failed for lack of Direct3D 11.1 runtime:
    if (hr == E_INVALIDARG)
    {
        // Try again without Direct3D 11.1:
        hr = D3D11CreateDevice(
            dxgiAdapter,
            D3D_DRIVER_TYPE_UNKNOWN,
            nullptr,
            (0 * D3D11_CREATE_DEVICE_SINGLETHREADED) | D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
            d3dFeatureLevels + 1,
            nFeatLevels - 1,
            D3D11_SDK_VERSION,
            &d3dDx11Device,
            &featLevelCodeSuccess,
            nullptr
        );
    }

    // Get name of Direct3D feature level that succeeded upon device creation:
    std::cout << "Hardware device supports " << std::find_if(
        d3dFLevelNames,
        d3dFLevelNames + nFeatLevels,
        [featLevelCodeSuccess](const KeyValPair& entry)
        {
            return entry.code == featLevelCodeSuccess;
        }
    )->name << std::endl;

done:

    return d3dDx11Device;
}

异步回调实现:

struct EncoderCallbacks : IMFAsyncCallback
{
    EncoderCallbacks(IMFTransform* encoder)
    {
        TickEvent = CreateEvent(0, FALSE, FALSE, 0);
        _pEncoder = encoder;
    }

    ~EncoderCallbacks()
    {
        eventGen = nullptr;
        CloseHandle(TickEvent);
    }

    bool Initialize() {

        _pEncoder->QueryInterface(IID_PPV_ARGS(&eventGen));

        if (eventGen) {

            eventGen->BeginGetEvent(this, 0);
            return true;
        }

        return false;
    }

    // dummy IUnknown impl
    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject) override { return E_NOTIMPL; }
    virtual ULONG STDMETHODCALLTYPE AddRef(void) override { return 1; }
    virtual ULONG STDMETHODCALLTYPE Release(void) override { return 1; }

    virtual HRESULT STDMETHODCALLTYPE GetParameters(DWORD* pdwFlags, DWORD* pdwQueue) override
    {
        // we return immediately and don't do anything except signaling another thread
        *pdwFlags = MFASYNC_SIGNAL_CALLBACK;
        *pdwQueue = MFASYNC_CALLBACK_QUEUE_IO;
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE Invoke(IMFAsyncResult* pAsyncResult) override
    {
        IMFMediaEvent* event = 0;
        eventGen->EndGetEvent(pAsyncResult, &event);
        if (event)
        {
            MediaEventType type;
            event->GetType(&type);
            switch (type)
            {
            case METransformNeedInput: InterlockedIncrement(&NeedsInput); break;
            case METransformHaveOutput: InterlockedIncrement(&HasOutput); break;
            }
            event->Release();
            SetEvent(TickEvent);
        }

        eventGen->BeginGetEvent(this, 0);
        return S_OK;
    }

    CComQIPtr<IMFMediaEventGenerator> eventGen = nullptr;
    HANDLE TickEvent;
    IMFTransform* _pEncoder = nullptr;

    unsigned int NeedsInput = 0;
    unsigned int HasOutput = 0;
};

生成样本方法:

bool GenerateSampleAsync() {

    DWORD processOutputStatus = 0;
    HRESULT mftProcessOutput = S_OK;
    bool frameSent = false;

    // Create sample
    CComPtr<IMFSample> currentVideoSample = nullptr;

    MFT_OUTPUT_STREAM_INFO StreamInfo;

    // wait for any callback to come in
    WaitForSingleObject(_pEventCallback->TickEvent, INFINITE);

    while (_pEventCallback->NeedsInput) {

        if (!currentVideoSample) {

            (pDesktopDuplication)->releaseBuffer();
            (pDesktopDuplication)->cleanUpCurrentFrameObjects();

            bool bTimeout = false;

            if (pDesktopDuplication->GetCurrentFrameAsVideoSample((void**)& currentVideoSample, waitTime, bTimeout, deviceRect, deviceRect.Width(), deviceRect.Height())) {

                prevVideoSample = currentVideoSample;
            }
            // Feed the previous sample to the encoder in case of no update in display
            else {
                currentVideoSample = prevVideoSample;
            }
        }

        if (currentVideoSample)
        {
            InterlockedDecrement(&_pEventCallback->NeedsInput);
            _frameCount++;

            CHECK_HR(currentVideoSample->SetSampleTime(mTimeStamp), "Error setting the video sample time.");
            CHECK_HR(currentVideoSample->SetSampleDuration(VIDEO_FRAME_DURATION), "Error getting video sample duration.");

            CHECK_HR(_pTransform->ProcessInput(inputStreamID, currentVideoSample, 0), "The resampler H264 ProcessInput call failed.");

            mTimeStamp += VIDEO_FRAME_DURATION;
        }
    }

    while (_pEventCallback->HasOutput) {

        CComPtr<IMFSample> mftOutSample = nullptr;
        CComPtr<IMFMediaBuffer> pOutMediaBuffer = nullptr;

        InterlockedDecrement(&_pEventCallback->HasOutput);

        CHECK_HR(_pTransform->GetOutputStreamInfo(outputStreamID, &StreamInfo), "Failed to get output stream info from H264 MFT.");

        CHECK_HR(MFCreateSample(&mftOutSample), "Failed to create MF sample.");
        CHECK_HR(MFCreateMemoryBuffer(StreamInfo.cbSize, &pOutMediaBuffer), "Failed to create memory buffer.");
        CHECK_HR(mftOutSample->AddBuffer(pOutMediaBuffer), "Failed to add sample to buffer.");

        MFT_OUTPUT_DATA_BUFFER _outputDataBuffer;
        memset(&_outputDataBuffer, 0, sizeof _outputDataBuffer);
        _outputDataBuffer.dwStreamID = outputStreamID;
        _outputDataBuffer.dwStatus = 0;
        _outputDataBuffer.pEvents = nullptr;
        _outputDataBuffer.pSample = mftOutSample;

        mftProcessOutput = _pTransform->ProcessOutput(0, 1, &_outputDataBuffer, &processOutputStatus);

        if (mftProcessOutput != MF_E_TRANSFORM_NEED_MORE_INPUT)
        {
            if (_outputDataBuffer.pSample) {

                CComPtr<IMFMediaBuffer> buf = NULL;
                DWORD bufLength;
                CHECK_HR(_outputDataBuffer.pSample->ConvertToContiguousBuffer(&buf), "ConvertToContiguousBuffer failed.");

                if (buf) {

                    CHECK_HR(buf->GetCurrentLength(&bufLength), "Get buffer length failed.");
                    BYTE* rawBuffer = NULL;

                    fFrameSize = bufLength;
                    fDurationInMicroseconds = 0;
                    gettimeofday(&fPresentationTime, NULL);

                    buf->Lock(&rawBuffer, NULL, NULL);
                    memmove(fTo, rawBuffer, fFrameSize > fMaxSize ? fMaxSize : fFrameSize);

                    bytesTransfered += bufLength;

                    FramedSource::afterGetting(this);

                    buf->Unlock();

                    frameSent = true;
                }
            }

            if (_outputDataBuffer.pEvents)
                _outputDataBuffer.pEvents->Release();
        }
        else if (MF_E_TRANSFORM_STREAM_CHANGE == mftProcessOutput) {

            // some encoders want to renegotiate the output format. 
            if (_outputDataBuffer.dwStatus & MFT_OUTPUT_DATA_BUFFER_FORMAT_CHANGE)
            {
                CComPtr<IMFMediaType> pNewOutputMediaType = nullptr;
                HRESULT res = _pTransform->GetOutputAvailableType(outputStreamID, 1, &pNewOutputMediaType);

                res = _pTransform->SetOutputType(0, pNewOutputMediaType, 0);//setting the type again
                CHECK_HR(res, "Failed to set output type during stream change");
            }
        }
        else {
            HandleFailure();
        }
    }

    return frameSent;
}

创建视频样本和颜色转换:

bool GetCurrentFrameAsVideoSample(void **videoSample, int waitTime, bool &isTimeout, CRect &deviceRect, int surfaceWidth, int surfaceHeight)
{

FRAME_DATA currentFrameData;

m_LastErrorCode = m_DuplicationManager.GetFrame(&currentFrameData, waitTime, &isTimeout);

if (!isTimeout && SUCCEEDED(m_LastErrorCode)) {

    m_CurrentFrameTexture = currentFrameData.Frame;

    if (!pDstTexture) {

        D3D11_TEXTURE2D_DESC desc;
        ZeroMemory(&desc, sizeof(D3D11_TEXTURE2D_DESC));

        desc.Format = DXGI_FORMAT_NV12;
        desc.Width = surfaceWidth;
        desc.Height = surfaceHeight;
        desc.MipLevels = 1;
        desc.ArraySize = 1;
        desc.SampleDesc.Count = 1;
        desc.CPUAccessFlags = 0;
        desc.Usage = D3D11_USAGE_DEFAULT;
        desc.BindFlags = D3D11_BIND_RENDER_TARGET;

        m_LastErrorCode = m_Id3d11Device->CreateTexture2D(&desc, NULL, &pDstTexture);
    }

    if (m_CurrentFrameTexture && pDstTexture) {

        // Copy diff area texels to new temp texture
        //m_Id3d11DeviceContext->CopySubresourceRegion(pNewTexture, D3D11CalcSubresource(0, 0, 1), 0, 0, 0, m_CurrentFrameTexture, 0, NULL);

        HRESULT hr = pColorConv->Convert(m_CurrentFrameTexture, pDstTexture);

        if (SUCCEEDED(hr)) { 

            CComPtr<IMFMediaBuffer> pMediaBuffer = nullptr;

            MFCreateDXGISurfaceBuffer(__uuidof(ID3D11Texture2D), pDstTexture, 0, FALSE, (IMFMediaBuffer**)&pMediaBuffer);

            if (pMediaBuffer) {

                CComPtr<IMF2DBuffer> p2DBuffer = NULL;
                DWORD length = 0;
                (((IMFMediaBuffer*)pMediaBuffer))->QueryInterface(__uuidof(IMF2DBuffer), reinterpret_cast<void**>(&p2DBuffer));
                p2DBuffer->GetContiguousLength(&length);
                (((IMFMediaBuffer*)pMediaBuffer))->SetCurrentLength(length);

                //MFCreateVideoSampleFromSurface(NULL, (IMFSample**)videoSample);
                MFCreateSample((IMFSample * *)videoSample);

                if (videoSample) {

                    (*((IMFSample **)videoSample))->AddBuffer((((IMFMediaBuffer*)pMediaBuffer)));
                }

                return true;
            }
        }
    }
}

return false;
}

机器中的intel图形驱动程序已经是最新的。

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

始终仅触发TransformNeedInput事件,而编码器抱怨它不能再接受任何输入。从未触发过TransformHaveOutput事件。

在此处输入图片说明

在intel和msdn论坛上报告的类似问题:1)https://software.intel.com/zh-cn/forums/intel-media-sdk/topic/607189 2) https://social.msdn.microsoft.com/论坛/安全性/ zh-CN / fe051dd5-b522-4e4b-9cbb-2c06a5450e40 / imfsinkwriter-merit-validation-failed-for-mft-intel-quick-sync-video-h264-encoder-mft?forum = mediafoundationdevelopment

更新: 我尝试仅模拟输入源(通过以编程方式创建动画矩形NV12样本),而保持所有其他内容不变。这次,英特尔编码器什么也没抱怨,我什至得到了输出样本。除了英特尔编码器的输出视频失真而Nvidia编码器工作得很好的事实之外。

此外,对于带有英特尔编码器的原始NV12源,我仍然遇到ProcessInput错误。Nvidia MFT和软件编码器没有问题。

英特尔硬件MFT的输出:(请查看Nvidia编码器的输出) 在此处输入图片说明

Nvidia硬件MFT的输出: 在此处输入图片说明

Nvidia图形使用情况统计: 在此处输入图片说明

英特尔图形使用情况统计信息(我不明白为什么GPU引擎显示为视频解码): 在此处输入图片说明


没有显示相关代码。在接收“需要的输入”并为其提供时,可能会出现问题ProcessInput
Roman R.

@RomanR。如果是这样,那么软件和Nvidia硬件MFT也可能失败了,不是吗?我没有显示任何与枚举MFT以及输入和输出配置有关的代码,因为对于线程来说,这是多余的,不必要的,而且时间太长,正如我提到的那样,我遵循的是与intel论坛(software.intel.com / en-us / forums / intel-media-sdk / topic / 681571)。我将尝试使用必要的代码块更新此线程。
拉姆

不它不是。AMD,Intel和NVIDIA的硬件MFT的实现方式相同,但行为略有不同。所有这三个主要都是异步MFT,因此您的问题显然表明您做错了事。没有代码,这仅仅是猜测。微软的软件编码器是同步MFT AFAIR,因此很可能与异步MFT进行通信是无法正常进行的部分。
Roman R.

顺便说一句,该英特尔论坛链接中的代码对我有用并产生视频。
罗曼

@RomanR。我已经使用IMFAsyncCallback,示例创建和颜色转换,ProcessInput和ProcessOutput的实现更新了线程。只需从此处(github.com/NVIDIA/video-sdk-samples/blob/master/…)即可获取颜色转换器。
拉姆

Answers:


2

我看着你的代码。

根据您的帖子,我怀疑是英特尔视频处理器问题。

我的操作系统是Win7,所以我决定先在Nvidia卡上然后在Intel HD Graphics 4000上使用D3D9Device测试视频处理器的性能。

我想视频处理器功能对于D3D9Device的行为与对D3D11Device的行为相同。当然有必要进行检查。

因此,我使该程序进行了检查:https : //github.com/mofo7777/DirectXVideoScreen(请参阅D3D9VideoProcessor子项目)

似乎您没有检查有关视频处理器功能的足够信息。

使用IDXVAHD_Device :: GetVideoProcessorDeviceCaps,这是我检查的内容:

DXVAHD_VPDEVCAPS.MaxInputStreams> 0

DXVAHD_VPDEVCAPS.VideoProcessorCount> 0

DXVAHD_VPDEVCAPS.OutputFormatCount> 0

DXVAHD_VPDEVCAPS.InputFormatCount> 0

DXVAHD_VPDEVCAPS.InputPool == D3DPOOL_DEFAULT

我还将检查IDXVAHD_Device :: GetVideoProcessorOutputFormats和IDXVAHD_Device :: GetVideoProcessorInputFormats支持的输入和输出格式。

这是我在Nvidia GPU和Intel GPU之间发现差异的地方。

NVIDIA:4输出格式

  • D3DFMT_A8R8G8B8
  • D3DFMT_X8R8G8B8
  • D3DFMT_YUY2
  • D3DFMT_NV12

INTEL:3输出格式

  • D3DFMT_A8R8G8B8
  • D3DFMT_X8R8G8B8
  • D3DFMT_YUY2

在Intel HD Graphics 4000上,不支持NV12输出格式。

另外,为使程序正常工作,我需要在使用VideoProcessBltHD之前设置流状态:

  • DXVAHD_STREAM_STATE_D3DFORMAT
  • DXVAHD_STREAM_STATE_FRAME_FORMAT
  • DXVAHD_STREAM_STATE_INPUT_COLOR_SPACE
  • DXVAHD_STREAM_STATE_SOURCE_RECT
  • DXVAHD_STREAM_STATE_DESTINATION_RECT

对于D3D11:

ID3D11VideoProcessorEnumerator :: GetVideoProcessorCaps == IDXVAHD_Device :: GetVideoProcessorDeviceCaps

(D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT_OUTPUT)ID3D11VideoProcessorEnumerator :: CheckVideoProcessorFormat == IDXVAHD_Device :: GetVideoProcessorOutputFormats

(D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT_INPUT)ID3D11VideoProcessorEnumerator :: CheckVideoProcessorFormat == IDXVAHD_Device :: GetVideoProcessorInputFormats

ID3D11VideoContext ::(...)== IDXVAHD_VideoProcessor :: SetVideoProcessStreamState

您能否首先验证GPU的视频处理器功能。你看到和我一样的区别吗?

这是我们需要知道的第一件事,而且看来我的程序并未根据我在github项目上看到的内容对此进行检查。


你是对的。Intel图形上的GetVideoProcessorOutputFormats仅返回RGB变体和YUY2。
拉姆(Ram)

我可以轻松地将RGBA纹理转换为Intel处理器上的YUY2。但是要注意的是,英特尔显卡似乎仅支持NV12输入格式。现在,颜色转换器和视频编码器不兼容。我仍然想知道为什么英特尔决定这样做。还有其他方法可以有效地将RGB转换为NV12吗?我已经尝试了无法提供足够性能的软件方法。
拉姆

您具有着色器或计算着色器。
mofo77 '19

1
我正在研究着色器方法。检查 github.com/mofo7777/DirectXVideoScreen以获取更新。
mofo77 '19

大!感谢您的分享,这真的很有帮助。
拉姆

1

如文章中所述,错误MEError(“未指定错误”)在Intel硬件上提供第一个输入样本后立即由Transform的事件生成器返回,并且进一步的调用仅返回“ Transform Need more input”,但未产生任何输出。不过,相同的代码在Nvidia机器上也可以正常工作。经过大量的实验和研究,我发现我创建了太多的D3d11Device实例,以我为例,我分别创建了2到3个用于捕获,颜色转换和硬件编码器的设备。而我可以简单地重用单个D3dDevice实例。但是,创建多个D3d11Device实例可能在高端计算机上工作。这没有记录在任何地方。我什至找不到“ MEError”错误原因的线索。无处提及。

重用D3D11Device实例解决了该问题。发布此解决方案,因为它可能对与我面临同样问题的人们有所帮助。


我在您的帖子中看不到提到E_UNEXPECTED错误的地方……
mofo77

@ mofo77,很抱歉,帖子中提到的是MEError = 1(“未指定错误”)。我有点迷失了方向。更正了我的答案。感谢您指出。
拉姆
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.