FurioosSignaling.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. using System;
  2. using System.Text;
  3. using System.Threading;
  4. using Unity.WebRTC;
  5. using UnityEngine;
  6. using WebSocketSharp;
  7. namespace Unity.RenderStreaming.Signaling
  8. {
  9. [Serializable]
  10. public class FurioosRoutedMessage<T>
  11. {
  12. public string from;
  13. public string to;
  14. public T message;
  15. }
  16. [Flags]
  17. enum SslProtocolsHack
  18. {
  19. Tls = 192,
  20. Tls11 = 768,
  21. Tls12 = 3072
  22. }
  23. public class FurioosSignaling : ISignaling
  24. {
  25. private float m_timeout;
  26. private bool m_running;
  27. private SynchronizationContext m_mainThreadContext;
  28. private Thread m_signalingThread;
  29. private AutoResetEvent m_wsCloseEvent;
  30. private WebSocket m_webSocket;
  31. public delegate void OnSignedInHandler(ISignaling sender);
  32. public string Url { get { return string.Empty; } }
  33. public FurioosSignaling(SignalingSettings signalingSettings, SynchronizationContext mainThreadContext)
  34. {
  35. m_timeout = 5.0f;
  36. m_mainThreadContext = mainThreadContext;
  37. m_wsCloseEvent = new AutoResetEvent(false);
  38. }
  39. public string connectionId
  40. {
  41. get
  42. {
  43. throw new NotImplementedException();
  44. }
  45. }
  46. public void Start()
  47. {
  48. m_running = true;
  49. m_signalingThread = new Thread(WSManage);
  50. m_signalingThread.Start();
  51. }
  52. public void Stop()
  53. {
  54. if (m_running)
  55. {
  56. m_running = false;
  57. m_webSocket.Close();
  58. if (m_signalingThread.ThreadState == ThreadState.WaitSleepJoin)
  59. {
  60. m_signalingThread.Abort();
  61. }
  62. else
  63. {
  64. m_signalingThread.Join(1000);
  65. }
  66. m_signalingThread = null;
  67. }
  68. }
  69. //todo(kazuki):: remove warning CS0067
  70. #pragma warning disable 0067
  71. public event OnStartHandler OnStart;
  72. public event OnSignedInHandler OnSignedIn;
  73. public event OnConnectHandler OnCreateConnection;
  74. public event OnDisconnectHandler OnDestroyConnection;
  75. public event OnOfferHandler OnOffer;
  76. public event OnAnswerHandler OnAnswer;
  77. public event OnIceCandidateHandler OnIceCandidate;
  78. #pragma warning restore 0067
  79. public void SendOffer(string connectionId, RTCSessionDescription offer)
  80. {
  81. throw new NotImplementedException();
  82. }
  83. public void SendAnswer(string connectionId, RTCSessionDescription answer)
  84. {
  85. DescData data = new DescData();
  86. data.connectionId = connectionId;
  87. data.sdp = answer.sdp;
  88. data.type = "answer";
  89. FurioosRoutedMessage<DescData> routedMessage = new FurioosRoutedMessage<DescData>();
  90. routedMessage.to = connectionId;
  91. routedMessage.message = data;
  92. WSSend(routedMessage);
  93. }
  94. public void SendCandidate(string connectionId, RTCIceCandidate candidate)
  95. {
  96. CandidateData data = new CandidateData();
  97. data.connectionId = connectionId;
  98. data.candidate = candidate.Candidate;
  99. data.sdpMLineIndex = candidate.SdpMLineIndex.GetValueOrDefault(0);
  100. data.sdpMid = candidate.SdpMid;
  101. FurioosRoutedMessage<CandidateData> routedMessage = new FurioosRoutedMessage<CandidateData>();
  102. routedMessage.to = connectionId;
  103. routedMessage.message = data;
  104. WSSend(routedMessage);
  105. }
  106. public void OpenConnection(string connectionId)
  107. {
  108. this.WSSend("{\"type\":\"connect\"}");
  109. }
  110. public void CloseConnection(string connectionId)
  111. {
  112. throw new NotImplementedException();
  113. }
  114. private void WSManage()
  115. {
  116. while (m_running)
  117. {
  118. WSCreate();
  119. m_wsCloseEvent.WaitOne();
  120. Thread.Sleep((int)(m_timeout * 1000));
  121. }
  122. Debug.Log("Signaling: WS managing thread ended");
  123. }
  124. private void WSCreate()
  125. {
  126. m_webSocket = new WebSocket("ws://127.0.0.1:8081");
  127. m_webSocket.OnOpen += WSConnected;
  128. m_webSocket.OnMessage += WSProcessMessage;
  129. m_webSocket.OnError += WSError;
  130. m_webSocket.OnClose += WSClosed;
  131. Monitor.Enter(m_webSocket);
  132. Debug.Log($"Signaling: Connecting to Furioos Server");
  133. m_webSocket.ConnectAsync();
  134. }
  135. private void WSProcessMessage(object sender, MessageEventArgs e)
  136. {
  137. var content = Encoding.UTF8.GetString(e.RawData);
  138. Debug.Log($"Signaling: Receiving message: {content}");
  139. try
  140. {
  141. var routedMessage = JsonUtility.FromJson<FurioosRoutedMessage<SignalingMessage>>(content);
  142. SignalingMessage msg;
  143. if (!string.IsNullOrEmpty(routedMessage.from))
  144. {
  145. msg = routedMessage.message;
  146. }
  147. else
  148. {
  149. msg = JsonUtility.FromJson<SignalingMessage>(content);
  150. }
  151. if (!string.IsNullOrEmpty(msg.type))
  152. {
  153. if (msg.type == "signIn")
  154. {
  155. if (msg.status == "SUCCESS")
  156. {
  157. Debug.Log("Signaling: Slot signed in.");
  158. this.WSSend("{\"type\":\"furioos\",\"task\":\"enableStreaming\",\"streamType\":\"RenderStreaming\",\"streamProtocols\":[\"WebRTC\"],\"controlsTypes\":[\"RenderStreaming\"]}");
  159. OnSignedIn?.Invoke(this);
  160. }
  161. else
  162. {
  163. Debug.LogError("Signaling: Sign-in error : " + msg.message);
  164. }
  165. }
  166. else if (msg.type == "reconnect")
  167. {
  168. if (msg.status == "SUCCESS")
  169. {
  170. Debug.Log("Signaling: Slot reconnected.");
  171. }
  172. else
  173. {
  174. Debug.LogError("Signaling: Reconnect error : " + msg.message);
  175. }
  176. }
  177. if (msg.type == "offer")
  178. {
  179. if (!string.IsNullOrEmpty(routedMessage.from))
  180. {
  181. DescData offer = new DescData();
  182. offer.connectionId = routedMessage.from;
  183. offer.sdp = msg.sdp;
  184. offer.polite = false;
  185. m_mainThreadContext.Post(d => OnOffer?.Invoke(this, offer), null);
  186. }
  187. else
  188. {
  189. Debug.LogError("Signaling: Received message from unknown peer");
  190. }
  191. }
  192. }
  193. else if (!string.IsNullOrEmpty(msg.candidate))
  194. {
  195. if (!string.IsNullOrEmpty(routedMessage.from))
  196. {
  197. CandidateData candidate = new CandidateData();
  198. candidate.connectionId = routedMessage.from;
  199. candidate.candidate = msg.candidate;
  200. candidate.sdpMLineIndex = msg.sdpMLineIndex;
  201. candidate.sdpMid = msg.sdpMid;
  202. m_mainThreadContext.Post(d => OnIceCandidate?.Invoke(this, candidate), null);
  203. }
  204. else
  205. {
  206. Debug.LogError("Signaling: Received message from unknown peer");
  207. }
  208. }
  209. }
  210. catch (Exception ex)
  211. {
  212. Debug.LogError("Signaling: Failed to parse message: " + ex);
  213. }
  214. }
  215. private void WSConnected(object sender, EventArgs e)
  216. {
  217. Debug.Log("Signaling: WS connected.");
  218. this.WSSend("{\"type\" :\"signIn\",\"peerName\" :\"Unity Test App\"}");
  219. }
  220. private void WSError(object sender, ErrorEventArgs e)
  221. {
  222. Debug.LogError($"Signaling: WS connection error: {e.Message}");
  223. }
  224. private void WSClosed(object sender, CloseEventArgs e)
  225. {
  226. Debug.Log($"Signaling: WS connection closed, code: {e.Code}");
  227. m_wsCloseEvent.Set();
  228. m_webSocket = null;
  229. }
  230. private void WSSend(object data)
  231. {
  232. if (m_webSocket == null || m_webSocket.ReadyState != WebSocketState.Open)
  233. {
  234. Debug.LogError("Signaling: WS is not connected. Unable to send message");
  235. return;
  236. }
  237. if (data is string s)
  238. {
  239. Debug.Log("Signaling: Sending WS data: " + s);
  240. m_webSocket.Send(s);
  241. }
  242. else
  243. {
  244. string str = JsonUtility.ToJson(data);
  245. Debug.Log("Signaling: Sending WS data: " + str);
  246. m_webSocket.Send(str);
  247. }
  248. }
  249. }
  250. }