rtc.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /**
  2. * Copyright (c) 2019 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 "datachannel.hpp"
  20. #include "peerconnection.hpp"
  21. #if RTC_ENABLE_WEBSOCKET
  22. #include "websocket.hpp"
  23. #endif
  24. #include <rtc.h>
  25. #include <exception>
  26. #include <mutex>
  27. #include <type_traits>
  28. #include <unordered_map>
  29. #include <utility>
  30. using namespace rtc;
  31. using std::shared_ptr;
  32. using std::string;
  33. namespace {
  34. std::unordered_map<int, shared_ptr<PeerConnection>> peerConnectionMap;
  35. std::unordered_map<int, shared_ptr<DataChannel>> dataChannelMap;
  36. #if RTC_ENABLE_WEBSOCKET
  37. std::unordered_map<int, shared_ptr<WebSocket>> webSocketMap;
  38. #endif
  39. std::unordered_map<int, void *> userPointerMap;
  40. std::mutex mutex;
  41. int lastId = 0;
  42. void *getUserPointer(int id) {
  43. std::lock_guard lock(mutex);
  44. auto it = userPointerMap.find(id);
  45. return it != userPointerMap.end() ? it->second : nullptr;
  46. }
  47. void setUserPointer(int i, void *ptr) {
  48. std::lock_guard lock(mutex);
  49. if (ptr)
  50. userPointerMap.insert(std::make_pair(i, ptr));
  51. else
  52. userPointerMap.erase(i);
  53. }
  54. shared_ptr<PeerConnection> getPeerConnection(int id) {
  55. std::lock_guard lock(mutex);
  56. if (auto it = peerConnectionMap.find(id); it != peerConnectionMap.end())
  57. return it->second;
  58. else
  59. throw std::invalid_argument("PeerConnection ID does not exist");
  60. }
  61. shared_ptr<DataChannel> getDataChannel(int id) {
  62. std::lock_guard lock(mutex);
  63. if (auto it = dataChannelMap.find(id); it != dataChannelMap.end())
  64. return it->second;
  65. else
  66. throw std::invalid_argument("DataChannel ID does not exist");
  67. }
  68. int emplacePeerConnection(shared_ptr<PeerConnection> ptr) {
  69. std::lock_guard lock(mutex);
  70. int pc = ++lastId;
  71. peerConnectionMap.emplace(std::make_pair(pc, ptr));
  72. return pc;
  73. }
  74. int emplaceDataChannel(shared_ptr<DataChannel> ptr) {
  75. std::lock_guard lock(mutex);
  76. int dc = ++lastId;
  77. dataChannelMap.emplace(std::make_pair(dc, ptr));
  78. return dc;
  79. }
  80. void erasePeerConnection(int pc) {
  81. std::lock_guard lock(mutex);
  82. if (peerConnectionMap.erase(pc) == 0)
  83. throw std::invalid_argument("PeerConnection ID does not exist");
  84. userPointerMap.erase(pc);
  85. }
  86. void eraseDataChannel(int dc) {
  87. std::lock_guard lock(mutex);
  88. if (dataChannelMap.erase(dc) == 0)
  89. throw std::invalid_argument("DataChannel ID does not exist");
  90. userPointerMap.erase(dc);
  91. }
  92. #if RTC_ENABLE_WEBSOCKET
  93. shared_ptr<WebSocket> getWebSocket(int id) {
  94. std::lock_guard lock(mutex);
  95. if (auto it = webSocketMap.find(id); it != webSocketMap.end())
  96. return it->second;
  97. else
  98. throw std::invalid_argument("WebSocket ID does not exist");
  99. }
  100. int emplaceWebSocket(shared_ptr<WebSocket> ptr) {
  101. std::lock_guard lock(mutex);
  102. int ws = ++lastId;
  103. webSocketMap.emplace(std::make_pair(ws, ptr));
  104. return ws;
  105. }
  106. void eraseWebSocket(int ws) {
  107. std::lock_guard lock(mutex);
  108. if (webSocketMap.erase(ws) == 0)
  109. throw std::invalid_argument("WebSocket ID does not exist");
  110. userPointerMap.erase(ws);
  111. }
  112. #endif
  113. shared_ptr<Channel> getChannel(int id) {
  114. std::lock_guard lock(mutex);
  115. if (auto it = dataChannelMap.find(id); it != dataChannelMap.end())
  116. return it->second;
  117. #if RTC_ENABLE_WEBSOCKET
  118. if (auto it = webSocketMap.find(id); it != webSocketMap.end())
  119. return it->second;
  120. #endif
  121. throw std::invalid_argument("DataChannel or WebSocket ID does not exist");
  122. }
  123. template <typename F> int wrap(F func) {
  124. try {
  125. return func();
  126. } catch (const std::invalid_argument &e) {
  127. PLOG_ERROR << e.what();
  128. return RTC_ERR_INVALID;
  129. } catch (const std::exception &e) {
  130. PLOG_ERROR << e.what();
  131. return RTC_ERR_FAILURE;
  132. }
  133. }
  134. #define WRAP(statement) \
  135. wrap([&]() { \
  136. statement; \
  137. return RTC_ERR_SUCCESS; \
  138. })
  139. } // namespace
  140. void rtcInitLogger(rtcLogLevel level) { InitLogger(static_cast<LogLevel>(level)); }
  141. void rtcSetUserPointer(int i, void *ptr) { setUserPointer(i, ptr); }
  142. int rtcCreatePeerConnection(const rtcConfiguration *config) {
  143. return WRAP({
  144. Configuration c;
  145. for (int i = 0; i < config->iceServersCount; ++i)
  146. c.iceServers.emplace_back(string(config->iceServers[i]));
  147. if (config->portRangeBegin || config->portRangeEnd) {
  148. c.portRangeBegin = config->portRangeBegin;
  149. c.portRangeEnd = config->portRangeEnd;
  150. }
  151. return emplacePeerConnection(std::make_shared<PeerConnection>(c));
  152. });
  153. }
  154. int rtcDeletePeerConnection(int pc) {
  155. return WRAP({
  156. auto peerConnection = getPeerConnection(pc);
  157. peerConnection->onDataChannel(nullptr);
  158. peerConnection->onLocalDescription(nullptr);
  159. peerConnection->onLocalCandidate(nullptr);
  160. peerConnection->onStateChange(nullptr);
  161. peerConnection->onGatheringStateChange(nullptr);
  162. erasePeerConnection(pc);
  163. });
  164. }
  165. int rtcCreateDataChannel(int pc, const char *label) {
  166. return WRAP({
  167. auto peerConnection = getPeerConnection(pc);
  168. int dc = emplaceDataChannel(peerConnection->createDataChannel(string(label)));
  169. rtcSetUserPointer(dc, getUserPointer(pc));
  170. return dc;
  171. });
  172. }
  173. int rtcDeleteDataChannel(int dc) {
  174. return WRAP({
  175. auto dataChannel = getDataChannel(dc);
  176. dataChannel->onOpen(nullptr);
  177. dataChannel->onClosed(nullptr);
  178. dataChannel->onError(nullptr);
  179. dataChannel->onMessage(nullptr);
  180. dataChannel->onBufferedAmountLow(nullptr);
  181. dataChannel->onAvailable(nullptr);
  182. eraseDataChannel(dc);
  183. });
  184. }
  185. #if RTC_ENABLE_WEBSOCKET
  186. int rtcCreateWebSocket(const char *url) {
  187. return WRAP({
  188. auto ws = std::make_shared<WebSocket>();
  189. ws->open(url);
  190. return emplaceWebSocket(ws);
  191. });
  192. }
  193. int rtcDeleteWebsocket(int ws) {
  194. return WRAP({
  195. auto webSocket = getWebSocket(ws);
  196. webSocket->onOpen(nullptr);
  197. webSocket->onClosed(nullptr);
  198. webSocket->onError(nullptr);
  199. webSocket->onMessage(nullptr);
  200. webSocket->onBufferedAmountLow(nullptr);
  201. webSocket->onAvailable(nullptr);
  202. eraseWebSocket(ws);
  203. });
  204. }
  205. #endif
  206. int rtcSetDataChannelCallback(int pc, dataChannelCallbackFunc cb) {
  207. return WRAP({
  208. auto peerConnection = getPeerConnection(pc);
  209. if (cb)
  210. peerConnection->onDataChannel([pc, cb](std::shared_ptr<DataChannel> dataChannel) {
  211. int dc = emplaceDataChannel(dataChannel);
  212. void *ptr = getUserPointer(pc);
  213. rtcSetUserPointer(dc, ptr);
  214. cb(dc, ptr);
  215. });
  216. else
  217. peerConnection->onDataChannel(nullptr);
  218. });
  219. }
  220. int rtcSetLocalDescriptionCallback(int pc, descriptionCallbackFunc cb) {
  221. return WRAP({
  222. auto peerConnection = getPeerConnection(pc);
  223. if (cb)
  224. peerConnection->onLocalDescription([pc, cb](const Description &desc) {
  225. cb(string(desc).c_str(), desc.typeString().c_str(), getUserPointer(pc));
  226. });
  227. else
  228. peerConnection->onLocalDescription(nullptr);
  229. });
  230. }
  231. int rtcSetLocalCandidateCallback(int pc, candidateCallbackFunc cb) {
  232. return WRAP({
  233. auto peerConnection = getPeerConnection(pc);
  234. if (cb)
  235. peerConnection->onLocalCandidate([pc, cb](const Candidate &cand) {
  236. cb(cand.candidate().c_str(), cand.mid().c_str(), getUserPointer(pc));
  237. });
  238. else
  239. peerConnection->onLocalCandidate(nullptr);
  240. });
  241. }
  242. int rtcSetStateChangeCallback(int pc, stateChangeCallbackFunc cb) {
  243. return WRAP({
  244. auto peerConnection = getPeerConnection(pc);
  245. if (cb)
  246. peerConnection->onStateChange([pc, cb](PeerConnection::State state) {
  247. cb(static_cast<rtcState>(state), getUserPointer(pc));
  248. });
  249. else
  250. peerConnection->onStateChange(nullptr);
  251. });
  252. }
  253. int rtcSetGatheringStateChangeCallback(int pc, gatheringStateCallbackFunc cb) {
  254. return WRAP({
  255. auto peerConnection = getPeerConnection(pc);
  256. if (cb)
  257. peerConnection->onGatheringStateChange([pc, cb](PeerConnection::GatheringState state) {
  258. cb(static_cast<rtcGatheringState>(state), getUserPointer(pc));
  259. });
  260. else
  261. peerConnection->onGatheringStateChange(nullptr);
  262. });
  263. }
  264. int rtcSetRemoteDescription(int pc, const char *sdp, const char *type) {
  265. return WRAP({
  266. auto peerConnection = getPeerConnection(pc);
  267. if (!sdp)
  268. throw std::invalid_argument("Unexpected null pointer");
  269. peerConnection->setRemoteDescription({string(sdp), type ? string(type) : ""});
  270. });
  271. }
  272. int rtcAddRemoteCandidate(int pc, const char *cand, const char *mid) {
  273. return WRAP({
  274. auto peerConnection = getPeerConnection(pc);
  275. if (!cand)
  276. throw std::invalid_argument("Unexpected null pointer");
  277. peerConnection->addRemoteCandidate({string(cand), mid ? string(mid) : ""});
  278. });
  279. }
  280. int rtcGetLocalAddress(int pc, char *buffer, int size) {
  281. return WRAP({
  282. auto peerConnection = getPeerConnection(pc);
  283. if (!buffer)
  284. throw std::invalid_argument("Unexpected null pointer");
  285. if (auto addr = peerConnection->localAddress()) {
  286. size = std::min(size_t(size - 1), addr->size());
  287. std::copy(addr->data(), addr->data() + size, buffer);
  288. buffer[size] = '\0';
  289. return size + 1;
  290. }
  291. });
  292. }
  293. int rtcGetRemoteAddress(int pc, char *buffer, int size) {
  294. return WRAP({
  295. auto peerConnection = getPeerConnection(pc);
  296. if (!buffer)
  297. throw std::invalid_argument("Unexpected null pointer");
  298. if (auto addr = peerConnection->remoteAddress()) {
  299. size = std::min(size_t(size - 1), addr->size());
  300. std::copy(addr->data(), addr->data() + size, buffer);
  301. buffer[size] = '\0';
  302. return size + 1;
  303. }
  304. });
  305. }
  306. int rtcGetDataChannelLabel(int dc, char *buffer, int size) {
  307. return WRAP({
  308. auto dataChannel = getDataChannel(dc);
  309. if (!buffer)
  310. throw std::invalid_argument("Unexpected null pointer");
  311. if (size >= 0) {
  312. string label = dataChannel->label();
  313. size = std::min(size_t(size - 1), label.size());
  314. std::copy(label.data(), label.data() + size, buffer);
  315. buffer[size] = '\0';
  316. return size + 1;
  317. } else {
  318. return 0;
  319. }
  320. });
  321. }
  322. int rtcSetOpenCallback(int id, openCallbackFunc cb) {
  323. return WRAP({
  324. auto channel = getChannel(id);
  325. if (cb)
  326. channel->onOpen([id, cb]() { cb(getUserPointer(id)); });
  327. else
  328. channel->onOpen(nullptr);
  329. });
  330. }
  331. int rtcSetClosedCallback(int id, closedCallbackFunc cb) {
  332. return WRAP({
  333. auto channel = getChannel(id);
  334. if (cb)
  335. channel->onClosed([id, cb]() { cb(getUserPointer(id)); });
  336. else
  337. channel->onClosed(nullptr);
  338. });
  339. }
  340. int rtcSetErrorCallback(int id, errorCallbackFunc cb) {
  341. return WRAP({
  342. auto channel = getChannel(id);
  343. if (cb)
  344. channel->onError(
  345. [id, cb](const string &error) { cb(error.c_str(), getUserPointer(id)); });
  346. else
  347. channel->onError(nullptr);
  348. });
  349. }
  350. int rtcSetMessageCallback(int id, messageCallbackFunc cb) {
  351. return WRAP({
  352. auto channel = getChannel(id);
  353. if (cb)
  354. channel->onMessage(
  355. [id, cb](const binary &b) {
  356. cb(reinterpret_cast<const char *>(b.data()), b.size(), getUserPointer(id));
  357. },
  358. [id, cb](const string &s) { cb(s.c_str(), -1, getUserPointer(id)); });
  359. else
  360. channel->onMessage(nullptr);
  361. });
  362. }
  363. int rtcSendMessage(int id, const char *data, int size) {
  364. return WRAP({
  365. auto channel = getChannel(id);
  366. if (!data)
  367. throw std::invalid_argument("Unexpected null pointer");
  368. if (size >= 0) {
  369. auto b = reinterpret_cast<const byte *>(data);
  370. channel->send(binary(b, b + size));
  371. return size;
  372. } else {
  373. string str(data);
  374. int len = str.size();
  375. channel->send(std::move(str));
  376. return len;
  377. }
  378. });
  379. }
  380. int rtcGetBufferedAmount(int id) {
  381. return WRAP({
  382. auto channel = getChannel(id);
  383. return int(channel->bufferedAmount());
  384. });
  385. }
  386. int rtcSetBufferedAmountLowThreshold(int id, int amount) {
  387. return WRAP({
  388. auto channel = getChannel(id);
  389. channel->setBufferedAmountLowThreshold(size_t(amount));
  390. });
  391. }
  392. int rtcSetBufferedAmountLowCallback(int id, bufferedAmountLowCallbackFunc cb) {
  393. return WRAP({
  394. auto channel = getChannel(id);
  395. if (cb)
  396. channel->onBufferedAmountLow([id, cb]() { cb(getUserPointer(id)); });
  397. else
  398. channel->onBufferedAmountLow(nullptr);
  399. });
  400. }
  401. int rtcGetAvailableAmount(int id) {
  402. return WRAP({ return int(getChannel(id)->availableAmount()); });
  403. }
  404. int rtcSetAvailableCallback(int id, availableCallbackFunc cb) {
  405. return WRAP({
  406. auto channel = getChannel(id);
  407. if (cb)
  408. channel->onOpen([id, cb]() { cb(getUserPointer(id)); });
  409. else
  410. channel->onOpen(nullptr);
  411. });
  412. }
  413. int rtcReceiveMessage(int id, char *buffer, int *size) {
  414. return WRAP({
  415. auto channel = getChannel(id);
  416. if (!buffer || !size)
  417. throw std::invalid_argument("Unexpected null pointer");
  418. if (auto message = channel->receive())
  419. return std::visit( //
  420. overloaded{ //
  421. [&](const binary &b) {
  422. *size = std::min(*size, int(b.size()));
  423. auto data = reinterpret_cast<const char *>(b.data());
  424. std::copy(data, data + *size, buffer);
  425. return 1;
  426. },
  427. [&](const string &s) {
  428. int len = std::min(*size - 1, int(s.size()));
  429. if (len >= 0) {
  430. std::copy(s.data(), s.data() + len, buffer);
  431. buffer[len] = '\0';
  432. }
  433. *size = -(len + 1);
  434. return 1;
  435. }},
  436. *message);
  437. else
  438. return 0;
  439. });
  440. }
  441. void rtcPreload() { rtc::Preload(); }
  442. void rtcCleanup() { rtc::Cleanup(); }