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