Opening video management killed the client on some hosts: the DirectShow
sample callback memcpy'd into a null bitmap buffer.
IMediaControl::Run legitimately returns S_FALSE while the state change
completes asynchronously; the graph is already running and frames are
delivered. Open passed that S_FALSE to its caller, which compared against
S_OK (introduced in 8d4c118) and took the "camera failed to open" abort
path while the graph kept running; ConstructBI never allocated the buffers
and the first callback wrote to address 0.
Open now returns S_OK only when the graph is running (S_FALSE normalised)
and a failure code otherwise. BufferCB drops a frame with S_OK when the
buffer is not ready or the driver hands over more bytes than negotiated,
so the start-up race or a resolution change can neither corrupt the heap
nor stop the stream. ConstructBI validates the dimensions and allocates the
full BITMAPINFO that SendBitMapInfor copies.
Also accept FORMAT_VideoInfo2 (many built-in cameras report it, and the
cast to VIDEOINFOHEADER read garbage dimensions) and fix BindVideoFilter's
comma-expression loop that called BindToStorage with a dangling IMoniker
once enumeration ran out.
Debug and Release x64 clients build; the host that reproducibly crashed
now works.
Co-Authored-By: deepseek-flash
287 lines
9.5 KiB
C++
287 lines
9.5 KiB
C++
// CaptureVideo.cpp: implementation of the CCaptureVideo class.
|
||
//
|
||
//////////////////////////////////////////////////////////////////////
|
||
|
||
#include "stdafx.h"
|
||
#include "CaptureVideo.h"
|
||
#include <dvdmedia.h> // VIDEOINFOHEADER2:不少摄像头/驱动给的是 FORMAT_VideoInfo2
|
||
|
||
//////////////////////////////////////////////////////////////////////
|
||
// Construction/Destruction
|
||
//////////////////////////////////////////////////////////////////////
|
||
CSampleGrabberCB CCaptureVideo::mCB;
|
||
|
||
CCaptureVideo::CCaptureVideo()
|
||
{
|
||
m_pCapture = NULL;
|
||
m_pGB = NULL;
|
||
m_pMC = NULL;
|
||
m_pVW = NULL;
|
||
m_pBF = NULL;
|
||
m_pGrabber = NULL;
|
||
m_bExit = FALSE;
|
||
m_hWnd = NULL;
|
||
if (FAILED(CoInitialize(NULL))) {
|
||
return;
|
||
}
|
||
}
|
||
|
||
CCaptureVideo::~CCaptureVideo()
|
||
{
|
||
m_bExit = TRUE;
|
||
if(m_pMC)m_pMC->StopWhenReady();
|
||
if(m_pVW) {
|
||
m_pVW->put_Visible(OAFALSE);
|
||
m_pVW->put_Owner(NULL);
|
||
}
|
||
SAFE_RELEASE(m_pMC);
|
||
SAFE_RELEASE(m_pVW);
|
||
SAFE_RELEASE(m_pGB);
|
||
SAFE_RELEASE(m_pBF);
|
||
SAFE_RELEASE(m_pGrabber);
|
||
SAFE_RELEASE(m_pCapture);
|
||
|
||
CoUninitialize() ;
|
||
}
|
||
|
||
HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
|
||
{
|
||
Mprintf("CCaptureVideo call Open\n");
|
||
HRESULT hResult = E_FAIL; // 默认失败:只有图真正跑起来才算成功
|
||
bool graphRunning = false;
|
||
do {
|
||
hResult = InitCaptureGraphBuilder();
|
||
if (FAILED(hResult))
|
||
break;
|
||
if (!BindVideoFilter(iDeviceID, &m_pBF)) {
|
||
hResult = E_FAIL; // 没有可用的 DirectShow 采集设备
|
||
break;
|
||
}
|
||
|
||
hResult = m_pGB->AddFilter(m_pBF, L"Capture Filter");
|
||
|
||
hResult = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER,
|
||
IID_ISampleGrabber, (void**)&m_pGrabber); //引脚内存
|
||
if(FAILED(hResult))
|
||
break;
|
||
|
||
//m_pGrabber 属性设置 1 格式 2 内存缓冲形式
|
||
CComQIPtr<IBaseFilter, &IID_IBaseFilter> pGrabBase(m_pGrabber);//设置视频格式
|
||
AM_MEDIA_TYPE mt; //视频格式
|
||
ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE));
|
||
mt.majortype = MEDIATYPE_Video;
|
||
mt.subtype = MEDIASUBTYPE_RGB24; // MEDIASUBTYPE_RGB24
|
||
|
||
hResult = m_pGrabber->SetMediaType(&mt);
|
||
if(FAILED(hResult))
|
||
break;
|
||
|
||
hResult = m_pGB->AddFilter(pGrabBase,L"Grabber");
|
||
|
||
if(FAILED(hResult))
|
||
break;
|
||
|
||
hResult = m_pCapture->RenderStream(&PIN_CATEGORY_PREVIEW, //静态
|
||
&MEDIATYPE_Video,m_pBF,pGrabBase,NULL);
|
||
if(FAILED(hResult)) {
|
||
//扑捉
|
||
hResult = m_pCapture->RenderStream(&PIN_CATEGORY_CAPTURE,&MEDIATYPE_Video,m_pBF,pGrabBase,NULL);
|
||
break;
|
||
}
|
||
|
||
if(FAILED(hResult))
|
||
break;
|
||
|
||
hResult = m_pGrabber->GetConnectedMediaType(&mt);
|
||
|
||
if (FAILED(hResult))
|
||
break;
|
||
|
||
//3 扑捉数据 FDO 一旦有数据就进行 回调函数调用 属于一个类
|
||
|
||
// 只按 VIDEOINFOHEADER 解释 mt.pbFormat 不够:很多摄像头/驱动(尤其
|
||
// 笔记本内置摄像头)给出的格式是 FORMAT_VideoInfo2,两者头部布局不同,
|
||
// 直接强转会读出垃圾宽高,后面按它分配缓冲/逐帧 memcpy 就会崩。两种都认,
|
||
// 其它格式或非法尺寸一律当失败处理,让上层优雅退出而不是带病跑。
|
||
BITMAPINFOHEADER* bmi = NULL;
|
||
if (mt.formattype == FORMAT_VideoInfo && mt.pbFormat != NULL
|
||
&& mt.cbFormat >= sizeof(VIDEOINFOHEADER)) {
|
||
bmi = &((VIDEOINFOHEADER*)mt.pbFormat)->bmiHeader;
|
||
} else if (mt.formattype == FORMAT_VideoInfo2 && mt.pbFormat != NULL
|
||
&& mt.cbFormat >= sizeof(VIDEOINFOHEADER2)) {
|
||
bmi = &((VIDEOINFOHEADER2*)mt.pbFormat)->bmiHeader;
|
||
}
|
||
if (bmi == NULL || bmi->biWidth <= 0 || bmi->biHeight == 0
|
||
|| bmi->biWidth > 16384 || abs(bmi->biHeight) > 16384) {
|
||
Mprintf("CCaptureVideo: unsupported media type (formattype=%08lx cbFormat=%lu), abort\n",
|
||
(unsigned long)mt.formattype.Data1, (unsigned long)mt.cbFormat);
|
||
FreeMediaType(mt);
|
||
hResult = E_FAIL;
|
||
break;
|
||
}
|
||
//mCB 是个另外一个类 并且全局变量 有个回调
|
||
mCB.m_ulFullWidth = (ULONG)bmi->biWidth;
|
||
mCB.m_ulFullHeight = (ULONG)abs(bmi->biHeight);
|
||
|
||
FreeMediaType(mt);
|
||
|
||
hResult = m_pGrabber->SetBufferSamples( FALSE ); //回调函数
|
||
hResult = m_pGrabber->SetOneShot( FALSE );
|
||
|
||
//设置视频捕获回调函数 也就是如果有视频数据时就会调用这个类的BufferCB函数
|
||
|
||
//返回OnTimer
|
||
hResult = m_pGrabber->SetCallback(&mCB, 1);
|
||
|
||
m_hWnd = CreateWindow("#32770", "", WS_POPUP, 0, 0, 0, 0, NULL, NULL, NULL, NULL);
|
||
|
||
SetupVideoWindow(); //屏蔽窗口
|
||
|
||
hResult = m_pMC->Run(); //开灯
|
||
|
||
if(FAILED(hResult))
|
||
break;
|
||
// IMediaControl::Run 在「状态切换尚未完成、稍后异步完成」时会返回 S_FALSE,
|
||
// 这时图已经在跑、SampleGrabber 回调随时会到。以前把它原样返回给上层,
|
||
// 上层用 == S_OK 判断就误判成「摄像头没打开」并提前中止(8d4c118 引入),
|
||
// 而回调随后拿还没分配的 m_BitmapData_Full 做 memcpy —— 写地址 0 崩溃。
|
||
hResult = S_OK;
|
||
graphRunning = true;
|
||
} while (false);
|
||
|
||
Mprintf("CCaptureVideo Open %s (hr=%08lX)\n",
|
||
graphRunning ? "succeed" : "failed", (unsigned long)hResult);
|
||
|
||
// 图没跑起来时一律返回失败码(S_FALSE 也是「成功」语义,会让上层误判)
|
||
return graphRunning ? S_OK : (FAILED(hResult) ? hResult : E_FAIL);
|
||
}
|
||
|
||
|
||
HRESULT CCaptureVideo::InitCaptureGraphBuilder()
|
||
{
|
||
HRESULT hResult = CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC,
|
||
IID_ICaptureGraphBuilder2, (void**)&m_pCapture); //真实设备
|
||
|
||
if (FAILED(hResult)) {
|
||
return hResult;
|
||
}
|
||
|
||
hResult=CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
|
||
IID_IGraphBuilder, (void**)&m_pGB); //虚拟设备
|
||
|
||
if (FAILED(hResult)) {
|
||
return hResult;
|
||
}
|
||
//将过滤绑定到真实设备上面
|
||
m_pCapture->SetFiltergraph(m_pGB);
|
||
hResult = m_pGB->QueryInterface(IID_IMediaControl,(LPVOID*)&m_pMC);
|
||
if (FAILED(hResult)) {
|
||
return hResult;
|
||
}
|
||
|
||
hResult = m_pGB->QueryInterface(IID_IVideoWindow,(LPVOID*) &m_pVW);
|
||
if (FAILED(hResult)) {
|
||
return hResult;
|
||
}
|
||
return hResult;
|
||
}
|
||
|
||
LPBITMAPINFO CCaptureVideo::GetBmpInfor()
|
||
{
|
||
return mCB.GetBmpInfor(); //构建位图内存头和数据
|
||
}
|
||
|
||
BOOL CCaptureVideo::BindVideoFilter(int deviceId, IBaseFilter **pFilter)
|
||
{
|
||
if (deviceId < 0 || pFilter == NULL)
|
||
return FALSE;// enumerate all video capture devices
|
||
*pFilter = NULL;
|
||
|
||
CComPtr<ICreateDevEnum> pCreateDevEnum;
|
||
HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
|
||
IID_ICreateDevEnum, (void**)&pCreateDevEnum);
|
||
if (hr != NOERROR)
|
||
return FALSE;
|
||
|
||
CComPtr<IEnumMoniker> pEm;
|
||
hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEm, 0);
|
||
if (hr != S_OK) // S_FALSE = 该类别下没有任何 DirectShow 设备
|
||
return FALSE;
|
||
|
||
pEm->Reset();
|
||
ULONG cFetched = 0;
|
||
IMoniker* pM = NULL;
|
||
int index = 0;
|
||
// 原实现写成逗号表达式 `while (hr = Next(...), hr == S_OK, index <= deviceId)`:
|
||
// 循环条件实际只看 index,枚举结束后还会继续用未初始化/已释放的 pM 调
|
||
// BindToStorage。机器上 VFW 能枚举到摄像头、DirectShow 却一个都没有时必崩。
|
||
while (pEm->Next(1, &pM, &cFetched) == S_OK && pM != NULL) {
|
||
if (index == deviceId) {
|
||
hr = pM->BindToObject(0, 0, IID_IBaseFilter, (void**)pFilter);
|
||
pM->Release();
|
||
return SUCCEEDED(hr) && *pFilter != NULL;
|
||
}
|
||
pM->Release();
|
||
pM = NULL;
|
||
++index;
|
||
}
|
||
Mprintf("CCaptureVideo: no DirectShow video device #%d (enumerated %d)\n", deviceId, index);
|
||
return FALSE;
|
||
}
|
||
|
||
|
||
void CCaptureVideo::FreeMediaType(AM_MEDIA_TYPE& mt)
|
||
{
|
||
if (mt.cbFormat != 0) {
|
||
CoTaskMemFree((PVOID)mt.pbFormat);
|
||
mt.cbFormat = 0;
|
||
mt.pbFormat = NULL;
|
||
}
|
||
if (mt.pUnk != NULL) {
|
||
mt.pUnk->Release();
|
||
mt.pUnk = NULL;
|
||
}
|
||
}
|
||
|
||
|
||
HRESULT CCaptureVideo::SetupVideoWindow()
|
||
{
|
||
HRESULT hr;
|
||
hr = m_pVW->put_Owner((OAHWND)m_hWnd);
|
||
if (FAILED(hr))return hr;
|
||
hr = m_pVW->put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN);
|
||
if (FAILED(hr))return hr;
|
||
ResizeVideoWindow();
|
||
hr = m_pVW->put_Visible(OATRUE);
|
||
return hr;
|
||
}
|
||
|
||
void CCaptureVideo::ResizeVideoWindow()
|
||
{
|
||
if (m_pVW) {
|
||
RECT rc;
|
||
::GetClientRect(m_hWnd,&rc);
|
||
m_pVW->SetWindowPosition(0, 0, rc.right, rc.bottom); //将窗口设置到0 0 0 0 处
|
||
}
|
||
}
|
||
|
||
void CCaptureVideo::SendEnd() //发送结束 设置可以再取数据
|
||
{
|
||
InterlockedExchange((LPLONG)&mCB.bStact,CMD_CAN_COPY);
|
||
}
|
||
|
||
LPBYTE CCaptureVideo::GetDIB(DWORD& dwSize)
|
||
{
|
||
BYTE *szBuffer = NULL;
|
||
int n = 200; // 10s没有获取到数据则返回NULL
|
||
do {
|
||
if (mCB.bStact==CMD_CAN_SEND) { //这里改变了一下发送的状态
|
||
if (szBuffer = mCB.GetNextScreen(dwSize)) //是否获取到视频
|
||
break;
|
||
}
|
||
Sleep(50);
|
||
} while (!m_bExit && --n);
|
||
|
||
return szBuffer;
|
||
}
|