Client.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Configuration.Hid;
  3. using Ryujinx.Common.Configuration.Hid.Controller;
  4. using Ryujinx.Common.Configuration.Hid.Controller.Motion;
  5. using Ryujinx.Common.Logging;
  6. using Ryujinx.Common.Memory;
  7. using Ryujinx.Input.HLE;
  8. using Ryujinx.Input.Motion.CemuHook.Protocol;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.IO.Hashing;
  13. using System.Net;
  14. using System.Net.Sockets;
  15. using System.Numerics;
  16. using System.Threading.Tasks;
  17. namespace Ryujinx.Input.Motion.CemuHook
  18. {
  19. public class Client : IDisposable
  20. {
  21. public const uint Magic = 0x43555344; // DSUC
  22. public const ushort Version = 1001;
  23. private bool _active;
  24. private readonly Dictionary<int, IPEndPoint> _hosts;
  25. private readonly Dictionary<int, Dictionary<int, MotionInput>> _motionData;
  26. private readonly Dictionary<int, UdpClient> _clients;
  27. private readonly bool[] _clientErrorStatus = new bool[Enum.GetValues<PlayerIndex>().Length];
  28. private readonly long[] _clientRetryTimer = new long[Enum.GetValues<PlayerIndex>().Length];
  29. private readonly NpadManager _npadManager;
  30. public Client(NpadManager npadManager)
  31. {
  32. _npadManager = npadManager;
  33. _hosts = new Dictionary<int, IPEndPoint>();
  34. _motionData = new Dictionary<int, Dictionary<int, MotionInput>>();
  35. _clients = new Dictionary<int, UdpClient>();
  36. CloseClients();
  37. }
  38. public void CloseClients()
  39. {
  40. _active = false;
  41. lock (_clients)
  42. {
  43. foreach (var client in _clients)
  44. {
  45. try
  46. {
  47. client.Value?.Dispose();
  48. }
  49. catch (SocketException socketException)
  50. {
  51. Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to dispose motion client. Error: {socketException.ErrorCode}");
  52. }
  53. }
  54. _hosts.Clear();
  55. _clients.Clear();
  56. _motionData.Clear();
  57. }
  58. }
  59. public void RegisterClient(int player, string host, int port)
  60. {
  61. if (_clients.ContainsKey(player) || !CanConnect(player))
  62. {
  63. return;
  64. }
  65. lock (_clients)
  66. {
  67. if (_clients.ContainsKey(player) || !CanConnect(player))
  68. {
  69. return;
  70. }
  71. UdpClient client = null;
  72. try
  73. {
  74. IPEndPoint endPoint = new(IPAddress.Parse(host), port);
  75. client = new UdpClient(host, port);
  76. _clients.Add(player, client);
  77. _hosts.Add(player, endPoint);
  78. _active = true;
  79. Task.Run(() =>
  80. {
  81. ReceiveLoop(player);
  82. });
  83. }
  84. catch (FormatException formatException)
  85. {
  86. if (!_clientErrorStatus[player])
  87. {
  88. Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to connect to motion source at {host}:{port}. Error: {formatException.Message}");
  89. _clientErrorStatus[player] = true;
  90. }
  91. }
  92. catch (SocketException socketException)
  93. {
  94. if (!_clientErrorStatus[player])
  95. {
  96. Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to connect to motion source at {host}:{port}. Error: {socketException.ErrorCode}");
  97. _clientErrorStatus[player] = true;
  98. }
  99. RemoveClient(player);
  100. client?.Dispose();
  101. SetRetryTimer(player);
  102. }
  103. catch (Exception exception)
  104. {
  105. Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to register motion client. Error: {exception.Message}");
  106. _clientErrorStatus[player] = true;
  107. RemoveClient(player);
  108. client?.Dispose();
  109. SetRetryTimer(player);
  110. }
  111. }
  112. }
  113. public bool TryGetData(int player, int slot, out MotionInput input)
  114. {
  115. lock (_motionData)
  116. {
  117. if (_motionData.TryGetValue(player, out Dictionary<int, MotionInput> value))
  118. {
  119. if (value.TryGetValue(slot, out input))
  120. {
  121. return true;
  122. }
  123. }
  124. }
  125. input = null;
  126. return false;
  127. }
  128. private void RemoveClient(int clientId)
  129. {
  130. _clients?.Remove(clientId);
  131. _hosts?.Remove(clientId);
  132. }
  133. private void Send(byte[] data, int clientId)
  134. {
  135. if (_clients.TryGetValue(clientId, out UdpClient client))
  136. {
  137. if (client != null && client.Client != null && client.Client.Connected)
  138. {
  139. try
  140. {
  141. client?.Send(data, data.Length);
  142. }
  143. catch (SocketException socketException)
  144. {
  145. if (!_clientErrorStatus[clientId])
  146. {
  147. Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to send data request to motion source at {client.Client.RemoteEndPoint}. Error: {socketException.ErrorCode}");
  148. }
  149. _clientErrorStatus[clientId] = true;
  150. RemoveClient(clientId);
  151. client?.Dispose();
  152. SetRetryTimer(clientId);
  153. }
  154. catch (ObjectDisposedException)
  155. {
  156. _clientErrorStatus[clientId] = true;
  157. RemoveClient(clientId);
  158. client?.Dispose();
  159. SetRetryTimer(clientId);
  160. }
  161. }
  162. }
  163. }
  164. private byte[] Receive(int clientId, int timeout = 0)
  165. {
  166. if (_hosts.TryGetValue(clientId, out IPEndPoint endPoint) && _clients.TryGetValue(clientId, out UdpClient client))
  167. {
  168. if (client != null && client.Client != null && client.Client.Connected)
  169. {
  170. client.Client.ReceiveTimeout = timeout;
  171. var result = client?.Receive(ref endPoint);
  172. if (result.Length > 0)
  173. {
  174. _clientErrorStatus[clientId] = false;
  175. }
  176. return result;
  177. }
  178. }
  179. throw new Exception($"Client {clientId} is not registered.");
  180. }
  181. private void SetRetryTimer(int clientId)
  182. {
  183. var elapsedMs = PerformanceCounter.ElapsedMilliseconds;
  184. _clientRetryTimer[clientId] = elapsedMs;
  185. }
  186. private void ResetRetryTimer(int clientId)
  187. {
  188. _clientRetryTimer[clientId] = 0;
  189. }
  190. private bool CanConnect(int clientId)
  191. {
  192. return _clientRetryTimer[clientId] == 0 || PerformanceCounter.ElapsedMilliseconds - 5000 > _clientRetryTimer[clientId];
  193. }
  194. public void ReceiveLoop(int clientId)
  195. {
  196. if (_hosts.TryGetValue(clientId, out IPEndPoint endPoint) && _clients.TryGetValue(clientId, out UdpClient client))
  197. {
  198. if (client != null && client.Client != null && client.Client.Connected)
  199. {
  200. try
  201. {
  202. while (_active)
  203. {
  204. byte[] data = Receive(clientId);
  205. if (data.Length == 0)
  206. {
  207. continue;
  208. }
  209. Task.Run(() => HandleResponse(data, clientId));
  210. }
  211. }
  212. catch (SocketException socketException)
  213. {
  214. if (!_clientErrorStatus[clientId])
  215. {
  216. Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to receive data from motion source at {endPoint}. Error: {socketException.ErrorCode}");
  217. }
  218. _clientErrorStatus[clientId] = true;
  219. RemoveClient(clientId);
  220. client?.Dispose();
  221. SetRetryTimer(clientId);
  222. }
  223. catch (ObjectDisposedException)
  224. {
  225. _clientErrorStatus[clientId] = true;
  226. RemoveClient(clientId);
  227. client?.Dispose();
  228. SetRetryTimer(clientId);
  229. }
  230. }
  231. }
  232. }
  233. public void HandleResponse(byte[] data, int clientId)
  234. {
  235. ResetRetryTimer(clientId);
  236. MessageType type = (MessageType)BitConverter.ToUInt32(data.AsSpan().Slice(16, 4));
  237. data = data.AsSpan()[16..].ToArray();
  238. using MemoryStream stream = new(data);
  239. using BinaryReader reader = new(stream);
  240. switch (type)
  241. {
  242. case MessageType.Protocol:
  243. break;
  244. case MessageType.Info:
  245. ControllerInfoResponse contollerInfo = reader.ReadStruct<ControllerInfoResponse>();
  246. break;
  247. case MessageType.Data:
  248. ControllerDataResponse inputData = reader.ReadStruct<ControllerDataResponse>();
  249. Vector3 accelerometer = new()
  250. {
  251. X = -inputData.AccelerometerX,
  252. Y = inputData.AccelerometerZ,
  253. Z = -inputData.AccelerometerY,
  254. };
  255. Vector3 gyroscrope = new()
  256. {
  257. X = inputData.GyroscopePitch,
  258. Y = inputData.GyroscopeRoll,
  259. Z = -inputData.GyroscopeYaw,
  260. };
  261. ulong timestamp = inputData.MotionTimestamp;
  262. InputConfig config = _npadManager.GetPlayerInputConfigByIndex(clientId);
  263. lock (_motionData)
  264. {
  265. // Sanity check the configuration state and remove client if needed if needed.
  266. if (config is StandardControllerInputConfig controllerConfig &&
  267. controllerConfig.Motion.EnableMotion &&
  268. controllerConfig.Motion.MotionBackend == MotionInputBackendType.CemuHook &&
  269. controllerConfig.Motion is CemuHookMotionConfigController cemuHookConfig)
  270. {
  271. int slot = inputData.Shared.Slot;
  272. if (_motionData.TryGetValue(clientId, out var motionDataItem))
  273. {
  274. if (motionDataItem.TryGetValue(slot, out var previousData))
  275. {
  276. previousData.Update(accelerometer, gyroscrope, timestamp, cemuHookConfig.Sensitivity, (float)cemuHookConfig.GyroDeadzone);
  277. }
  278. else
  279. {
  280. MotionInput input = new();
  281. input.Update(accelerometer, gyroscrope, timestamp, cemuHookConfig.Sensitivity, (float)cemuHookConfig.GyroDeadzone);
  282. motionDataItem.Add(slot, input);
  283. }
  284. }
  285. else
  286. {
  287. MotionInput input = new();
  288. input.Update(accelerometer, gyroscrope, timestamp, cemuHookConfig.Sensitivity, (float)cemuHookConfig.GyroDeadzone);
  289. _motionData.Add(clientId, new Dictionary<int, MotionInput> { { slot, input } });
  290. }
  291. }
  292. else
  293. {
  294. RemoveClient(clientId);
  295. }
  296. }
  297. break;
  298. }
  299. }
  300. public void RequestInfo(int clientId, int slot)
  301. {
  302. if (!_active)
  303. {
  304. return;
  305. }
  306. Header header = GenerateHeader(clientId);
  307. using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
  308. using BinaryWriter writer = new(stream);
  309. writer.WriteStruct(header);
  310. ControllerInfoRequest request = new()
  311. {
  312. Type = MessageType.Info,
  313. PortsCount = 4,
  314. };
  315. request.PortIndices[0] = (byte)slot;
  316. writer.WriteStruct(request);
  317. header.Length = (ushort)(stream.Length - 16);
  318. writer.Seek(6, SeekOrigin.Begin);
  319. writer.Write(header.Length);
  320. Crc32.Hash(stream.ToArray(), header.Crc32.AsSpan());
  321. writer.Seek(8, SeekOrigin.Begin);
  322. writer.Write(header.Crc32.AsSpan());
  323. byte[] data = stream.ToArray();
  324. Send(data, clientId);
  325. }
  326. public void RequestData(int clientId, int slot)
  327. {
  328. if (!_active)
  329. {
  330. return;
  331. }
  332. Header header = GenerateHeader(clientId);
  333. using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
  334. using BinaryWriter writer = new(stream);
  335. writer.WriteStruct(header);
  336. ControllerDataRequest request = new()
  337. {
  338. Type = MessageType.Data,
  339. Slot = (byte)slot,
  340. SubscriberType = SubscriberType.Slot,
  341. };
  342. writer.WriteStruct(request);
  343. header.Length = (ushort)(stream.Length - 16);
  344. writer.Seek(6, SeekOrigin.Begin);
  345. writer.Write(header.Length);
  346. Crc32.Hash(stream.ToArray(), header.Crc32.AsSpan());
  347. writer.Seek(8, SeekOrigin.Begin);
  348. writer.Write(header.Crc32.AsSpan());
  349. byte[] data = stream.ToArray();
  350. Send(data, clientId);
  351. }
  352. private static Header GenerateHeader(int clientId)
  353. {
  354. Header header = new()
  355. {
  356. Id = (uint)clientId,
  357. MagicString = Magic,
  358. Version = Version,
  359. Length = 0,
  360. };
  361. return header;
  362. }
  363. public void Dispose()
  364. {
  365. GC.SuppressFinalize(this);
  366. _active = false;
  367. CloseClients();
  368. }
  369. }
  370. }