HttpSignaling.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Threading;
  7. using Unity.WebRTC;
  8. using UnityEngine;
  9. namespace Unity.RenderStreaming.Signaling
  10. {
  11. public class HttpSignaling : ISignaling
  12. {
  13. private static HashSet<HttpSignaling> instances = new HashSet<HttpSignaling>();
  14. private readonly string m_url;
  15. private readonly int m_timeout;
  16. private readonly SynchronizationContext m_mainThreadContext;
  17. private bool m_running;
  18. private Thread m_signalingThread;
  19. private string m_sessionId;
  20. private long m_lastTimeGetAllRequest;
  21. public string Url { get { return m_url; } }
  22. public HttpSignaling(SignalingSettings signalingSettings, SynchronizationContext mainThreadContext)
  23. {
  24. if (signalingSettings == null)
  25. throw new ArgumentNullException(nameof(signalingSettings));
  26. if (!(signalingSettings is HttpSignalingSettings settings))
  27. throw new ArgumentException("signalingSettings is not HttpSignalingSettings");
  28. m_url = settings.url;
  29. m_timeout = settings.interval;
  30. m_mainThreadContext = mainThreadContext;
  31. if (m_url.StartsWith("https"))
  32. {
  33. ServicePointManager.ServerCertificateValidationCallback =
  34. (sender, certificate, chain, errors) => true;
  35. }
  36. if (instances.Any(x => x.Url == m_url))
  37. {
  38. Debug.LogWarning($"Other {nameof(HttpSignaling)} exists with same URL:{m_url}. Signaling process may be in conflict.");
  39. }
  40. instances.Add(this);
  41. }
  42. ~HttpSignaling()
  43. {
  44. Stop();
  45. instances.Remove(this);
  46. }
  47. public void Start()
  48. {
  49. if (m_running)
  50. throw new InvalidOperationException("This object is already started.");
  51. m_running = true;
  52. m_signalingThread = new Thread(HTTPPolling);
  53. m_signalingThread.Start();
  54. }
  55. public void Stop()
  56. {
  57. m_running = false;
  58. if (m_signalingThread != null)
  59. {
  60. if (m_signalingThread.ThreadState == ThreadState.WaitSleepJoin)
  61. {
  62. m_signalingThread.Abort();
  63. }
  64. else
  65. {
  66. m_signalingThread.Join(1000);
  67. }
  68. m_signalingThread = null;
  69. }
  70. }
  71. public event OnStartHandler OnStart;
  72. public event OnConnectHandler OnCreateConnection;
  73. public event OnDisconnectHandler OnDestroyConnection;
  74. public event OnOfferHandler OnOffer;
  75. public event OnAnswerHandler OnAnswer;
  76. public event OnIceCandidateHandler OnIceCandidate;
  77. public void SendOffer(string connectionId, RTCSessionDescription offer)
  78. {
  79. DescData data = new DescData();
  80. data.connectionId = connectionId;
  81. data.sdp = offer.sdp;
  82. data.type = "offer";
  83. ThreadPool.QueueUserWorkItem(_ => { HTTPPost("signaling/offer", data); });
  84. }
  85. public void SendAnswer(string connectionId, RTCSessionDescription answer)
  86. {
  87. DescData data = new DescData();
  88. data.connectionId = connectionId;
  89. data.sdp = answer.sdp;
  90. data.type = "answer";
  91. ThreadPool.QueueUserWorkItem(_ => { HTTPPost("signaling/answer", data); });
  92. }
  93. public void SendCandidate(string connectionId, RTCIceCandidate candidate)
  94. {
  95. CandidateData data = new CandidateData();
  96. data.connectionId = connectionId;
  97. data.candidate = candidate.Candidate;
  98. data.sdpMLineIndex = candidate.SdpMLineIndex.GetValueOrDefault(0);
  99. data.sdpMid = candidate.SdpMid;
  100. ThreadPool.QueueUserWorkItem(_ => { HTTPPost("signaling/candidate", data); });
  101. }
  102. public void OpenConnection(string connectionId)
  103. {
  104. ThreadPool.QueueUserWorkItem(_ => { HTTPConnect(connectionId); });
  105. }
  106. public void CloseConnection(string connectionId)
  107. {
  108. ThreadPool.QueueUserWorkItem(_ => { HTTPDisonnect(connectionId); });
  109. }
  110. private void HTTPPolling()
  111. {
  112. // ignore messages arrived before 30 secs ago
  113. m_lastTimeGetAllRequest = DateTime.UtcNow.Millisecond - 30000;
  114. while (m_running && string.IsNullOrEmpty(m_sessionId))
  115. {
  116. HTTPCreate();
  117. try
  118. {
  119. Thread.Sleep(m_timeout);
  120. }
  121. catch (ThreadAbortException)
  122. {
  123. // Thread.Abort() called from main thread. Ignore
  124. return;
  125. }
  126. }
  127. while (m_running)
  128. {
  129. try
  130. {
  131. HTTPGetAll();
  132. Thread.Sleep(m_timeout);
  133. }
  134. catch (ThreadAbortException)
  135. {
  136. // Thread.Abort() called from main thread. Ignore
  137. return;
  138. }
  139. catch (Exception e)
  140. {
  141. Debug.LogError("Signaling: HTTP polling error : " + e);
  142. }
  143. }
  144. HTTPDelete();
  145. Debug.Log("Signaling: HTTP polling thread ended");
  146. }
  147. private static HttpWebResponse HTTPGetResponse(HttpWebRequest request)
  148. {
  149. try
  150. {
  151. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  152. if (response.StatusCode == HttpStatusCode.OK)
  153. {
  154. return response;
  155. }
  156. else
  157. {
  158. Debug.LogError($"Signaling: {response.ResponseUri} HTTP request failed ({response.StatusCode})");
  159. response.Close();
  160. }
  161. }
  162. catch (ThreadAbortException)
  163. {
  164. // Thread.Abort() called from main thread. Ignore
  165. }
  166. catch (Exception e)
  167. {
  168. Debug.LogError($"Signaling: HTTP request error. url:{request.RequestUri} exception:{e}");
  169. }
  170. return null;
  171. }
  172. private static T HTTPParseJsonResponse<T>(HttpWebResponse response) where T : class
  173. {
  174. if (response == null) return null;
  175. T obj = null;
  176. using (Stream dataStream = response.GetResponseStream())
  177. {
  178. StreamReader reader = new StreamReader(dataStream);
  179. string responseFromServer = reader.ReadToEnd();
  180. obj = JsonUtility.FromJson<T>(responseFromServer);
  181. }
  182. response.Close();
  183. return obj;
  184. }
  185. private static string HTTPParseTextResponse(HttpWebResponse response)
  186. {
  187. if (response == null) return null;
  188. string str = null;
  189. using (Stream dataStream = response.GetResponseStream())
  190. {
  191. StreamReader reader = new StreamReader(dataStream);
  192. str = reader.ReadToEnd();
  193. }
  194. response.Close();
  195. return str;
  196. }
  197. private bool HTTPCreate()
  198. {
  199. HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{m_url}/signaling");
  200. request.Method = "PUT";
  201. request.ContentType = "application/json";
  202. request.KeepAlive = false;
  203. request.ContentLength = 0;
  204. Debug.Log($"Signaling: Connecting HTTP {m_url}");
  205. OpenSessionData resp = HTTPParseJsonResponse<OpenSessionData>(HTTPGetResponse(request));
  206. if (resp != null)
  207. {
  208. m_sessionId = resp.sessionId;
  209. Debug.Log("Signaling: HTTP connected, sessionId : " + m_sessionId);
  210. m_mainThreadContext.Post(d => OnStart?.Invoke(this), null);
  211. return true;
  212. }
  213. else
  214. {
  215. return false;
  216. }
  217. }
  218. private bool HTTPDelete()
  219. {
  220. HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{m_url}/signaling");
  221. request.Method = "DELETE";
  222. request.ContentType = "application/json";
  223. request.KeepAlive = false;
  224. request.Headers.Add("Session-Id", m_sessionId);
  225. Debug.Log($"Signaling: Removing HTTP connection from {m_url}");
  226. return (HTTPParseTextResponse(HTTPGetResponse(request)) != null);
  227. }
  228. private bool HTTPPost(string path, object data)
  229. {
  230. string str = JsonUtility.ToJson(data);
  231. byte[] bytes = new System.Text.UTF8Encoding().GetBytes(str);
  232. Debug.Log("Signaling: Posting HTTP data: " + str);
  233. HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{m_url}/{path}");
  234. request.Method = "POST";
  235. request.ContentType = "application/json";
  236. request.Headers.Add("Session-Id", m_sessionId);
  237. request.KeepAlive = false;
  238. using (Stream dataStream = request.GetRequestStream())
  239. {
  240. dataStream.Write(bytes, 0, bytes.Length);
  241. dataStream.Close();
  242. }
  243. return (HTTPParseTextResponse(HTTPGetResponse(request)) != null);
  244. }
  245. private bool HTTPConnect(string connectionId)
  246. {
  247. HttpWebRequest request =
  248. (HttpWebRequest)WebRequest.Create($"{m_url}/signaling/connection");
  249. request.Method = "PUT";
  250. request.ContentType = "application/json";
  251. request.Headers.Add("Session-Id", m_sessionId);
  252. request.KeepAlive = false;
  253. using (Stream dataStream = request.GetRequestStream())
  254. {
  255. byte[] bytes = new System.Text.UTF8Encoding().GetBytes($"{{\"connectionId\":\"{connectionId}\"}}");
  256. dataStream.Write(bytes, 0, bytes.Length);
  257. dataStream.Close();
  258. }
  259. HttpWebResponse response = HTTPGetResponse(request);
  260. CreateConnectionResData data = HTTPParseJsonResponse<CreateConnectionResData>(response);
  261. if (data == null) return false;
  262. Debug.Log($"Signaling: HTTP create connection, connectionId: {connectionId}, polite:{data.polite}");
  263. m_mainThreadContext.Post(d => OnCreateConnection?.Invoke(this, data.connectionId, data.polite), null);
  264. return true;
  265. }
  266. private bool HTTPDisonnect(string connectionId)
  267. {
  268. HttpWebRequest request =
  269. (HttpWebRequest)WebRequest.Create($"{m_url}/signaling/connection");
  270. request.Method = "Delete";
  271. request.ContentType = "application/json";
  272. request.Headers.Add("Session-Id", m_sessionId);
  273. request.KeepAlive = false;
  274. using (Stream dataStream = request.GetRequestStream())
  275. {
  276. byte[] bytes = new System.Text.UTF8Encoding().GetBytes($"{{\"connectionId\":\"{connectionId}\"}}");
  277. dataStream.Write(bytes, 0, bytes.Length);
  278. dataStream.Close();
  279. }
  280. var data = HTTPParseTextResponse(HTTPGetResponse(request));
  281. if (data == null) return false;
  282. Debug.Log("Signaling: HTTP delete connection, connectionId : " + connectionId);
  283. m_mainThreadContext.Post(d => OnDestroyConnection?.Invoke(this, connectionId), null);
  284. return true;
  285. }
  286. private bool HTTPGetAll()
  287. {
  288. HttpWebRequest request =
  289. (HttpWebRequest)WebRequest.Create($"{m_url}/signaling?fromtime={m_lastTimeGetAllRequest}");
  290. request.Method = "GET";
  291. request.ContentType = "application/json";
  292. request.Headers.Add("Session-Id", m_sessionId);
  293. request.KeepAlive = false;
  294. HttpWebResponse response = HTTPGetResponse(request);
  295. AllResData data = HTTPParseJsonResponse<AllResData>(response);
  296. if (data == null) return false;
  297. m_lastTimeGetAllRequest = DateTimeExtension.ParseHttpDate(response.Headers[HttpResponseHeader.Date])
  298. .ToJsMilliseconds();
  299. foreach (var msg in data.messages)
  300. {
  301. if (string.IsNullOrEmpty(msg.type))
  302. continue;
  303. if(msg.type == "disconnect")
  304. {
  305. m_mainThreadContext.Post(d => OnDestroyConnection?.Invoke(this, msg.connectionId), null);
  306. }
  307. else if (msg.type == "offer")
  308. {
  309. DescData offer = new DescData();
  310. offer.connectionId = msg.connectionId;
  311. offer.sdp = msg.sdp;
  312. offer.polite = msg.polite;
  313. m_mainThreadContext.Post(d => OnOffer?.Invoke(this, offer), null);
  314. }
  315. else if (msg.type == "answer")
  316. {
  317. DescData answer = new DescData
  318. {
  319. connectionId = msg.connectionId,
  320. sdp = msg.sdp
  321. };
  322. m_mainThreadContext.Post(d => OnAnswer?.Invoke(this, answer), null);
  323. }
  324. else if (msg.type == "candidate")
  325. {
  326. CandidateData candidate = new CandidateData
  327. {
  328. connectionId = msg.connectionId,
  329. candidate = msg.candidate,
  330. sdpMLineIndex = msg.sdpMLineIndex,
  331. sdpMid = msg.sdpMid
  332. };
  333. m_mainThreadContext.Post(d => OnIceCandidate?.Invoke(this, candidate), null);
  334. }
  335. }
  336. return true;
  337. }
  338. }
  339. }