blob: b7ab8292a7beb83409ddeeddfde5d2855819ff84 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
|
#include "stdafx.h"
#include "mfStartup.h"
#include <atlbase.h>
#include <mfapi.h>
#pragma comment(lib, "Mfplat.lib")
namespace
{
struct sCoInitStatus
{
// Possible state:
// -1 is the initial state, coInitialize never called
// S_OK - CoInitializeEx succeeded, in this state the counter tracks the count of coInitialize() for the current thread
// S_FALSE - CoInitializeEx failed with RPC_E_CHANGED_MODE, or did nothing because already initialized for the current thread
// Error status - CoInitializeEx failed for some other reason
HRESULT code = -1;
uint32_t counter = 0;
};
thread_local sCoInitStatus coInitStatus;
static HRESULT coInitialize()
{
sCoInitStatus& cis = coInitStatus;
HRESULT hr = cis.code;
if( SUCCEEDED( hr ) )
{
if( S_OK == hr )
cis.counter++;
return S_FALSE;
}
if( hr == HRESULT( -1 ) )
{
hr = CoInitializeEx( nullptr, COINIT_MULTITHREADED );
if( S_OK == hr )
{
cis.counter = 1;
return cis.code = S_OK;
}
if( S_FALSE == hr || RPC_E_CHANGED_MODE == hr )
{
return cis.code = S_FALSE;
}
cis.code = hr;
return hr;
}
return hr;
}
static void coUninitialize()
{
sCoInitStatus& cis = coInitStatus;
if( cis.code == S_OK )
{
assert( cis.counter > 0 );
cis.counter--;
if( 0 == cis.counter )
CoUninitialize();
}
}
static CComAutoCriticalSection s_lock;
#define LOCK() CComCritSecLock<CComAutoCriticalSection> lock{ s_lock }
static uint32_t mfStartupCounter = 0;
constexpr uint8_t FlagCOM = 1;
constexpr uint8_t FlagMF = 0x10;
}
using namespace Whisper;
MfStartupRaii::~MfStartupRaii()
{
if( 0 != ( successFlags & FlagMF ) )
{
LOCK();
assert( mfStartupCounter > 0 );
mfStartupCounter--;
if( mfStartupCounter > 0 )
return;
MFShutdown();
successFlags &= ~FlagMF;
}
if( 0 != ( successFlags & FlagCOM ) )
{
coUninitialize();
successFlags &= ~FlagCOM;
}
}
HRESULT MfStartupRaii::startup()
{
if( 0 != ( successFlags & FlagMF ) )
return HRESULT_FROM_WIN32( ERROR_ALREADY_INITIALIZED );
HRESULT hr = coInitialize();
CHECK( hr );
if( hr == S_OK )
successFlags |= FlagCOM;
LOCK();
if( 0 == mfStartupCounter )
{
HRESULT hr = MFStartup( MF_VERSION, MFSTARTUP_LITE );
if( SUCCEEDED( hr ) )
{
mfStartupCounter = 1;
successFlags |= FlagMF;
return S_OK;
}
if( 0 != ( successFlags & FlagCOM ) )
{
coUninitialize();
successFlags &= ~FlagCOM;
}
return hr;
}
else
{
mfStartupCounter++;
successFlags |= FlagMF;
return S_FALSE;
}
}
|