如何复制IMFSample对象

时间:2016-07-13 14:42:46

标签: c++ windows win-universal-app video-processing ms-media-foundation

我需要复制IMFSample对象,以便我将拥有单独的独立对象。 Microsoft API无法轻松复制IMFSample视频帧。

1 个答案:

答案 0 :(得分:1)

以下是示例代码:

#define MmfThrowIfError(hrVal) \
{ \
    HRESULT hrMmfTraceInternal = (hrVal); \
    if (FAILED(hrMmfTraceInternal)) \
    { \
        /* LOG_F(LS_ERROR)<<"MMF hr: 0x"<<std::hex<<hrMmfTraceInternal; */ \
        throw ref new ::Platform::Exception(hrMmfTraceInternal); \
    } \
}

MFComPtr<IMFMediaBuffer> DuplicateBuffer(const MFComPtr<IMFMediaBuffer>& srcBuf)
{
    byte* srcByteBuffer = nullptr;
    DWORD srcBuffMaxLen = 0;
    DWORD srcBuffCurrLen = 0;
    MmfThrowIfError(srcBuf->Lock(&srcByteBuffer, &srcBuffMaxLen, &srcBuffCurrLen));

    MFComPtr<IMFMediaBuffer> destBuf = nullptr;
    MmfThrowIfError(MFCreateMemoryBuffer(srcBuffCurrLen, &destBuf));

    byte* destByteBuffer = nullptr;
    MmfThrowIfError(destBuf->Lock(&destByteBuffer, nullptr, nullptr));
    memcpy(destByteBuffer, srcByteBuffer, srcBuffCurrLen);
    MmfThrowIfError(destBuf->Unlock());
    MmfThrowIfError(srcBuf->Unlock());

    MmfThrowIfError(destBuf->SetCurrentLength(srcBuffCurrLen));
    return destBuf;
}

SampleComPtr DuplicateSample(const SampleComPtr& sample)
{
    if (!sample)
        return nullptr;

    DWORD sampleFlags = 0;
    LONGLONG llVideoTimeStamp = 0;
    LONGLONG llSampleDuration = 0;
    MmfThrowIfError(sample->GetSampleFlags(&sampleFlags));
    MmfThrowIfError(sample->GetSampleTime(&llVideoTimeStamp));
    MmfThrowIfError(sample->GetSampleDuration(&llSampleDuration));

    SampleComPtr outSample;
    MFCreateSample(&outSample);
    MmfThrowIfError(outSample->SetSampleFlags(sampleFlags));
    MmfThrowIfError(outSample->SetSampleTime(llVideoTimeStamp));
    MmfThrowIfError(outSample->SetSampleDuration(llSampleDuration));

    DWORD bufferCount = 0;
    MmfThrowIfError(sample->GetBufferCount(&bufferCount));

    for (DWORD index = 0; index < bufferCount; ++index)
    {
        MFComPtr<IMFMediaBuffer> srcBuf = nullptr;
        MmfThrowIfError(sample->GetBufferByIndex(index, &srcBuf));

        MFComPtr<IMFMediaBuffer> reConstructedBuffer = DuplicateBuffer(srcBuf);
        srcBuf = nullptr;
        MmfThrowIfError(outSample->AddBuffer(reConstructedBuffer.Get()));
    }

    return outSample;
}