rtc.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. /**
  2. * Copyright (c) 2019-2020 Paul-Louis Ageneau
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "include.hpp"
  19. #include "rtc.h"
  20. #include "datachannel.hpp"
  21. #include "log.hpp"
  22. #include "peerconnection.hpp"
  23. #if RTC_ENABLE_WEBSOCKET
  24. #include "websocket.hpp"
  25. #endif
  26. #include "plog/Formatters/FuncMessageFormatter.h"
  27. #include <exception>
  28. #include <mutex>
  29. #include <type_traits>
  30. #include <unordered_map>
  31. #include <utility>
  32. #ifdef _WIN32
  33. #include <codecvt>
  34. #include <locale>
  35. #endif
  36. using namespace rtc;
  37. using std::shared_ptr;
  38. using std::string;
  39. namespace {
  40. std::unordered_map<int, shared_ptr<PeerConnection>> peerConnectionMap;
  41. std::unordered_map<int, shared_ptr<DataChannel>> dataChannelMap;
  42. #if RTC_ENABLE_WEBSOCKET
  43. std::unordered_map<int, shared_ptr<WebSocket>> webSocketMap;
  44. #endif
  45. std::unordered_map<int, void *> userPointerMap;
  46. std::mutex mutex;
  47. int lastId = 0;
  48. std::optional<void *> getUserPointer(int id) {
  49. std::lock_guard lock(mutex);
  50. auto it = userPointerMap.find(id);
  51. return it != userPointerMap.end() ? std::make_optional(it->second) : nullopt;
  52. }
  53. void setUserPointer(int i, void *ptr) {
  54. std::lock_guard lock(mutex);
  55. userPointerMap[i] = ptr;
  56. }
  57. shared_ptr<PeerConnection> getPeerConnection(int id) {
  58. std::lock_guard lock(mutex);
  59. if (auto it = peerConnectionMap.find(id); it != peerConnectionMap.end())
  60. return it->second;
  61. else
  62. throw std::invalid_argument("PeerConnection ID does not exist");
  63. }
  64. shared_ptr<DataChannel> getDataChannel(int id) {
  65. std::lock_guard lock(mutex);
  66. if (auto it = dataChannelMap.find(id); it != dataChannelMap.end())
  67. return it->second;
  68. else
  69. throw std::invalid_argument("DataChannel ID does not exist");
  70. }
  71. int emplacePeerConnection(shared_ptr<PeerConnection> ptr) {
  72. std::lock_guard lock(mutex);
  73. int pc = ++lastId;
  74. peerConnectionMap.emplace(std::make_pair(pc, ptr));
  75. userPointerMap.emplace(std::make_pair(pc, nullptr));
  76. return pc;
  77. }
  78. int emplaceDataChannel(shared_ptr<DataChannel> ptr) {
  79. std::lock_guard lock(mutex);
  80. int dc = ++lastId;
  81. dataChannelMap.emplace(std::make_pair(dc, ptr));
  82. userPointerMap.emplace(std::make_pair(dc, nullptr));
  83. return dc;
  84. }
  85. void erasePeerConnection(int pc) {
  86. std::lock_guard lock(mutex);
  87. if (peerConnectionMap.erase(pc) == 0)
  88. throw std::invalid_argument("PeerConnection ID does not exist");
  89. userPointerMap.erase(pc);
  90. }
  91. void eraseDataChannel(int dc) {
  92. std::lock_guard lock(mutex);
  93. if (dataChannelMap.erase(dc) == 0)
  94. throw std::invalid_argument("DataChannel ID does not exist");
  95. userPointerMap.erase(dc);
  96. }
  97. #if RTC_ENABLE_WEBSOCKET
  98. shared_ptr<WebSocket> getWebSocket(int id) {
  99. std::lock_guard lock(mutex);
  100. if (auto it = webSocketMap.find(id); it != webSocketMap.end())
  101. return it->second;
  102. else
  103. throw std::invalid_argument("WebSocket ID does not exist");
  104. }
  105. int emplaceWebSocket(shared_ptr<WebSocket> ptr) {
  106. std::lock_guard lock(mutex);
  107. int ws = ++lastId;
  108. webSocketMap.emplace(std::make_pair(ws, ptr));
  109. userPointerMap.emplace(std::make_pair(ws, nullptr));
  110. return ws;
  111. }
  112. void eraseWebSocket(int ws) {
  113. std::lock_guard lock(mutex);
  114. if (webSocketMap.erase(ws) == 0)
  115. throw std::invalid_argument("WebSocket ID does not exist");
  116. userPointerMap.erase(ws);
  117. }
  118. #endif
  119. shared_ptr<Channel> getChannel(int id) {
  120. std::lock_guard lock(mutex);
  121. if (auto it = dataChannelMap.find(id); it != dataChannelMap.end())
  122. return it->second;
  123. #if RTC_ENABLE_WEBSOCKET
  124. if (auto it = webSocketMap.find(id); it != webSocketMap.end())
  125. return it->second;
  126. #endif
  127. throw std::invalid_argument("DataChannel or WebSocket ID does not exist");
  128. }
  129. template <typename F> int wrap(F func) {
  130. try {
  131. return int(func());
  132. } catch (const std::invalid_argument &e) {
  133. PLOG_ERROR << e.what();
  134. return RTC_ERR_INVALID;
  135. } catch (const std::exception &e) {
  136. PLOG_ERROR << e.what();
  137. return RTC_ERR_FAILURE;
  138. }
  139. }
  140. #define WRAP(statement) \
  141. wrap([&]() { \
  142. statement; \
  143. return RTC_ERR_SUCCESS; \
  144. })
  145. class plog_appender : public plog::IAppender {
  146. public:
  147. plog_appender(rtcLogCallbackFunc cb = nullptr) { set_callback(cb); }
  148. void set_callback(rtcLogCallbackFunc cb) {
  149. std::lock_guard lock(mutex);
  150. callback = cb;
  151. }
  152. void write(const plog::Record &record) override {
  153. plog::Severity severity = record.getSeverity();
  154. auto formatted = plog::FuncMessageFormatter::format(record);
  155. formatted.pop_back(); // remove newline
  156. #ifdef _WIN32
  157. using convert_type = std::codecvt_utf8<wchar_t>;
  158. std::wstring_convert<convert_type, wchar_t> converter;
  159. std::string str = converter.to_bytes(formatted);
  160. #else
  161. std::string str = formatted;
  162. #endif
  163. std::lock_guard lock(mutex);
  164. if (callback)
  165. callback(static_cast<rtcLogLevel>(record.getSeverity()), str.c_str());
  166. else
  167. std::cout << plog::severityToString(severity) << " " << str << std::endl;
  168. }
  169. private:
  170. rtcLogCallbackFunc callback;
  171. };
  172. } // namespace
  173. void rtcInitLogger(rtcLogLevel level, rtcLogCallbackFunc cb) {
  174. static std::optional<plog_appender> appender;
  175. if (appender)
  176. appender->set_callback(cb);
  177. else if (cb)
  178. appender.emplace(plog_appender(cb));
  179. InitLogger(static_cast<plog::Severity>(level), appender ? &appender.value() : nullptr);
  180. }
  181. void rtcSetUserPointer(int i, void *ptr) { setUserPointer(i, ptr); }
  182. int rtcCreatePeerConnection(const rtcConfiguration *config) {
  183. return WRAP({
  184. Configuration c;
  185. for (int i = 0; i < config->iceServersCount; ++i)
  186. c.iceServers.emplace_back(string(config->iceServers[i]));
  187. if (config->portRangeBegin || config->portRangeEnd) {
  188. c.portRangeBegin = config->portRangeBegin;
  189. c.portRangeEnd = config->portRangeEnd;
  190. }
  191. return emplacePeerConnection(std::make_shared<PeerConnection>(c));
  192. });
  193. }
  194. int rtcDeletePeerConnection(int pc) {
  195. return WRAP({
  196. auto peerConnection = getPeerConnection(pc);
  197. peerConnection->onDataChannel(nullptr);
  198. peerConnection->onLocalDescription(nullptr);
  199. peerConnection->onLocalCandidate(nullptr);
  200. peerConnection->onStateChange(nullptr);
  201. peerConnection->onGatheringStateChange(nullptr);
  202. erasePeerConnection(pc);
  203. });
  204. }
  205. int rtcCreateDataChannel(int pc, const char *label) {
  206. return WRAP({
  207. auto peerConnection = getPeerConnection(pc);
  208. int dc = emplaceDataChannel(peerConnection->createDataChannel(string(label)));
  209. if (auto ptr = getUserPointer(pc))
  210. rtcSetUserPointer(dc, *ptr);
  211. return dc;
  212. });
  213. }
  214. int rtcDeleteDataChannel(int dc) {
  215. return WRAP({
  216. auto dataChannel = getDataChannel(dc);
  217. dataChannel->onOpen(nullptr);
  218. dataChannel->onClosed(nullptr);
  219. dataChannel->onError(nullptr);
  220. dataChannel->onMessage(nullptr);
  221. dataChannel->onBufferedAmountLow(nullptr);
  222. dataChannel->onAvailable(nullptr);
  223. eraseDataChannel(dc);
  224. });
  225. }
  226. #if RTC_ENABLE_WEBSOCKET
  227. int rtcCreateWebSocket(const char *url) {
  228. return WRAP({
  229. auto ws = std::make_shared<WebSocket>();
  230. ws->open(url);
  231. return emplaceWebSocket(ws);
  232. });
  233. }
  234. int rtcCreateWebSocketEx(const char *url, const rtcWsConfiguration *config) {
  235. return WRAP({
  236. WebSocket::Configuration c;
  237. c.disableTlsVerification = config->disableTlsVerification;
  238. auto ws = std::make_shared<WebSocket>(c);
  239. ws->open(url);
  240. return emplaceWebSocket(ws);
  241. });
  242. }
  243. int rtcDeleteWebsocket(int ws) {
  244. return WRAP({
  245. auto webSocket = getWebSocket(ws);
  246. webSocket->onOpen(nullptr);
  247. webSocket->onClosed(nullptr);
  248. webSocket->onError(nullptr);
  249. webSocket->onMessage(nullptr);
  250. webSocket->onBufferedAmountLow(nullptr);
  251. webSocket->onAvailable(nullptr);
  252. eraseWebSocket(ws);
  253. });
  254. }
  255. #endif
  256. int rtcSetDataChannelCallback(int pc, rtcDataChannelCallbackFunc cb) {
  257. return WRAP({
  258. auto peerConnection = getPeerConnection(pc);
  259. if (cb)
  260. peerConnection->onDataChannel([pc, cb](std::shared_ptr<DataChannel> dataChannel) {
  261. int dc = emplaceDataChannel(dataChannel);
  262. if (auto ptr = getUserPointer(pc)) {
  263. rtcSetUserPointer(dc, *ptr);
  264. cb(dc, *ptr);
  265. }
  266. });
  267. else
  268. peerConnection->onDataChannel(nullptr);
  269. });
  270. }
  271. int rtcSetLocalDescriptionCallback(int pc, rtcDescriptionCallbackFunc cb) {
  272. return WRAP({
  273. auto peerConnection = getPeerConnection(pc);
  274. if (cb)
  275. peerConnection->onLocalDescription([pc, cb](const Description &desc) {
  276. if (auto ptr = getUserPointer(pc))
  277. cb(string(desc).c_str(), desc.typeString().c_str(), *ptr);
  278. });
  279. else
  280. peerConnection->onLocalDescription(nullptr);
  281. });
  282. }
  283. int rtcSetLocalCandidateCallback(int pc, rtcCandidateCallbackFunc cb) {
  284. return WRAP({
  285. auto peerConnection = getPeerConnection(pc);
  286. if (cb)
  287. peerConnection->onLocalCandidate([pc, cb](const Candidate &cand) {
  288. if (auto ptr = getUserPointer(pc))
  289. cb(cand.candidate().c_str(), cand.mid().c_str(), *ptr);
  290. });
  291. else
  292. peerConnection->onLocalCandidate(nullptr);
  293. });
  294. }
  295. int rtcSetStateChangeCallback(int pc, rtcStateChangeCallbackFunc cb) {
  296. return WRAP({
  297. auto peerConnection = getPeerConnection(pc);
  298. if (cb)
  299. peerConnection->onStateChange([pc, cb](PeerConnection::State state) {
  300. if (auto ptr = getUserPointer(pc))
  301. cb(static_cast<rtcState>(state), *ptr);
  302. });
  303. else
  304. peerConnection->onStateChange(nullptr);
  305. });
  306. }
  307. int rtcSetGatheringStateChangeCallback(int pc, rtcGatheringStateCallbackFunc cb) {
  308. return WRAP({
  309. auto peerConnection = getPeerConnection(pc);
  310. if (cb)
  311. peerConnection->onGatheringStateChange([pc, cb](PeerConnection::GatheringState state) {
  312. if (auto ptr = getUserPointer(pc))
  313. cb(static_cast<rtcGatheringState>(state), *ptr);
  314. });
  315. else
  316. peerConnection->onGatheringStateChange(nullptr);
  317. });
  318. }
  319. int rtcSetRemoteDescription(int pc, const char *sdp, const char *type) {
  320. return WRAP({
  321. auto peerConnection = getPeerConnection(pc);
  322. if (!sdp)
  323. throw std::invalid_argument("Unexpected null pointer");
  324. peerConnection->setRemoteDescription({string(sdp), type ? string(type) : ""});
  325. });
  326. }
  327. int rtcAddRemoteCandidate(int pc, const char *cand, const char *mid) {
  328. return WRAP({
  329. auto peerConnection = getPeerConnection(pc);
  330. if (!cand)
  331. throw std::invalid_argument("Unexpected null pointer");
  332. peerConnection->addRemoteCandidate({string(cand), mid ? string(mid) : ""});
  333. });
  334. }
  335. int rtcGetLocalAddress(int pc, char *buffer, int size) {
  336. return WRAP({
  337. auto peerConnection = getPeerConnection(pc);
  338. if (!buffer)
  339. throw std::invalid_argument("Unexpected null pointer");
  340. if (size <= 0)
  341. return 0;
  342. if (auto addr = peerConnection->localAddress()) {
  343. const char *data = addr->data();
  344. size = std::min(size - 1, int(addr->size()));
  345. std::copy(data, data + size, buffer);
  346. buffer[size] = '\0';
  347. return size + 1;
  348. }
  349. });
  350. }
  351. int rtcGetRemoteAddress(int pc, char *buffer, int size) {
  352. return WRAP({
  353. auto peerConnection = getPeerConnection(pc);
  354. if (!buffer)
  355. throw std::invalid_argument("Unexpected null pointer");
  356. if (size <= 0)
  357. return 0;
  358. if (auto addr = peerConnection->remoteAddress()) {
  359. const char *data = addr->data();
  360. size = std::min(size - 1, int(addr->size()));
  361. std::copy(data, data + size, buffer);
  362. buffer[size] = '\0';
  363. return int(size + 1);
  364. }
  365. });
  366. }
  367. int rtcGetDataChannelLabel(int dc, char *buffer, int size) {
  368. return WRAP({
  369. auto dataChannel = getDataChannel(dc);
  370. if (!buffer)
  371. throw std::invalid_argument("Unexpected null pointer");
  372. if (size <= 0)
  373. return 0;
  374. string label = dataChannel->label();
  375. const char *data = label.data();
  376. size = std::min(size - 1, int(label.size()));
  377. std::copy(data, data + size, buffer);
  378. buffer[size] = '\0';
  379. return int(size + 1);
  380. });
  381. }
  382. int rtcSetOpenCallback(int id, rtcOpenCallbackFunc cb) {
  383. return WRAP({
  384. auto channel = getChannel(id);
  385. if (cb)
  386. channel->onOpen([id, cb]() {
  387. if (auto ptr = getUserPointer(id))
  388. cb(*ptr);
  389. });
  390. else
  391. channel->onOpen(nullptr);
  392. });
  393. }
  394. int rtcSetClosedCallback(int id, rtcClosedCallbackFunc cb) {
  395. return WRAP({
  396. auto channel = getChannel(id);
  397. if (cb)
  398. channel->onClosed([id, cb]() {
  399. if (auto ptr = getUserPointer(id))
  400. cb(*ptr);
  401. });
  402. else
  403. channel->onClosed(nullptr);
  404. });
  405. }
  406. int rtcSetErrorCallback(int id, rtcErrorCallbackFunc cb) {
  407. return WRAP({
  408. auto channel = getChannel(id);
  409. if (cb)
  410. channel->onError([id, cb](const string &error) {
  411. if (auto ptr = getUserPointer(id))
  412. cb(error.c_str(), *ptr);
  413. });
  414. else
  415. channel->onError(nullptr);
  416. });
  417. }
  418. int rtcSetMessageCallback(int id, rtcMessageCallbackFunc cb) {
  419. return WRAP({
  420. auto channel = getChannel(id);
  421. if (cb)
  422. channel->onMessage(
  423. [id, cb](const binary &b) {
  424. if (auto ptr = getUserPointer(id))
  425. cb(reinterpret_cast<const char *>(b.data()), int(b.size()), *ptr);
  426. },
  427. [id, cb](const string &s) {
  428. if (auto ptr = getUserPointer(id))
  429. cb(s.c_str(), -int(s.size() + 1), *ptr);
  430. });
  431. else
  432. channel->onMessage(nullptr);
  433. });
  434. }
  435. int rtcSendMessage(int id, const char *data, int size) {
  436. return WRAP({
  437. auto channel = getChannel(id);
  438. if (!data)
  439. throw std::invalid_argument("Unexpected null pointer");
  440. if (size >= 0) {
  441. auto b = reinterpret_cast<const byte *>(data);
  442. channel->send(binary(b, b + size));
  443. return size;
  444. } else {
  445. string str(data);
  446. int len = int(str.size());
  447. channel->send(std::move(str));
  448. return len;
  449. }
  450. });
  451. }
  452. int rtcGetBufferedAmount(int id) {
  453. return WRAP({
  454. auto channel = getChannel(id);
  455. return int(channel->bufferedAmount());
  456. });
  457. }
  458. int rtcSetBufferedAmountLowThreshold(int id, int amount) {
  459. return WRAP({
  460. auto channel = getChannel(id);
  461. channel->setBufferedAmountLowThreshold(size_t(amount));
  462. });
  463. }
  464. int rtcSetBufferedAmountLowCallback(int id, rtcBufferedAmountLowCallbackFunc cb) {
  465. return WRAP({
  466. auto channel = getChannel(id);
  467. if (cb)
  468. channel->onBufferedAmountLow([id, cb]() {
  469. if (auto ptr = getUserPointer(id))
  470. cb(*ptr);
  471. });
  472. else
  473. channel->onBufferedAmountLow(nullptr);
  474. });
  475. }
  476. int rtcGetAvailableAmount(int id) {
  477. return WRAP({ return int(getChannel(id)->availableAmount()); });
  478. }
  479. int rtcSetAvailableCallback(int id, rtcAvailableCallbackFunc cb) {
  480. return WRAP({
  481. auto channel = getChannel(id);
  482. if (cb)
  483. channel->onOpen([id, cb]() {
  484. if (auto ptr = getUserPointer(id))
  485. cb(*ptr);
  486. });
  487. else
  488. channel->onOpen(nullptr);
  489. });
  490. }
  491. int rtcReceiveMessage(int id, char *buffer, int *size) {
  492. return WRAP({
  493. auto channel = getChannel(id);
  494. if (!buffer || !size)
  495. throw std::invalid_argument("Unexpected null pointer");
  496. if (auto message = channel->receive())
  497. return std::visit( //
  498. overloaded{ //
  499. [&](const binary &b) {
  500. *size = std::min(*size, int(b.size()));
  501. auto data = reinterpret_cast<const char *>(b.data());
  502. std::copy(data, data + *size, buffer);
  503. return 1;
  504. },
  505. [&](const string &s) {
  506. int len = std::min(*size - 1, int(s.size()));
  507. if (len >= 0) {
  508. std::copy(s.data(), s.data() + len, buffer);
  509. buffer[len] = '\0';
  510. }
  511. *size = -(len + 1);
  512. return 1;
  513. }},
  514. *message);
  515. else
  516. return 0;
  517. });
  518. }
  519. void rtcPreload() { rtc::Preload(); }
  520. void rtcCleanup() { rtc::Cleanup(); }