Client.cs 15 KB

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