Skip to content

Commit 2e4c2b5

Browse files
committed
refactor: use static COM init in MSMF backend to avoid thread-affinity issues
Replace per-instance m_didInitializeCom/m_didSetup flags with a static setupCom pattern matching the DirectShow backend. Removes CoUninitialize from the destructor since static COM init is never paired with uninit, avoiding mismatched init/uninit on different threads.
1 parent 81bb3ab commit 2e4c2b5

2 files changed

Lines changed: 9 additions & 10 deletions

File tree

src/ccap_imp_windows_msmf.cpp

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -152,22 +152,23 @@ ProviderMSMF::ProviderMSMF() {
152152
ProviderMSMF::~ProviderMSMF() {
153153
close();
154154
uninitMediaFoundation();
155-
if (m_didInitializeCom) {
156-
CoUninitialize();
157-
m_didInitializeCom = false;
158-
}
159155
}
160156

161157
bool ProviderMSMF::setup() {
162158
if (m_mfInitialized) {
163159
return true;
164160
}
165161

166-
if (!m_didSetup) {
162+
// Use static COM initialization (matching DirectShow backend pattern).
163+
// COM init/uninit is thread-affine — caching per-instance flags can
164+
// mismatch if the destructor runs on a different thread. A static
165+
// flag avoids the issue and is safe because COM reference-counts its
166+
// per-thread initialization.
167+
static bool s_didSetup = false;
168+
if (!s_didSetup) {
167169
HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
168-
m_didInitializeCom = SUCCEEDED(hr);
169-
m_didSetup = m_didInitializeCom || hr == RPC_E_CHANGED_MODE;
170-
if (!m_didSetup) {
170+
s_didSetup = SUCCEEDED(hr) || hr == RPC_E_CHANGED_MODE;
171+
if (!s_didSetup) {
171172
reportError(ErrorCode::InitializationFailed, "COM initialization failed for Media Foundation backend");
172173
return false;
173174
}

src/ccap_imp_windows_msmf.h

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,6 @@ class ProviderMSMF : public ProviderImp {
8181
std::atomic<bool> m_shouldStop{ false };
8282
std::atomic<bool> m_isRunning{ false };
8383
bool m_isOpened{ false };
84-
bool m_didSetup{ false };
85-
bool m_didInitializeCom{ false };
8684
bool m_mfInitialized{ false };
8785
PixelFormat m_activePixelFormat = PixelFormat::Unknown;
8886
uint32_t m_activeWidth = 0;

0 commit comments

Comments
 (0)