Client.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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 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 IPEndPoint(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.ContainsKey(player))
  118. {
  119. if (_motionData[player].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 MemoryStream(data);
  239. using BinaryReader reader = new BinaryReader(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 Vector3()
  250. {
  251. X = -inputData.AccelerometerX,
  252. Y = inputData.AccelerometerZ,
  253. Z = -inputData.AccelerometerY
  254. };
  255. Vector3 gyroscrope = new Vector3()
  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.ContainsKey(clientId))
  273. {
  274. if (_motionData[clientId].ContainsKey(slot))
  275. {
  276. MotionInput previousData = _motionData[clientId][slot];
  277. previousData.Update(accelerometer, gyroscrope, timestamp, cemuHookConfig.Sensitivity, (float)cemuHookConfig.GyroDeadzone);
  278. }
  279. else
  280. {
  281. MotionInput input = new MotionInput();
  282. input.Update(accelerometer, gyroscrope, timestamp, cemuHookConfig.Sensitivity, (float)cemuHookConfig.GyroDeadzone);
  283. _motionData[clientId].Add(slot, input);
  284. }
  285. }
  286. else
  287. {
  288. MotionInput input = new MotionInput();
  289. input.Update(accelerometer, gyroscrope, timestamp, cemuHookConfig.Sensitivity, (float)cemuHookConfig.GyroDeadzone);
  290. _motionData.Add(clientId, new Dictionary<int, MotionInput>() { { slot, input } });
  291. }
  292. }
  293. else
  294. {
  295. RemoveClient(clientId);
  296. }
  297. }
  298. break;
  299. }
  300. }
  301. public void RequestInfo(int clientId, int slot)
  302. {
  303. if (!_active)
  304. {
  305. return;
  306. }
  307. Header header = GenerateHeader(clientId);
  308. using (MemoryStream stream = MemoryStreamManager.Shared.GetStream())
  309. using (BinaryWriter writer = new BinaryWriter(stream))
  310. {
  311. writer.WriteStruct(header);
  312. ControllerInfoRequest request = new ControllerInfoRequest()
  313. {
  314. Type = MessageType.Info,
  315. PortsCount = 4
  316. };
  317. request.PortIndices[0] = (byte)slot;
  318. writer.WriteStruct(request);
  319. header.Length = (ushort)(stream.Length - 16);
  320. writer.Seek(6, SeekOrigin.Begin);
  321. writer.Write(header.Length);
  322. Crc32.Hash(stream.ToArray(), header.Crc32.AsSpan());
  323. writer.Seek(8, SeekOrigin.Begin);
  324. writer.Write(header.Crc32.AsSpan());
  325. byte[] data = stream.ToArray();
  326. Send(data, clientId);
  327. }
  328. }
  329. public unsafe void RequestData(int clientId, int slot)
  330. {
  331. if (!_active)
  332. {
  333. return;
  334. }
  335. Header header = GenerateHeader(clientId);
  336. using (MemoryStream stream = MemoryStreamManager.Shared.GetStream())
  337. using (BinaryWriter writer = new BinaryWriter(stream))
  338. {
  339. writer.WriteStruct(header);
  340. ControllerDataRequest request = new ControllerDataRequest()
  341. {
  342. Type = MessageType.Data,
  343. Slot = (byte)slot,
  344. SubscriberType = SubscriberType.Slot
  345. };
  346. writer.WriteStruct(request);
  347. header.Length = (ushort)(stream.Length - 16);
  348. writer.Seek(6, SeekOrigin.Begin);
  349. writer.Write(header.Length);
  350. Crc32.Hash(stream.ToArray(), header.Crc32.AsSpan());
  351. writer.Seek(8, SeekOrigin.Begin);
  352. writer.Write(header.Crc32.AsSpan());
  353. byte[] data = stream.ToArray();
  354. Send(data, clientId);
  355. }
  356. }
  357. private Header GenerateHeader(int clientId)
  358. {
  359. Header header = new Header()
  360. {
  361. Id = (uint)clientId,
  362. MagicString = Magic,
  363. Version = Version,
  364. Length = 0
  365. };
  366. return header;
  367. }
  368. public void Dispose()
  369. {
  370. _active = false;
  371. CloseClients();
  372. }
  373. }
  374. }