rtc.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 (size <= 0)
  286. return 0;
  287. if (auto addr = peerConnection->localAddress()) {
  288. const char *data = addr->data();
  289. size = std::min(size_t(size - 1), addr->size());
  290. std::copy(data, data + size, buffer);
  291. buffer[size] = '\0';
  292. return size + 1;
  293. }
  294. });
  295. }
  296. int rtcGetRemoteAddress(int pc, char *buffer, int size) {
  297. return WRAP({
  298. auto peerConnection = getPeerConnection(pc);
  299. if (!buffer)
  300. throw std::invalid_argument("Unexpected null pointer");
  301. if (size <= 0)
  302. return 0;
  303. if (auto addr = peerConnection->remoteAddress()) {
  304. const char *data = addr->data();
  305. size = std::min(size_t(size - 1), addr->size());
  306. std::copy(data, data + size, buffer);
  307. buffer[size] = '\0';
  308. return size + 1;
  309. }
  310. });
  311. }
  312. int rtcGetDataChannelLabel(int dc, char *buffer, int size) {
  313. return WRAP({
  314. auto dataChannel = getDataChannel(dc);
  315. if (!buffer)
  316. throw std::invalid_argument("Unexpected null pointer");
  317. if (size <= 0)
  318. return 0;
  319. string label = dataChannel->label();
  320. const char *data = label.data();
  321. size = std::min(size_t(size - 1), label.size());
  322. std::copy(data, data + size, buffer);
  323. buffer[size] = '\0';
  324. return size + 1;
  325. });
  326. }
  327. int rtcSetOpenCallback(int id, openCallbackFunc cb) {
  328. return WRAP({
  329. auto channel = getChannel(id);
  330. if (cb)
  331. channel->onOpen([id, cb]() { cb(getUserPointer(id)); });
  332. else
  333. channel->onOpen(nullptr);
  334. });
  335. }
  336. int rtcSetClosedCallback(int id, closedCallbackFunc cb) {
  337. return WRAP({
  338. auto channel = getChannel(id);
  339. if (cb)
  340. channel->onClosed([id, cb]() { cb(getUserPointer(id)); });
  341. else
  342. channel->onClosed(nullptr);
  343. });
  344. }
  345. int rtcSetErrorCallback(int id, errorCallbackFunc cb) {
  346. return WRAP({
  347. auto channel = getChannel(id);
  348. if (cb)
  349. channel->onError(
  350. [id, cb](const string &error) { cb(error.c_str(), getUserPointer(id)); });
  351. else
  352. channel->onError(nullptr);
  353. });
  354. }
  355. int rtcSetMessageCallback(int id, messageCallbackFunc cb) {
  356. return WRAP({
  357. auto channel = getChannel(id);
  358. if (cb)
  359. channel->onMessage(
  360. [id, cb](const binary &b) {
  361. cb(reinterpret_cast<const char *>(b.data()), b.size(), getUserPointer(id));
  362. },
  363. [id, cb](const string &s) { cb(s.c_str(), -1, getUserPointer(id)); });
  364. else
  365. channel->onMessage(nullptr);
  366. });
  367. }
  368. int rtcSendMessage(int id, const char *data, int size) {
  369. return WRAP({
  370. auto channel = getChannel(id);
  371. if (!data)
  372. throw std::invalid_argument("Unexpected null pointer");
  373. if (size >= 0) {
  374. auto b = reinterpret_cast<const byte *>(data);
  375. channel->send(binary(b, b + size));
  376. return size;
  377. } else {
  378. string str(data);
  379. int len = str.size();
  380. channel->send(std::move(str));
  381. return len;
  382. }
  383. });
  384. }
  385. int rtcGetBufferedAmount(int id) {
  386. return WRAP({
  387. auto channel = getChannel(id);
  388. return int(channel->bufferedAmount());
  389. });
  390. }
  391. int rtcSetBufferedAmountLowThreshold(int id, int amount) {
  392. return WRAP({
  393. auto channel = getChannel(id);
  394. channel->setBufferedAmountLowThreshold(size_t(amount));
  395. });
  396. }
  397. int rtcSetBufferedAmountLowCallback(int id, bufferedAmountLowCallbackFunc cb) {
  398. return WRAP({
  399. auto channel = getChannel(id);
  400. if (cb)
  401. channel->onBufferedAmountLow([id, cb]() { cb(getUserPointer(id)); });
  402. else
  403. channel->onBufferedAmountLow(nullptr);
  404. });
  405. }
  406. int rtcGetAvailableAmount(int id) {
  407. return WRAP({ return int(getChannel(id)->availableAmount()); });
  408. }
  409. int rtcSetAvailableCallback(int id, availableCallbackFunc cb) {
  410. return WRAP({
  411. auto channel = getChannel(id);
  412. if (cb)
  413. channel->onOpen([id, cb]() { cb(getUserPointer(id)); });
  414. else
  415. channel->onOpen(nullptr);
  416. });
  417. }
  418. int rtcReceiveMessage(int id, char *buffer, int *size) {
  419. return WRAP({
  420. auto channel = getChannel(id);
  421. if (!buffer || !size)
  422. throw std::invalid_argument("Unexpected null pointer");
  423. if (auto message = channel->receive())
  424. return std::visit( //
  425. overloaded{ //
  426. [&](const binary &b) {
  427. *size = std::min(*size, int(b.size()));
  428. auto data = reinterpret_cast<const char *>(b.data());
  429. std::copy(data, data + *size, buffer);
  430. return 1;
  431. },
  432. [&](const string &s) {
  433. int len = std::min(*size - 1, int(s.size()));
  434. if (len >= 0) {
  435. std::copy(s.data(), s.data() + len, buffer);
  436. buffer[len] = '\0';
  437. }
  438. *size = -(len + 1);
  439. return 1;
  440. }},
  441. *message);
  442. else
  443. return 0;
  444. });
  445. }
  446. void rtcPreload() { rtc::Preload(); }
  447. void rtcCleanup() { rtc::Cleanup(); }