AkPlatformFuncs.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. /*******************************************************************************
  2. The content of this file includes portions of the AUDIOKINETIC Wwise Technology
  3. released in source code form as part of the SDK installer package.
  4. Commercial License Usage
  5. Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology
  6. may use this file in accordance with the end user license agreement provided
  7. with the software or, alternatively, in accordance with the terms contained in a
  8. written agreement between you and Audiokinetic Inc.
  9. Apache License Usage
  10. Alternatively, this file may be used under the Apache License, Version 2.0 (the
  11. "Apache License"); you may not use this file except in compliance with the
  12. Apache License. You may obtain a copy of the Apache License at
  13. http://www.apache.org/licenses/LICENSE-2.0.
  14. Unless required by applicable law or agreed to in writing, software distributed
  15. under the Apache License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
  16. OR CONDITIONS OF ANY KIND, either express or implied. See the Apache License for
  17. the specific language governing permissions and limitations under the License.
  18. Copyright (c) 2023 Audiokinetic Inc.
  19. *******************************************************************************/
  20. #ifndef _AK_PLATFORM_FUNCS_H_
  21. #define _AK_PLATFORM_FUNCS_H_
  22. #include "malloc.h"
  23. #include <AK/Tools/Common/AkAssert.h>
  24. #include <AK/SoundEngine/Common/AkAtomic.h>
  25. #include <windows.h>
  26. #include <stdio.h>
  27. #if defined(_WIN64)
  28. // on 64 bit, removes warning C4985: 'ceil': attributes not present on previous declaration.
  29. // see http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=294649
  30. #include <math.h>
  31. #endif // _WIN64
  32. #include <intrin.h>
  33. #if defined(AK_XBOXSERIESX)
  34. #include <ammintrin.h>
  35. #endif
  36. //-----------------------------------------------------------------------------
  37. // Platform-specific thread properties definition.
  38. //-----------------------------------------------------------------------------
  39. struct AkThreadProperties
  40. {
  41. int nPriority; ///< Thread priority
  42. #ifdef AK_WIN_UNIVERSAL_APP
  43. PROCESSOR_NUMBER processorNumber;///< Ideal processor (passed to SetThreadIdealProcessorEx)
  44. #else
  45. AkUInt32 dwAffinityMask; ///< Affinity mask
  46. #endif
  47. AkUInt32 uStackSize; ///< Thread stack size.
  48. };
  49. //-----------------------------------------------------------------------------
  50. // External variables.
  51. //-----------------------------------------------------------------------------
  52. // g_fFreqRatio is used by time helpers to return time values in milliseconds.
  53. // It is declared and updated by the sound engine.
  54. namespace AK
  55. {
  56. extern AkReal32 g_fFreqRatio;
  57. }
  58. //-----------------------------------------------------------------------------
  59. // Defines for Win32.
  60. //-----------------------------------------------------------------------------
  61. #define AK_DECLARE_THREAD_ROUTINE( FuncName ) DWORD WINAPI FuncName(LPVOID lpParameter)
  62. #define AK_THREAD_RETURN( _param_ ) return (_param_);
  63. #define AK_THREAD_ROUTINE_PARAMETER lpParameter
  64. #define AK_GET_THREAD_ROUTINE_PARAMETER_PTR(type) reinterpret_cast<type*>( AK_THREAD_ROUTINE_PARAMETER )
  65. #define AK_RETURN_THREAD_OK 0x00000000
  66. #define AK_RETURN_THREAD_ERROR 0x00000001
  67. #define AK_DEFAULT_STACK_SIZE (128*1024)
  68. #define AK_THREAD_PRIORITY_NORMAL THREAD_PRIORITY_NORMAL
  69. #define AK_THREAD_PRIORITY_ABOVE_NORMAL THREAD_PRIORITY_ABOVE_NORMAL
  70. #define AK_THREAD_PRIORITY_BELOW_NORMAL THREAD_PRIORITY_BELOW_NORMAL
  71. #define AK_THREAD_PRIORITY_TIME_CRITICAL THREAD_PRIORITY_TIME_CRITICAL
  72. #define AK_THREAD_MODE_BACKGROUND_BEGIN THREAD_MODE_BACKGROUND_BEGIN
  73. // NULL objects
  74. #define AK_NULL_THREAD NULL
  75. #define AK_INFINITE INFINITE
  76. #define AkMax(x1, x2) (((x1) > (x2))? (x1): (x2))
  77. #define AkMin(x1, x2) (((x1) < (x2))? (x1): (x2))
  78. #define AkClamp(x, min, max) ((x) < (min)) ? (min) : (((x) > (max) ? (max) : (x)))
  79. namespace AKPLATFORM
  80. {
  81. // Simple automatic event API
  82. // ------------------------------------------------------------------
  83. /// Platform Independent Helper
  84. inline void AkClearEvent( AkEvent & out_event )
  85. {
  86. out_event = NULL;
  87. }
  88. /// Platform Independent Helper
  89. inline AKRESULT AkCreateEvent( AkEvent & out_event )
  90. {
  91. out_event = ::CreateEvent( NULL, // No security attributes
  92. false, // Reset type: automatic
  93. false, // Initial signaled state: not signaled
  94. NULL // No name
  95. );
  96. return ( out_event ) ? AK_Success : AK_Fail;
  97. }
  98. /// Platform Independent Helper
  99. inline void AkDestroyEvent( AkEvent & io_event )
  100. {
  101. if ( io_event )
  102. ::CloseHandle( io_event );
  103. io_event = NULL;
  104. }
  105. /// Platform Independent Helper
  106. inline void AkWaitForEvent( AkEvent & in_event )
  107. {
  108. AKVERIFY( ::WaitForSingleObject( in_event, INFINITE ) == WAIT_OBJECT_0 );
  109. }
  110. /// Platform Independent Helper
  111. inline void AkSignalEvent( const AkEvent & in_event )
  112. {
  113. AKVERIFY( ::SetEvent( in_event ) );
  114. }
  115. /// Platform Independent Helper
  116. AkForceInline void AkClearSemaphore(AkSemaphore& io_semaphore)
  117. {
  118. io_semaphore = NULL;
  119. }
  120. /// Platform Independent Helper
  121. inline AKRESULT AkCreateSemaphore(AkSemaphore& out_semaphore, AkUInt32 in_initialCount)
  122. {
  123. out_semaphore = ::CreateSemaphore(
  124. NULL, // no security attributes
  125. in_initialCount, // initial count
  126. INT_MAX, // no maximum -- matches posix semaphore behaviour
  127. NULL); // no name
  128. return (out_semaphore) ? AK_Success : AK_Fail;
  129. }
  130. /// Platform Independent Helper
  131. inline void AkDestroySemaphore(AkSemaphore& io_semaphore)
  132. {
  133. ::CloseHandle(io_semaphore);
  134. }
  135. /// Platform Independent Helper - Semaphore wait, aka Operation P. Decrements value of semaphore, and, if the semaphore would be less than 0, waits for the semaphore to be released.
  136. inline void AkWaitForSemaphore(AkSemaphore& in_semaphore)
  137. {
  138. AKVERIFY(::WaitForSingleObject(in_semaphore, INFINITE) == WAIT_OBJECT_0);
  139. }
  140. /// Platform Independent Helper - Semaphore signal, aka Operation V. Increments value of semaphore by an arbitrary count.
  141. inline void AkReleaseSemaphore(AkSemaphore& in_semaphore, AkUInt32 in_count)
  142. {
  143. AKVERIFY(ReleaseSemaphore(in_semaphore, in_count, NULL) >= 0);
  144. }
  145. // Threads
  146. // ------------------------------------------------------------------
  147. /// Platform Independent Helper
  148. inline bool AkIsValidThread( AkThread * in_pThread )
  149. {
  150. return (*in_pThread != AK_NULL_THREAD);
  151. }
  152. /// Platform Independent Helper
  153. inline void AkClearThread( AkThread * in_pThread )
  154. {
  155. *in_pThread = AK_NULL_THREAD;
  156. }
  157. /// Platform Independent Helper
  158. inline void AkCloseThread( AkThread * in_pThread )
  159. {
  160. AKASSERT( in_pThread );
  161. AKASSERT( *in_pThread );
  162. AKVERIFY( ::CloseHandle( *in_pThread ) );
  163. AkClearThread( in_pThread );
  164. }
  165. #define AkExitThread( _result ) return _result;
  166. /// Platform Independent Helper
  167. inline void AkGetDefaultThreadProperties( AkThreadProperties & out_threadProperties )
  168. {
  169. out_threadProperties.nPriority = AK_THREAD_PRIORITY_NORMAL;
  170. out_threadProperties.uStackSize= AK_DEFAULT_STACK_SIZE;
  171. #ifdef AK_WIN_UNIVERSAL_APP
  172. out_threadProperties.processorNumber.Group = 0;
  173. out_threadProperties.processorNumber.Number = MAXIMUM_PROCESSORS;
  174. out_threadProperties.processorNumber.Reserved = 0;
  175. #else
  176. out_threadProperties.dwAffinityMask = 0;
  177. #endif
  178. }
  179. /// Set the name of a thread: see http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  180. inline void AkSetThreadName( AkThread in_threadHnd, DWORD in_dwThreadID, LPCSTR in_szThreadName )
  181. {
  182. const DWORD MS_VC_EXCEPTION=0x406D1388;
  183. #pragma pack(push,8)
  184. typedef struct tagTHREADNAME_INFO
  185. {
  186. DWORD dwType;
  187. LPCSTR szName;
  188. DWORD dwThreadID;
  189. DWORD dwFlags;
  190. } THREADNAME_INFO;
  191. #pragma pack(pop)
  192. THREADNAME_INFO info;
  193. info.dwType = 0x1000;
  194. info.szName = in_szThreadName;
  195. info.dwThreadID = in_dwThreadID;
  196. info.dwFlags = 0;
  197. __try
  198. {
  199. RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
  200. }
  201. #pragma warning(suppress: 6312 6322)
  202. __except(EXCEPTION_CONTINUE_EXECUTION)
  203. {
  204. }
  205. #if defined(AK_XBOX) || defined(_GAMING_DESKTOP) // also applicable on Windows when Win7 support is dropped. SetThreadDescription is a Win10 only API
  206. wchar_t wszThreadName[32];
  207. AkUInt32 maxStrLen = (sizeof(wszThreadName) / sizeof(wchar_t)) - 1;
  208. AkUInt32 nameStrLen = AkMin((int)strlen(in_szThreadName), maxStrLen);
  209. MultiByteToWideChar(CP_UTF8, 0, in_szThreadName, nameStrLen, wszThreadName, maxStrLen);
  210. wszThreadName[nameStrLen] = '\0';
  211. SetThreadDescription(in_threadHnd, wszThreadName);
  212. #endif
  213. }
  214. /// Platform Independent Helper
  215. inline void AkCreateThread(
  216. AkThreadRoutine pStartRoutine, // Thread routine.
  217. void * pParams, // Routine params.
  218. const AkThreadProperties & in_threadProperties, // Properties. NULL for default.
  219. AkThread * out_pThread, // Returned thread handle.
  220. const char * in_szThreadName ) // Opt thread name.
  221. {
  222. AKASSERT( out_pThread != NULL );
  223. AKASSERT( (in_threadProperties.nPriority >= THREAD_PRIORITY_LOWEST && in_threadProperties.nPriority <= THREAD_PRIORITY_HIGHEST)
  224. || ( in_threadProperties.nPriority == THREAD_PRIORITY_TIME_CRITICAL )
  225. || ( in_threadProperties.nPriority == THREAD_MODE_BACKGROUND_BEGIN ) );
  226. DWORD dwThreadID;
  227. *out_pThread = ::CreateThread( NULL, // No security attributes
  228. in_threadProperties.uStackSize, // StackSize (0 uses system default)
  229. pStartRoutine, // Thread start routine
  230. pParams, // Thread function parameter
  231. CREATE_SUSPENDED, // Creation flags: create suspended so we can set priority/affinity before starting
  232. &dwThreadID );
  233. // ::CreateThread() return NULL if it fails.
  234. if ( !*out_pThread )
  235. {
  236. AkClearThread( out_pThread );
  237. return;
  238. }
  239. // Set thread name.
  240. if (in_szThreadName)
  241. {
  242. AkSetThreadName(*out_pThread, dwThreadID, in_szThreadName);
  243. }
  244. // Set properties.
  245. if ( !::SetThreadPriority( *out_pThread, in_threadProperties.nPriority ) &&
  246. in_threadProperties.nPriority != THREAD_MODE_BACKGROUND_BEGIN )
  247. {
  248. AKASSERT( !"Failed setting thread priority" );
  249. AkCloseThread( out_pThread );
  250. AkClearThread(out_pThread);
  251. return;
  252. }
  253. #ifdef AK_WIN_UNIVERSAL_APP
  254. if ( in_threadProperties.processorNumber.Number != MAXIMUM_PROCESSORS)
  255. {
  256. if ( !SetThreadIdealProcessorEx( *out_pThread, const_cast<PPROCESSOR_NUMBER>(&in_threadProperties.processorNumber), NULL) )
  257. {
  258. AKASSERT( !"Failed setting thread ideal processor" );
  259. AkCloseThread( out_pThread );
  260. AkClearThread(out_pThread);
  261. return;
  262. }
  263. }
  264. #else
  265. if (in_threadProperties.dwAffinityMask)
  266. {
  267. AkUInt32 dwAffinityMask = in_threadProperties.dwAffinityMask;
  268. DWORD_PTR procAffinity, sysAffinity;
  269. if (::GetProcessAffinityMask(::GetCurrentProcess(), &procAffinity, &sysAffinity))
  270. {
  271. // To avoid errors in SetThreadAffinityMask, make sure the user-supplied mask is a subset of what is allowed by the process
  272. dwAffinityMask &= procAffinity;
  273. }
  274. if (!::SetThreadAffinityMask(*out_pThread, dwAffinityMask))
  275. {
  276. AKASSERT(!"Failed setting thread affinity mask");
  277. AkCloseThread(out_pThread);
  278. AkClearThread(out_pThread);
  279. return;
  280. }
  281. }
  282. #endif
  283. // Thread is ready, start it up.
  284. if (!::ResumeThread(*out_pThread))
  285. {
  286. AKASSERT(!"Failed to start the thread");
  287. AkCloseThread(out_pThread);
  288. AkClearThread(out_pThread);
  289. return;
  290. }
  291. }
  292. /// Platform Independent Helper
  293. inline void AkWaitForSingleThread( AkThread * in_pThread )
  294. {
  295. AKASSERT( in_pThread );
  296. AKASSERT( *in_pThread );
  297. ::WaitForSingleObject( *in_pThread, INFINITE );
  298. }
  299. /// Returns the calling thread's ID.
  300. inline AkThreadID CurrentThread()
  301. {
  302. return ::GetCurrentThreadId();
  303. }
  304. /// Platform Independent Helper
  305. inline void AkSleep( AkUInt32 in_ulMilliseconds )
  306. {
  307. ::Sleep( in_ulMilliseconds );
  308. }
  309. // Optimized memory functions
  310. // --------------------------------------------------------------------
  311. /// Platform Independent Helper
  312. inline void AkMemCpy( void * pDest, const void * pSrc, AkUInt32 uSize )
  313. {
  314. memcpy( pDest, pSrc, uSize );
  315. }
  316. /// Platform Independent Helper
  317. inline void AkMemMove( void* pDest, const void* pSrc, AkUInt32 uSize )
  318. {
  319. memmove( pDest, pSrc, uSize );
  320. }
  321. /// Platform Independent Helper
  322. inline void AkMemSet( void * pDest, AkInt32 iVal, AkUInt32 uSize )
  323. {
  324. memset( pDest, iVal, uSize );
  325. }
  326. // Time functions
  327. // ------------------------------------------------------------------
  328. /// Platform Independent Helper
  329. inline void PerformanceCounter( AkInt64 * out_piLastTime )
  330. {
  331. ::QueryPerformanceCounter( (LARGE_INTEGER*)out_piLastTime );
  332. }
  333. /// Platform Independent Helper
  334. inline void PerformanceFrequency( AkInt64 * out_piFreq )
  335. {
  336. ::QueryPerformanceFrequency( (LARGE_INTEGER*)out_piFreq );
  337. }
  338. /// Platform Independent Helper
  339. inline void UpdatePerformanceFrequency()
  340. {
  341. AkInt64 iFreq;
  342. PerformanceFrequency( &iFreq );
  343. AK::g_fFreqRatio = (AkReal32)((AkReal64)iFreq / 1000);
  344. }
  345. /// Returns a time range in milliseconds, using the sound engine's updated count->milliseconds ratio.
  346. inline AkReal32 Elapsed( const AkInt64 & in_iNow, const AkInt64 & in_iStart )
  347. {
  348. return ( in_iNow - in_iStart ) / AK::g_fFreqRatio;
  349. }
  350. /// String conversion helper. If io_pszAnsiString is null, the function returns the required size.
  351. inline AkInt32 AkWideCharToChar( const wchar_t* in_pszUnicodeString,
  352. AkUInt32 in_uiOutBufferSize,
  353. char* io_pszAnsiString )
  354. {
  355. if(!io_pszAnsiString)
  356. return WideCharToMultiByte(CP_UTF8, 0, in_pszUnicodeString, -1, NULL, 0, NULL, NULL);
  357. int iWritten = ::WideCharToMultiByte(CP_UTF8, // code page
  358. 0, // performance and mapping flags
  359. in_pszUnicodeString, // wide-character string
  360. (int)AkMin( ( (AkUInt32)wcslen( in_pszUnicodeString )), in_uiOutBufferSize-1 ), // number of chars in string : -1 = NULL terminated string.
  361. io_pszAnsiString, // buffer for new string
  362. in_uiOutBufferSize, // size of buffer
  363. NULL, // default for unmappable chars
  364. NULL); // set when default char used
  365. io_pszAnsiString[iWritten] = 0;
  366. return iWritten;
  367. }
  368. /// String conversion helper
  369. inline AkInt32 AkCharToWideChar( const char* in_pszAnsiString,
  370. AkUInt32 in_uiOutBufferSize,
  371. void* io_pvUnicodeStringBuffer )
  372. {
  373. return ::MultiByteToWideChar( CP_UTF8, // code page
  374. 0, // performance and mapping flags
  375. in_pszAnsiString, // wide-character string
  376. -1, // number of chars in string : -1 = NULL terminated string.
  377. (wchar_t*)io_pvUnicodeStringBuffer, // buffer for new string
  378. in_uiOutBufferSize); // size of buffer
  379. }
  380. /// String conversion helper
  381. inline AkInt32 AkUtf8ToWideChar( const char* in_pszUtf8String,
  382. AkUInt32 in_uiOutBufferSize,
  383. void* io_pvUnicodeStringBuffer )
  384. {
  385. return ::MultiByteToWideChar( CP_UTF8, // code page
  386. 0, // performance and mapping flags
  387. in_pszUtf8String, // wide-character string
  388. -1, // number of chars in string : -1 = NULL terminated string.
  389. (wchar_t*)io_pvUnicodeStringBuffer, // buffer for new string
  390. in_uiOutBufferSize); // size of buffer
  391. }
  392. /// Safe unicode string copy.
  393. inline void SafeStrCpy( wchar_t * in_pDest, const wchar_t* in_pSrc, size_t in_uDestMaxNumChars )
  394. {
  395. size_t iSizeCopy = AkMin( in_uDestMaxNumChars - 1, wcslen( in_pSrc ) + 1 );
  396. wcsncpy_s( in_pDest, in_uDestMaxNumChars, in_pSrc, iSizeCopy );
  397. in_pDest[iSizeCopy] = '\0';
  398. }
  399. /// Safe string copy.
  400. inline void SafeStrCpy( char * in_pDest, const char* in_pSrc, size_t in_uDestMaxNumChars )
  401. {
  402. size_t iSizeCopy = AkMin( in_uDestMaxNumChars - 1, strlen( in_pSrc ) + 1 );
  403. strncpy_s( in_pDest, in_uDestMaxNumChars, in_pSrc, iSizeCopy );
  404. in_pDest[iSizeCopy] = '\0';
  405. }
  406. /// Safe unicode string concatenation.
  407. inline void SafeStrCat( wchar_t * in_pDest, const wchar_t* in_pSrc, size_t in_uDestMaxNumChars )
  408. {
  409. int iAvailableSize = (int)( in_uDestMaxNumChars - wcslen( in_pDest ) - 1 );
  410. wcsncat_s( in_pDest, in_uDestMaxNumChars, in_pSrc, AkMin( iAvailableSize, (int)wcslen( in_pSrc ) ) );
  411. }
  412. /// Safe string concatenation.
  413. inline void SafeStrCat( char * in_pDest, const char* in_pSrc, size_t in_uDestMaxNumChars )
  414. {
  415. int iAvailableSize = (int)( in_uDestMaxNumChars - strlen( in_pDest ) - 1 );
  416. strncat_s( in_pDest, in_uDestMaxNumChars, in_pSrc, AkMin( iAvailableSize, (int)strlen( in_pSrc ) ) );
  417. }
  418. inline int SafeStrFormat(wchar_t * in_pDest, size_t in_uDestMaxNumChars, const wchar_t* in_pszFmt, ...)
  419. {
  420. va_list args;
  421. va_start(args, in_pszFmt);
  422. int r = vswprintf(in_pDest, in_uDestMaxNumChars, in_pszFmt, args);
  423. va_end(args);
  424. return r;
  425. }
  426. inline int SafeStrFormat(char * in_pDest, size_t in_uDestMaxNumChars, const char* in_pszFmt, ...)
  427. {
  428. va_list args;
  429. va_start(args, in_pszFmt);
  430. int r = vsnprintf(in_pDest, in_uDestMaxNumChars, in_pszFmt, args);
  431. va_end(args);
  432. return r;
  433. }
  434. /// Stack allocations.
  435. #define AkAlloca( _size_ ) _alloca( _size_ )
  436. /// Output a debug message on the console
  437. #if ! defined(AK_OPTIMIZED)
  438. inline void OutputDebugMsg( const wchar_t* in_pszMsg )
  439. {
  440. OutputDebugStringW( in_pszMsg );
  441. }
  442. /// Output a debug message on the console
  443. inline void OutputDebugMsg( const char* in_pszMsg )
  444. {
  445. OutputDebugStringA( in_pszMsg );
  446. }
  447. /// Output a debug message on the console (variadic function).
  448. /// Use MaxSize to specify the size to reserve for the message.
  449. /// Warning: On Win32, OutputDebugMsgV with wchar_t will truncate the string
  450. /// to MaxSize.
  451. template <int MaxSize = 256>
  452. inline void OutputDebugMsgV(const wchar_t* in_pszFmt, ...)
  453. {
  454. // No equivalent of snprintf for wide string so truncate if necessary
  455. // vswprintf returns the number of characters written and not the numbers
  456. // that would be written
  457. wchar_t* msg = (wchar_t*)AkAlloca(MaxSize * sizeof(wchar_t));
  458. msg[MaxSize - 1] = '\0';
  459. va_list args;
  460. va_start(args, in_pszFmt);
  461. vswprintf(msg, MaxSize, in_pszFmt, args);
  462. va_end(args);
  463. OutputDebugMsg(msg);
  464. }
  465. /// Output a debug message on the console (variadic function).
  466. /// Use MaxSize to specify the expected size of the message.
  467. /// If the required size is superior to MaxSize, a new string
  468. /// will be allocated on the stack with the required size.
  469. template <int MaxSize = 256>
  470. inline void OutputDebugMsgV(const char* in_pszFmt, ...)
  471. {
  472. int size = 0;
  473. {
  474. // Try with a reasonable guess first
  475. char msg[MaxSize];
  476. msg[MaxSize - 1] = '\0';
  477. va_list args;
  478. va_start(args, in_pszFmt);
  479. size = vsnprintf(msg, MaxSize, in_pszFmt, args);
  480. va_end(args);
  481. // If it was enough, print to debug log
  482. if (0 <= size && size <= MaxSize)
  483. {
  484. OutputDebugMsg(msg);
  485. return;
  486. }
  487. }
  488. // Else, we need more memory to prevent truncation
  489. {
  490. // size + 1 more char for the last '\0'
  491. size++;
  492. char* msg = (char*)AkAlloca((size) * sizeof(char));
  493. msg[size - 1] = '\0';
  494. va_list args;
  495. va_start(args, in_pszFmt);
  496. vsnprintf(msg, size, in_pszFmt, args);
  497. va_end(args);
  498. OutputDebugMsg(msg);
  499. }
  500. }
  501. #else
  502. inline void OutputDebugMsg(const wchar_t*){}
  503. inline void OutputDebugMsg(const char*){}
  504. template <int MaxSize = 0>
  505. inline void OutputDebugMsgV(const wchar_t*, ...) {}
  506. template <int MaxSize = 0>
  507. inline void OutputDebugMsgV(const char*, ...) {}
  508. #endif
  509. /// Converts a wchar_t string to an AkOSChar string.
  510. /// \remark On some platforms the AkOSChar string simply points to the same string,
  511. /// on others a new buffer is allocated on the stack using AkAlloca. This means
  512. /// you must make sure that:
  513. /// - The source string stays valid and unmodified for as long as you need the
  514. /// AkOSChar string (for cases where they point to the same string)
  515. /// - The AkOSChar string is used within this scope only -- for example, do NOT
  516. /// return that string from a function (for cases where it is allocated on the stack)
  517. #define CONVERT_WIDE_TO_OSCHAR( _wstring_, _oscharstring_ ) ( _oscharstring_ ) = (AkOSChar*)( _wstring_ )
  518. /// Converts a char string to an AkOSChar string.
  519. /// \remark On some platforms the AkOSChar string simply points to the same string,
  520. /// on others a new buffer is allocated on the stack using AkAlloca. This means
  521. /// you must make sure that:
  522. /// - The source string stays valid and unmodified for as long as you need the
  523. /// AkOSChar string (for cases where they point to the same string)
  524. /// - The AkOSChar string is used within this scope only -- for example, do NOT
  525. /// return that string from a function (for cases where it is allocated on the stack)
  526. #define CONVERT_CHAR_TO_OSCHAR( _astring_, _oscharstring_ ) \
  527. _oscharstring_ = (AkOSChar*)AkAlloca( (1 + strlen( _astring_ )) * sizeof(AkOSChar)); \
  528. AKPLATFORM::AkCharToWideChar( _astring_, (AkUInt32)(1 + strlen(_astring_ )), (AkOSChar*)( _oscharstring_ ) )
  529. /// Converts a AkOSChar string into wide char string.
  530. /// \remark On some platforms the AkOSChar string simply points to the same string,
  531. /// on others a new buffer is allocated on the stack using AkAlloca. This means
  532. /// you must make sure that:
  533. /// - The source string stays valid and unmodified for as long as you need the
  534. /// AkOSChar string (for cases where they point to the same string)
  535. /// - The AkOSChar string is used within this scope only -- for example, do NOT
  536. /// return that string from a function (for cases where it is allocated on the stack)
  537. #define CONVERT_OSCHAR_TO_WIDE( _osstring_, _wstring_ ) _wstring_ = _osstring_
  538. /// Converts a AkOSChar string into char string.
  539. /// \remark On some platforms the AkOSChar string simply points to the same string,
  540. /// on others a new buffer is allocated on the stack using AkAlloca. This means
  541. /// you must make sure that:
  542. /// - The source string stays valid and unmodified for as long as you need the
  543. /// AkOSChar string (for cases where they point to the same string)
  544. /// - The AkOSChar string is used within this scope only -- for example, do NOT
  545. /// return that string from a function (for cases where it is allocated on the stack)
  546. #define CONVERT_OSCHAR_TO_CHAR( _osstring_, _astring_ ) \
  547. _astring_ = (char*)AkAlloca( 1 + AKPLATFORM::AkWideCharToChar( _osstring_, 0, NULL )); \
  548. AKPLATFORM::AkWideCharToChar( _osstring_, AkUInt32(1 + AKPLATFORM::AkWideCharToChar( _osstring_, 0, NULL )), _astring_ );
  549. /// Get the length, in characters, of a NULL-terminated AkUtf16 string
  550. /// \return The length, in characters, of the specified string (excluding terminating NULL)
  551. inline size_t AkUtf16StrLen( const AkUtf16* in_pStr )
  552. {
  553. return ( wcslen( in_pStr ) );
  554. }
  555. /// Get the length, in characters, of a NULL-terminated AkOSChar string
  556. /// \return The length, in characters, of the specified string (excluding terminating NULL)
  557. inline size_t OsStrLen( const AkOSChar* in_pszString )
  558. {
  559. return ( wcslen( in_pszString ) );
  560. }
  561. /// AkOSChar version of sprintf().
  562. #define AK_OSPRINTF swprintf_s
  563. /// Compare two NULL-terminated AkOSChar strings
  564. /// \return
  565. /// - \< 0 if in_pszString1 \< in_pszString2
  566. /// - 0 if the two strings are identical
  567. /// - \> 0 if in_pszString1 \> in_pszString2
  568. /// \remark The comparison is case-sensitive
  569. inline int OsStrCmp( const AkOSChar* in_pszString1, const AkOSChar* in_pszString2 )
  570. {
  571. return ( wcscmp( in_pszString1, in_pszString2 ) );
  572. }
  573. /// Compare two NULL-terminated AkOSChar strings up to the specified count of characters.
  574. /// \return
  575. /// - \< 0 if in_pszString1 \< in_pszString2
  576. /// - 0 if the two strings are identical
  577. /// - \> 0 if in_pszString1 \> in_pszString2
  578. /// \remark The comparison is case-sensitive
  579. inline int OsStrNCmp( const AkOSChar* in_pszString1, const AkOSChar* in_pszString2, size_t in_MaxCountSize)
  580. {
  581. return wcsncmp(in_pszString1, in_pszString2, in_MaxCountSize);
  582. }
  583. #define AK_UTF16_TO_WCHAR( in_pdDest, in_pSrc, in_MaxSize ) AKPLATFORM::SafeStrCpy( in_pdDest, in_pSrc, in_MaxSize )
  584. #define AK_WCHAR_TO_UTF16( in_pdDest, in_pSrc, in_MaxSize ) AKPLATFORM::SafeStrCpy( in_pdDest, in_pSrc, in_MaxSize )
  585. #define AK_UTF8_TO_OSCHAR( in_pdDest, in_pSrc, in_MaxSize ) AKPLATFORM::AkCharToWideChar( in_pSrc, in_MaxSize, in_pdDest )
  586. #define AK_UTF16_TO_OSCHAR( in_pdDest, in_pSrc, in_MaxSize ) AKPLATFORM::SafeStrCpy( in_pdDest, in_pSrc, in_MaxSize )
  587. #define AK_UTF16_TO_CHAR( in_pdDest, in_pSrc, in_MaxSize ) AKPLATFORM::AkWideCharToChar( in_pSrc, in_MaxSize, in_pdDest )
  588. #define AK_CHAR_TO_UTF16( in_pdDest, in_pSrc, in_MaxSize ) AKPLATFORM::AkCharToWideChar( in_pSrc, in_MaxSize, in_pdDest )
  589. #define AK_OSCHAR_TO_UTF16( in_pdDest, in_pSrc, in_MaxSize ) AKPLATFORM::SafeStrCpy( in_pdDest, in_pSrc, in_MaxSize )
  590. /// Detects whether the string represents an absolute path to a file
  591. inline bool IsAbsolutePath(const AkOSChar* in_pszPath, size_t in_pathLen)
  592. {
  593. return
  594. (in_pathLen >= 3 && in_pszPath[1] == ':' && in_pszPath[2] == '\\') || // Classic "C:\..." DOS-style path
  595. (in_pathLen >= 2 && in_pszPath[0] == '\\'); // Uncommon "\..." absolute path from current drive, or UNC "\\..."
  596. }
  597. // Use with AkOSChar.
  598. #define AK_PATH_SEPARATOR L"\\"
  599. #define AK_LIBRARY_PREFIX L""
  600. #define AK_DYNAMIC_LIBRARY_EXTENSION L".dll"
  601. #define AK_FILEHANDLE_TO_UINTPTR(_h) ((AkUIntPtr)_h)
  602. #define AK_SET_FILEHANDLE_TO_UINTPTR(_h,_u) _h = (AkFileHandle)_u
  603. #if defined(AK_ENABLE_PERF_RECORDING)
  604. static AkUInt32 g_uAkPerfRecExecCount = 0;
  605. static AkReal32 g_fAkPerfRecExecTime = 0.f;
  606. #define AK_PERF_RECORDING_RESET() \
  607. AKPLATFORM::g_uAkPerfRecExecCount = 0;\
  608. AKPLATFORM::g_fAkPerfRecExecTime = 0.f;
  609. #define AK_PERF_RECORDING_START( __StorageName__, __uExecutionCountStart__, __uExecutionCountStop__ ) \
  610. AkInt64 iAkPerfRecTimeBefore; \
  611. if ( (AKPLATFORM::g_uAkPerfRecExecCount >= (__uExecutionCountStart__)) && (AKPLATFORM::g_uAkPerfRecExecCount <= (__uExecutionCountStop__)) ) \
  612. AKPLATFORM::PerformanceCounter( &iAkPerfRecTimeBefore );
  613. #define AK_PERF_RECORDING_STOP( __StorageName__, __uExecutionCountStart__, __uExecutionCountStop__ ) \
  614. if ( (AKPLATFORM::g_uAkPerfRecExecCount >= (__uExecutionCountStart__)) && (AKPLATFORM::g_uAkPerfRecExecCount <= (__uExecutionCountStop__)) ) \
  615. { \
  616. AkInt64 iAkPerfRecTimeAfter; \
  617. AKPLATFORM::PerformanceCounter( &iAkPerfRecTimeAfter ); \
  618. AKPLATFORM::g_fAkPerfRecExecTime += AKPLATFORM::Elapsed( iAkPerfRecTimeAfter, iAkPerfRecTimeBefore ); \
  619. if ( AKPLATFORM::g_uAkPerfRecExecCount == (__uExecutionCountStop__) ) \
  620. { \
  621. AkReal32 fAverageExecutionTime = AKPLATFORM::g_fAkPerfRecExecTime/((__uExecutionCountStop__)-(__uExecutionCountStart__)); \
  622. AkOSChar str[256]; \
  623. swprintf_s(str, 256, AKTEXT("%s average execution time: %f\n"), AKTEXT(__StorageName__), fAverageExecutionTime);\
  624. AKPLATFORM::OutputDebugMsg( str ); \
  625. } \
  626. } \
  627. AKPLATFORM::g_uAkPerfRecExecCount++;
  628. #endif // AK_ENABLE_PERF_RECORDING
  629. #if (defined(AK_CPU_X86_64) || defined(AK_CPU_X86))
  630. /// Support to fetch the CPUID for the platform. Only valid for X86 targets
  631. /// \remark Note that IAkProcessorFeatures should be preferred to fetch this data
  632. /// as it will have already translated the feature bits into AK-relevant enums
  633. inline void CPUID(AkUInt32 in_uLeafOpcode, AkUInt32 in_uSubLeafOpcode, unsigned int out_uCPUFeatures[4])
  634. {
  635. __cpuidex((int*)out_uCPUFeatures, in_uLeafOpcode, in_uSubLeafOpcode);
  636. }
  637. #endif
  638. }
  639. #endif // _AK_PLATFORM_FUNCS_H_