You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

285 lines
7.7 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "webrtcServer.h"
  2. #include <random>
  3. namespace mtx {
  4. namespace {
  5. const char * PLAYER_PAGE = R"HTML(<!DOCTYPE html>
  6. <html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
  7. <title>MediaMtx</title>
  8. <style>html,body{margin:0;height:100%;background:#000}video{width:100%;height:100%;object-fit:contain}#m{position:absolute;top:8px;left:8px;color:#fff;font:14px sans-serif}</style>
  9. </head><body><video id="v" autoplay muted playsinline></video><div id="m"></div>
  10. <script>
  11. const msg = (t) => { document.getElementById('m').textContent = t; };
  12. async function start() {
  13. const pc = new RTCPeerConnection();
  14. pc.addTransceiver('video', { direction: 'recvonly' });
  15. pc.ontrack = (e) => { document.getElementById('v').srcObject = e.streams[0] || new MediaStream([e.track]); };
  16. pc.onconnectionstatechange = () => { if (pc.connectionState === 'failed' || pc.connectionState === 'disconnected') { msg('reconnecting...'); pc.close(); setTimeout(start, 2000); } else if (pc.connectionState === 'connected') { msg(''); } };
  17. await pc.setLocalDescription(await pc.createOffer());
  18. await new Promise((r) => { if (pc.iceGatheringState === 'complete') r(); else { pc.onicegatheringstatechange = () => { if (pc.iceGatheringState === 'complete') r(); }; setTimeout(r, 2000); } });
  19. const res = await fetch(new URL('whep', window.location.href.replace(/\/?$/, '/')), { method: 'POST', headers: { 'Content-Type': 'application/sdp' }, body: pc.localDescription.sdp });
  20. if (res.status !== 201) { msg('error: ' + res.status + ' ' + await res.text()); pc.close(); setTimeout(start, 2000); return; }
  21. await pc.setRemoteDescription({ type: 'answer', sdp: await res.text() });
  22. }
  23. start();
  24. </script></body></html>
  25. )HTML";
  26. std::string newSecret()
  27. {
  28. static std::mutex s_mutex;
  29. static std::random_device s_rd;
  30. static std::mt19937_64 s_gen(((uint64_t) s_rd() << 32) ^ s_rd());
  31. std::lock_guard<std::mutex> lock(s_mutex);
  32. char tB[40];
  33. snprintf(tB, sizeof(tB), "%016llx%016llx", (unsigned long long) s_gen(), (unsigned long long) s_gen());
  34. return tB;
  35. }
  36. std::vector<std::string> splitPath(const std::string & p)
  37. {
  38. std::vector<std::string> tOut;
  39. size_t i = 0;
  40. while (i < p.size())
  41. {
  42. size_t j = p.find('/', i);
  43. if (j == std::string::npos)
  44. {
  45. j = p.size();
  46. }
  47. if (j > i)
  48. {
  49. tOut.push_back(p.substr(i, j - i));
  50. }
  51. i = j + 1;
  52. }
  53. return tOut;
  54. }
  55. } // namespace
  56. WebrtcServer::WebrtcServer(const ServerConf & global, PathProvider * paths) : LogParent("[WebRTC] "), m_global(global), m_pPaths(paths), m_http(this) {}
  57. WebrtcServer::~WebrtcServer()
  58. {
  59. stop();
  60. }
  61. bool WebrtcServer::start(std::string & err)
  62. {
  63. rtc::InitLogger(rtc::LogLevel::Warning, [](rtc::LogLevel level, std::string message) {
  64. Logger::instance().log(level <= rtc::LogLevel::Error ? LogLevel::Error : (level == rtc::LogLevel::Warning ? LogLevel::Warn : LogLevel::Debug), "[WebRTC] [libdatachannel] %s",
  65. message.c_str());
  66. });
  67. if (! m_http.start(m_global.webrtcAddress, [this](const HttpRequest & q, HttpResponse & r) { handle(q, r); }, err))
  68. {
  69. return false;
  70. }
  71. m_bRun = true;
  72. m_janitor = std::thread(&WebrtcServer::janitor, this);
  73. log(LogLevel::Info, "listener opened on %s (HTTP)", m_global.webrtcAddress.c_str());
  74. return true;
  75. }
  76. void WebrtcServer::stop()
  77. {
  78. {
  79. std::lock_guard<std::mutex> lock(m_stopMutex);
  80. if (! m_bRun)
  81. {
  82. return;
  83. }
  84. m_bRun = false;
  85. }
  86. m_stopCond.notify_all();
  87. if (m_janitor.joinable())
  88. {
  89. m_janitor.join();
  90. }
  91. m_http.stop();
  92. std::map<std::string, std::shared_ptr<WebrtcSession>> tAll;
  93. {
  94. std::lock_guard<std::mutex> lock(m_mutex);
  95. tAll.swap(m_sessions);
  96. }
  97. for (auto & s : tAll)
  98. {
  99. s.second->close();
  100. }
  101. rtc::Cleanup();
  102. }
  103. size_t WebrtcServer::sessionCount() const
  104. {
  105. std::lock_guard<std::mutex> lock(m_mutex);
  106. return m_sessions.size();
  107. }
  108. void WebrtcServer::janitor()
  109. {
  110. while (true)
  111. {
  112. {
  113. std::unique_lock<std::mutex> lock(m_stopMutex);
  114. m_stopCond.wait_for(lock, std::chrono::seconds(1), [this] { return ! m_bRun; });
  115. if (! m_bRun)
  116. {
  117. return;
  118. }
  119. }
  120. std::vector<std::shared_ptr<WebrtcSession>> tClose;
  121. int64_t tNow = nowMs();
  122. {
  123. std::lock_guard<std::mutex> lock(m_mutex);
  124. for (auto it = m_sessions.begin(); it != m_sessions.end();)
  125. {
  126. if (it->second->isClosing() || it->second->connectTimedOut(tNow))
  127. {
  128. tClose.push_back(it->second);
  129. it = m_sessions.erase(it);
  130. }
  131. else
  132. {
  133. ++it;
  134. }
  135. }
  136. }
  137. for (auto & s : tClose)
  138. {
  139. s->close();
  140. }
  141. }
  142. }
  143. void WebrtcServer::handle(const HttpRequest & req, HttpResponse & res)
  144. {
  145. res.setHeader("Access-Control-Allow-Origin", m_global.webrtcAllowOrigin);
  146. res.setHeader("Access-Control-Allow-Credentials", "true");
  147. res.setHeader("Access-Control-Expose-Headers", "ETag, ID, Accept-Patch, Link, Location");
  148. if (req.method == "OPTIONS")
  149. {
  150. res.status = 204;
  151. res.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PATCH, DELETE");
  152. res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, If-Match");
  153. return;
  154. }
  155. std::vector<std::string> tParts = splitPath(req.path);
  156. // GET /<path> or /<path>/ -> player page
  157. if (req.method == "GET" && tParts.size() == 1)
  158. {
  159. if (req.path.back() != '/')
  160. {
  161. res.status = 301;
  162. res.setHeader("Location", req.path + "/");
  163. return;
  164. }
  165. res.status = 200;
  166. res.setHeader("Content-Type", "text/html; charset=utf-8");
  167. res.body = PLAYER_PAGE;
  168. return;
  169. }
  170. if (tParts.size() < 2 || tParts[1] != "whep")
  171. {
  172. res.status = 404;
  173. res.body = "not found";
  174. return;
  175. }
  176. const std::string & tPathName = tParts[0];
  177. if (tParts.size() == 2)
  178. {
  179. if (req.method != "POST")
  180. {
  181. res.status = 405;
  182. return;
  183. }
  184. std::string tType = req.header("content-type");
  185. if (tType.compare(0, 15, "application/sdp") != 0)
  186. {
  187. res.status = 415;
  188. res.body = "invalid Content-Type";
  189. return;
  190. }
  191. std::shared_ptr<MediaPath> tPath = m_pPaths->findPath(tPathName);
  192. if (! tPath)
  193. {
  194. res.status = 404;
  195. res.body = "path '" + tPathName + "' is not configured";
  196. log(LogLevel::Info, "%s: path '%s' is not configured", req.remoteAddr.c_str(), tPathName.c_str());
  197. return;
  198. }
  199. std::string tSecret = newSecret();
  200. auto tSession = std::make_shared<WebrtcSession>(tSecret, tPath, m_global, req.remoteAddr);
  201. std::string tAnswer, tErr;
  202. int tStatus = 500;
  203. if (! tSession->create(req.body, tAnswer, tStatus, tErr))
  204. {
  205. tSession->log(LogLevel::Info, "closed: %s", tErr.c_str());
  206. tSession->close();
  207. res.status = tStatus;
  208. res.body = tErr;
  209. return;
  210. }
  211. {
  212. std::lock_guard<std::mutex> lock(m_mutex);
  213. m_sessions[tSecret] = tSession;
  214. }
  215. res.status = 201;
  216. res.setHeader("Content-Type", "application/sdp");
  217. res.setHeader("ETag", "*");
  218. res.setHeader("ID", tSecret);
  219. res.setHeader("Accept-Patch", "application/trickle-ice-sdpfrag");
  220. res.setHeader("Location", "/" + tPathName + "/whep/" + tSecret);
  221. for (const std::string & s : m_global.webrtcICEServers)
  222. {
  223. res.setHeader("Link", "<" + s + ">; rel=\"ice-server\"");
  224. }
  225. res.body = tAnswer;
  226. return;
  227. }
  228. // /<path>/whep/<secret>
  229. std::shared_ptr<WebrtcSession> tSession;
  230. {
  231. std::lock_guard<std::mutex> lock(m_mutex);
  232. auto it = m_sessions.find(tParts[2]);
  233. if (it != m_sessions.end() && it->second->pathName() == tPathName)
  234. {
  235. tSession = it->second;
  236. }
  237. }
  238. if (! tSession)
  239. {
  240. res.status = 404;
  241. res.body = "session not found";
  242. return;
  243. }
  244. if (req.method == "PATCH")
  245. {
  246. std::string tErr;
  247. if (! tSession->addRemoteCandidates(req.body, tErr))
  248. {
  249. res.status = 400;
  250. res.body = tErr;
  251. return;
  252. }
  253. res.status = 204;
  254. }
  255. else if (req.method == "DELETE")
  256. {
  257. {
  258. std::lock_guard<std::mutex> lock(m_mutex);
  259. m_sessions.erase(tParts[2]);
  260. }
  261. tSession->log(LogLevel::Info, "deleted by the client");
  262. tSession->close();
  263. res.status = 200;
  264. }
  265. else
  266. {
  267. res.status = 405;
  268. }
  269. }
  270. } // namespace mtx