Skip to content

Commit

Permalink
Fix voice token cache
Browse files Browse the repository at this point in the history
  • Loading branch information
gexgd0419 committed May 10, 2024
1 parent ee0ead2 commit 2cc256d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
16 changes: 9 additions & 7 deletions NaturalVoiceSAPIAdapter/VoiceTokenEnumerator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ inline static void CheckHr(HRESULT hr)
throw std::system_error(hr, std::system_category());
}

static CComPtr<IEnumSpObjectTokens> s_pCachedEnum = nullptr;
// use non-smart pointer so that it won't be released automatically on DLL unload
static IEnumSpObjectTokens* s_pCachedEnum = nullptr;

static std::mutex s_cacheMutex;
extern HANDLE g_hTimerQueue;
static HANDLE s_hCacheTimer = nullptr;
Expand All @@ -34,6 +36,9 @@ HRESULT CVoiceTokenEnumerator::FinalConstruct()

std::lock_guard lock(s_cacheMutex);

if (s_pCachedEnum)
return s_pCachedEnum->Clone(&m_pEnum);

// Timer queues CANNOT be created in DllMain, otherwise deadlocks would happen on Windows XP
// So we create the timer queue here on first use
if (!g_hTimerQueue)
Expand Down Expand Up @@ -87,19 +92,16 @@ HRESULT CVoiceTokenEnumerator::FinalConstruct()
const auto clearCache = [](PVOID, BOOLEAN)
{
std::lock_guard lock(s_cacheMutex);
s_pCachedEnum.Release();
s_pCachedEnum = nullptr;
(void)DeleteTimerQueueTimer(g_hTimerQueue, s_hCacheTimer, nullptr);
s_hCacheTimer = nullptr;
};
CreateTimerQueueTimer(&s_hCacheTimer, g_hTimerQueue, clearCache, nullptr, 10000, 0,
WT_EXECUTEONLYONCE | WT_EXECUTELONGFUNCTION);
}

CComPtr<IEnumSpObjectTokens> temp;
RETONFAIL(pEnumBuilder->QueryInterface(&temp));
s_pCachedEnum = std::move(temp);

return pEnumBuilder->QueryInterface(&m_pEnum);
RETONFAIL(pEnumBuilder->QueryInterface(&s_pCachedEnum));
return s_pCachedEnum->Clone(&m_pEnum);
}

static CComPtr<ISpDataKey> MakeVoiceKey(StringPairCollection&& values, SubkeyCollection&& subkeys)
Expand Down
12 changes: 10 additions & 2 deletions NaturalVoiceSAPIAdapter/dllmain.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,16 @@ extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpRes

if (dwReason == DLL_PROCESS_DETACH)
{
// Use INVALID_HANDLE_VALUE to wait for callback functions to complete
(void)DeleteTimerQueueEx(g_hTimerQueue, INVALID_HANDLE_VALUE);
if (lpReserved == nullptr) // being unloaded dynamically
{
// Use INVALID_HANDLE_VALUE to wait for callback functions to complete
(void)DeleteTimerQueueEx(g_hTimerQueue, INVALID_HANDLE_VALUE);
}
else
{
// Use nullptr to delete without waiting for callbacks
(void)DeleteTimerQueueEx(g_hTimerQueue, nullptr);
}
}

return _AtlModule.DllMain(dwReason, lpReserved);
Expand Down

0 comments on commit 2cc256d

Please sign in to comment.