AkWaapiClient.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /*******************************************************************************
  2. The content of this file includes portions of the proprietary AUDIOKINETIC Wwise
  3. Technology released in source code form as part of the game integration package.
  4. The content of this file may not be used without valid licenses to the
  5. AUDIOKINETIC Wwise Technology.
  6. Note that the use of the game engine is subject to the Unreal(R) Engine End User
  7. License Agreement at https://www.unrealengine.com/en-US/eula/unreal
  8. License Usage
  9. Licensees holding valid licenses to the AUDIOKINETIC Wwise Technology may use
  10. this file in accordance with the end user license agreement provided with the
  11. software or, alternatively, in accordance with the terms contained
  12. in a written agreement between you and Audiokinetic Inc.
  13. Copyright (c) 2023 Audiokinetic Inc.
  14. *******************************************************************************/
  15. /*=============================================================================
  16. AkWaapiClient.h: Audiokinetic WAAPI interface object.
  17. =============================================================================*/
  18. #pragma once
  19. /*------------------------------------------------------------------------------------
  20. AkWaapiClient system headers.
  21. ------------------------------------------------------------------------------------*/
  22. #include "AkInclude.h"
  23. #include "HAL/Runnable.h"
  24. #include "Dom/JsonObject.h"
  25. #include "HAL/ThreadSafeBool.h"
  26. /*------------------------------------------------------------------------------------
  27. Dependencies, helpers & forward declarations.
  28. ------------------------------------------------------------------------------------*/
  29. /** Defines WampEventCallback delegate interface */
  30. DECLARE_DELEGATE_TwoParams(WampEventCallback, uint64_t, TSharedPtr<FJsonObject>);
  31. /** Events fired when WAAPI connection is started or lost */
  32. DECLARE_EVENT(FAkWaapiClient, WwiseProjectLoaded);
  33. DECLARE_EVENT(FAkWaapiClient, WAAPIConnectionLost);
  34. DECLARE_EVENT(FAkWaapiClient, BeginDestroyClient);
  35. #define WAAPI_LOCAL_HOST_IP_STRING "127.0.0.1"
  36. #define WAAPI_PORT 8080
  37. /*------------------------------------------------------------------------------------
  38. - FAkWaapiClientConnectionHandler
  39. ------------------------------------------------------------------------------------*/
  40. class FAkWaapiClient;
  41. struct KeyValueArgs
  42. {
  43. const FString KeyArg;
  44. const FString ValueArg;
  45. };
  46. class FAkWaapiClientConnectionHandler : public FRunnable
  47. {
  48. public:
  49. FAkWaapiClientConnectionHandler(FAkWaapiClient& in_Client);
  50. ~FAkWaapiClientConnectionHandler();
  51. // FRunnable interface.
  52. virtual bool Init() override;
  53. virtual uint32 Run() override;
  54. virtual void Stop() override;
  55. virtual void Exit() override;
  56. void ResetReconnectionDelay();
  57. void RegisterAutoConnectChangedCallback();
  58. void Wake();
  59. private:
  60. FThreadSafeBool ThreadShouldExit = false;
  61. FThreadSafeCounter ReconnectDelay = 2;
  62. FThreadSafeCounter ConnectionMonitorDelay = 7;
  63. FThreadSafeCounter LogOutputCount = 0;
  64. int m_iMaxReconnectDelay = 32;
  65. FEvent* WaitEvent;
  66. FCriticalSection AkSettingsSection;
  67. FAkWaapiClient& m_Client;
  68. bool hadConnection = false;
  69. bool AttemptReconnect();
  70. FDelegateHandle AutoConnectChangedHandle;
  71. };
  72. /*------------------------------------------------------------------------------------
  73. AkWaapiClient audio device.
  74. ------------------------------------------------------------------------------------*/
  75. class AKAUDIO_API FAkWaapiClient
  76. {
  77. public:
  78. virtual ~FAkWaapiClient();
  79. /**
  80. * Initialize the singleton instance of FAkWaapiClient.
  81. * The singleton instance owns a connection thread which will monitor the WAAPI connection.
  82. * This function should therefore be called once, in the module startup function, such that WAAPI is ready to be used, if available.
  83. */
  84. static void Initialize();
  85. /**
  86. * Obtain a pointer to the singleton instance of FAkWaapiClient.
  87. * Be sure to call FAkWaapiClient::Initialize() first (i.e. during Module startup).
  88. *
  89. * @return Pointer to the singleton instance of FAkWaapiClient.
  90. */
  91. static FAkWaapiClient* Get();
  92. /**
  93. * Delete the singleton instance of FAkWaapiClient.
  94. */
  95. static void DeleteInstance();
  96. /**
  97. * Obtain a pointer to the delegate associated to the in_subscriptionId
  98. *
  99. * @return Pointer to the delegate associated to the in_subscriptionId
  100. */
  101. WampEventCallback* GetWampEventCallback(const uint64_t& in_subscriptionId);
  102. /**
  103. * Allows clients to subscribe to notifications according to the event.
  104. *
  105. * @param in_jsonObject An FJsonObject that we want to convert to string.
  106. * @param ou_jsonObjectString The result of conversation in string format.
  107. * @return A boolean to ensure that the conversion was successfully done.
  108. */
  109. static bool JsonObjectToString(const TSharedRef<FJsonObject>& in_jsonObject, FString& ou_jsonObjectString);
  110. bool IsConnected();
  111. bool AttemptConnection();
  112. /** Checks whether the current project is dirty */
  113. static bool IsProjectDirty();
  114. /**
  115. * Allows clients to subscribe to notifications according to the event.
  116. *
  117. * @param in_uri The reference to the event that we would be aware of when it happens.
  118. * @param in_options Optional flag to get more information about the event happened.
  119. * @param in_callback A delegate to be executed during the subscription event.
  120. * @param out_subscriptionId Gets the id of this subscription.
  121. * @param out_result A JSON object that contains useful information about the subscription process to a specific event, gets an error infos in case the subscription failed.
  122. * @return A boolean to ensure that the subscription was successfully done.
  123. */
  124. bool Subscribe(const char* in_uri, const FString& in_options, WampEventCallback in_callback,
  125. uint64& out_subscriptionId, FString& out_result, int in_iTimeoutMs = 500);
  126. bool Subscribe(const char* in_uri, const TSharedRef<FJsonObject>& in_options, WampEventCallback in_callback,
  127. uint64& out_subscriptionId, TSharedPtr<FJsonObject>& out_result, int in_iTimeoutMs = 500);
  128. /**
  129. * Unsubscribe to notifications
  130. *
  131. * @param in_subscriptionId Gets the id of the current subscription to the event from which we want to be unsubscribed.
  132. * @param out_result A JSON object that contains useful information about the unsubscription process from a specific event, gets an error infos in case the unsubscription failed.
  133. * @return A boolean to ensure that the unsubscription was successfully done.
  134. */
  135. bool Unsubscribe(const uint64_t& in_subscriptionId, FString& out_result, int in_iTimeoutMs = 500, bool in_bSilenceLog = false);
  136. bool Unsubscribe(const uint64_t& in_subscriptionId, TSharedPtr<FJsonObject>& out_result, int in_iTimeoutMs = 500, bool in_bSilenceLog = false);
  137. /**
  138. * Remove manually the WampEventCallback, used by the WAAPI picker when the connection is lost
  139. *
  140. * @param in_subscriptionId The subscription id to the event from which we want to be unsubscribed.
  141. */
  142. bool RemoveWampEventCallback(const uint64_t in_subscriptionId);
  143. /**
  144. *
  145. *
  146. * @param in_uri The Function that will be called when an event that we would be aware of happens.
  147. * @param in_args The arguments referenced to the in_uri function.
  148. * @param in_options Optional flag to get more information about the event happened.
  149. * @param out_result A JSON object that contains useful information about the Call process to a specific event, gets an error infos in case the Call fails.
  150. * @return A boolean to ensure that the call was successfully passed.
  151. */
  152. bool Call(const char* in_uri, const FString& in_args, const FString& in_options, FString& out_result, int in_iTimeoutMs = 500, bool silenceLog = false);
  153. bool Call(const char* in_uri, const TSharedRef<FJsonObject>& in_args, const TSharedRef<FJsonObject>& in_options,
  154. TSharedPtr<FJsonObject>& out_result, int in_iTimeoutMs = 500, bool silenceLog = false);
  155. /**
  156. * Call WAAPI to change the object name form the path or the id of the object (inFromIdOrPath).
  157. *
  158. * @param inUri The Unique Resource Identifier used to indicate a specific action to WAAPI; i.e. ak::wwise::core::object::setName
  159. * @param Values An array that contains the pair of field and field value; e.i. when asking WAAPI to rename an item, the arguments are like this : {{object,id},{value,newname}}
  160. * @return A boolean to ensure that the call was successfully done.
  161. */
  162. bool Call(const char* inUri, const TArray<KeyValueArgs>& Values, TSharedPtr<FJsonObject>& outJsonResult);
  163. /** Sets in_outParentGUID to the object ID of a parent of object in_objectGUID of type in_strType. */
  164. static void GetParentOfType(FGuid in_objectGUID, FGuid& in_outParentGUID, FString in_strType);
  165. /** Gets the path of the currently loaded project in Wwise Authoring. */
  166. static bool GetProjectPath(TSharedPtr<FJsonObject>& inOutJsonResult, FString& ProjectPath);
  167. WwiseProjectLoaded OnProjectLoaded;
  168. WAAPIConnectionLost OnConnectionLost;
  169. BeginDestroyClient OnClientBeginDestroy;
  170. /** This is called when the reconnection handler successfully connects to WAAPI.
  171. * We check if the correct project is loaded on a background thread. If it is, we broadcast OnProjectLoaded.
  172. * We also subscribe to ak::wwise::core::project::loaded in order to check the project whenever one is loaded.
  173. * If an incorrect project is loaded we broadcast OnConnectionLost.
  174. */
  175. void ConnectionEstablished();
  176. void BroadcastConnectionLost();
  177. static bool IsProjectLoaded();
  178. /**
  179. * Indicates that the connection to WAAPI should be stopped and shouldn't be reconnected.
  180. */
  181. bool IsDisconnecting();
  182. bool AppIsExiting();
  183. void SetConnectionClosing(bool isClosing);
  184. /**
  185. * Since it's a singleton WaapiClient, we want to make sure these methods (copying constructor and assignment operator).
  186. * are unacceptable otherwise we may accidentally get copies of our WaapiClient singleton appearing.
  187. */
  188. FAkWaapiClient(FAkWaapiClient const&) = delete;
  189. void operator=(FAkWaapiClient const&) = delete;
  190. //===================================================================================================
  191. // WAAPI enums
  192. //===================================================================================================
  193. enum class WAAPIGetFromOption : AkUInt16
  194. {
  195. ID = 0,
  196. SEARCH,
  197. PATH,
  198. OF_TYPE,
  199. QUERY
  200. };
  201. static FString GetFromOptionString(WAAPIGetFromOption from);
  202. enum class WAAPIGetTransformOption : AkUInt16
  203. {
  204. SELECT = 0,
  205. RANGE,
  206. WHERE,
  207. NONE
  208. };
  209. static FString GetTransformOptionString(WAAPIGetTransformOption transform);
  210. enum class WAAPIGetReturnOptionFlag : AkInt64
  211. {
  212. ID = 0x1,
  213. NAME = 0x2,
  214. NOTES = 0x4,
  215. TYPE = 0x8,
  216. PATH = 0x10,
  217. PARENT = 0x20,
  218. OWNER = 0x40,
  219. IS_PLAYABLE = 0x80,
  220. SHORT_ID = 0x100,
  221. CATEGORY = 0x200,
  222. FILEPATH = 0x400,
  223. WORKUNIT = 0x800,
  224. CHILDREN_COUNT = 0x1000,
  225. MUSIC_TRANSITION_ROOT = 0x2000,
  226. MUSIC_PLAYLIST_ROOT = 0x4000,
  227. SOUND_ORIGINAL_WAV_FILE_PATH = 0x8000,
  228. SOUND_CONVERTED_WEM_FILE_PATH = 0x10000,
  229. SOUNDBANK_BANK_FILE_PATH = 0x20000,
  230. AUDIO_SOURCE_PLAYBACK_DURATION = 0x40000,
  231. AUDIO_SOURCE_MAX_DURATION_SOURCE = 0x80000,
  232. AUDIO_SOURCE_TRIM_VALUES = 0x100000,
  233. WORKUNIT_IS_DEFAULT = 0x200000,
  234. WORKUNIT_TYPE = 0x400000,
  235. WORKUNIT_IS_DIRTY = 0x800000,
  236. NUM_FLAGS = 0x19
  237. };
  238. //===================================================================================================
  239. // WAAPI JSon Helpers
  240. //===================================================================================================
  241. /** Returns a shared reference to a FJsonObject with the requested WAAPI FROM and TRANSFORM items. */
  242. static TSharedRef<FJsonObject> CreateWAAPIGetArgumentJson(WAAPIGetFromOption in_FromOption, TArray<TSharedPtr<FJsonValue>> in_FromItems,
  243. WAAPIGetTransformOption in_TransformOption = WAAPIGetTransformOption::NONE,
  244. TArray<TSharedPtr<FJsonValue>> in_TransformItems = TArray<TSharedPtr<FJsonValue>>());
  245. /** Returns a shared reference to a FJsonObject with the requested WAAPI RETURN options. */
  246. static TSharedRef<FJsonObject> CreateWAAPIGetReturnOptionsJson(AkInt64 ReturnOptions);
  247. static WAAPIGetReturnOptionFlag GetReturnOptionFlagValue(int in_iFlagIndex);
  248. /** Returns the correct string for a given WAAPI RETURN option. */
  249. static FString GetReturnOptionString(WAAPIGetReturnOptionFlag returnOption);
  250. /** Calls wwise.core.object.get with the given WAAPI FROM, RETURN, and TRANSFORM items.*/
  251. static bool WAAPIGet(WAAPIGetFromOption inFromField,
  252. TArray<TSharedPtr<FJsonValue>> inFromItems,
  253. AkInt64 inReturnOptionsFlags,
  254. TSharedPtr<FJsonObject>& outJsonResult,
  255. WAAPIGetTransformOption inTransformField = WAAPIGetTransformOption::NONE,
  256. TArray<TSharedPtr<FJsonValue>> inTransformItems = TArray<TSharedPtr<FJsonValue>>(),
  257. bool in_bSilenceLog = false);
  258. /** Searches for an object of type in_sTypeName with name in_sName via WAAPI. */
  259. static bool GetGUIDForObjectOfTypeWithName(FGuid& io_GUID, const FString& in_sTypeName, const FString& in_sName);
  260. /** Saves the Wwise project via WAAPI.*/
  261. static void SaveProject();
  262. //===================================================================================================
  263. // WAAPI Strings
  264. //===================================================================================================
  265. struct WAAPIStrings
  266. {
  267. static const FString BACK_SLASH;
  268. static const FString ID;
  269. static const FString RETURN;
  270. static const FString PATH;
  271. static const FString FILEPATH;
  272. static const FString FROM;
  273. static const FString NAME;
  274. static const FString TYPE;
  275. static const FString CHILDREN;
  276. static const FString CHILDREN_COUNT;
  277. static const FString ANCESTORS;
  278. static const FString DESCENDANTS;
  279. static const FString WORKUNIT_TYPE;
  280. static const FString FOLDER;
  281. static const FString PHYSICAL_FOLDER;
  282. static const FString SEARCH;
  283. static const FString PARENT;
  284. static const FString SELECT;
  285. static const FString TRANSFORM;
  286. static const FString OBJECT;
  287. static const FString OBJECTS;
  288. static const FString VALUE;
  289. static const FString COMMAND;
  290. static const FString TRANSPORT;
  291. static const FString ACTION;
  292. static const FString PLAY;
  293. static const FString STOP;
  294. static const FString STOPPED;
  295. static const FString DISPLAY_NAME;
  296. static const FString DELETE_ITEMS;
  297. static const FString DRAG_DROP_ITEMS;
  298. static const FString UNDO;
  299. static const FString REDO;
  300. static const FString STATE;
  301. static const FString OF_TYPE;
  302. static const FString PROJECT;
  303. static const FString PROPERTY;
  304. static const FString VOLUME;
  305. static const FString FIND_IN_PROJECT_EXPLORER;
  306. static const FString TRIMMED_DURATION;
  307. };
  308. struct WwiseTypeStrings
  309. {
  310. static const FString SOUND;
  311. static const FString WORKUNIT;
  312. };
  313. struct AudioPeaksStrings
  314. {
  315. struct Args
  316. {
  317. static const FString OBJECT;
  318. static const FString NUM_PEAKS;
  319. static const FString TIME_FROM;
  320. static const FString TIME_TO;
  321. static const FString CROSS_CHANNEL_PEAKS;
  322. };
  323. struct Results
  324. {
  325. static const FString PEAKS_BINARY;
  326. static const FString MAX_ABS_VALUE;
  327. static const FString PEAKS_ARRAY_LENGTH;
  328. static const FString PEAKS_DATA_SIZE;
  329. };
  330. };
  331. struct PropertyChangedStrings
  332. {
  333. struct RequiredOptions
  334. {
  335. static const FString OBJECT;
  336. static const FString PROPERTY;
  337. };
  338. struct OptionalOptions
  339. {
  340. static const FString RETURN;
  341. static const FString PLATFORM;
  342. };
  343. };
  344. struct AudioSourceProperties
  345. {
  346. static const FString TRIM_END;
  347. static const FString TRIM_BEGIN;
  348. };
  349. struct PlaybackDurationStrings
  350. {
  351. static const FString MIN;
  352. static const FString MAX;
  353. static const FString TYPE;
  354. };
  355. struct TrimValuesStrings
  356. {
  357. static const FString TRIM_BEGIN;
  358. static const FString TRIM_END;
  359. };
  360. bool bIsWrongProjectLoaded = false;
  361. private:
  362. /**
  363. * Since it's a singleton WaapiClient, we want to make sure this method (default constructor).
  364. * is inaccessible otherwise we may accidentally get instances of our WaapiClient singleton appearing.
  365. */
  366. FAkWaapiClient();
  367. /** Checks if the currently loaded Wwise project matches the project path set in AkSettings (Wwise plugin settings).
  368. * NOTE: This function will block while Wwise has a modal window open. It should not be called on the Game thread.
  369. */
  370. static bool CheckProjectLoaded();
  371. struct FAkWaapiClientImpl* m_Impl;
  372. };