capi.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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 <chrono>
  28. #include <exception>
  29. #include <mutex>
  30. #include <type_traits>
  31. #include <unordered_map>
  32. #include <utility>
  33. #ifdef _WIN32
  34. #include <codecvt>
  35. #include <locale>
  36. #endif
  37. using namespace rtc;
  38. using std::shared_ptr;
  39. using std::string;
  40. using std::chrono::milliseconds;
  41. namespace {
  42. std::unordered_map<int, shared_ptr<PeerConnection>> peerConnectionMap;
  43. std::unordered_map<int, shared_ptr<DataChannel>> dataChannelMap;
  44. std::unordered_map<int, shared_ptr<Track>> trackMap;
  45. #if RTC_ENABLE_WEBSOCKET
  46. std::unordered_map<int, shared_ptr<WebSocket>> webSocketMap;
  47. #endif
  48. std::unordered_map<int, void *> userPointerMap;
  49. std::mutex mutex;
  50. int lastId = 0;
  51. std::optional<void *> getUserPointer(int id) {
  52. std::lock_guard lock(mutex);
  53. auto it = userPointerMap.find(id);
  54. return it != userPointerMap.end() ? std::make_optional(it->second) : nullopt;
  55. }
  56. void setUserPointer(int i, void *ptr) {
  57. std::lock_guard lock(mutex);
  58. userPointerMap[i] = ptr;
  59. }
  60. shared_ptr<PeerConnection> getPeerConnection(int id) {
  61. std::lock_guard lock(mutex);
  62. if (auto it = peerConnectionMap.find(id); it != peerConnectionMap.end())
  63. return it->second;
  64. else
  65. throw std::invalid_argument("PeerConnection ID does not exist");
  66. }
  67. shared_ptr<DataChannel> getDataChannel(int id) {
  68. std::lock_guard lock(mutex);
  69. if (auto it = dataChannelMap.find(id); it != dataChannelMap.end())
  70. return it->second;
  71. else
  72. throw std::invalid_argument("DataChannel ID does not exist");
  73. }
  74. shared_ptr<Track> getTrack(int id) {
  75. std::lock_guard lock(mutex);
  76. if (auto it = trackMap.find(id); it != trackMap.end())
  77. return it->second;
  78. else
  79. throw std::invalid_argument("Track ID does not exist");
  80. }
  81. int emplacePeerConnection(shared_ptr<PeerConnection> ptr) {
  82. std::lock_guard lock(mutex);
  83. int pc = ++lastId;
  84. peerConnectionMap.emplace(std::make_pair(pc, ptr));
  85. userPointerMap.emplace(std::make_pair(pc, nullptr));
  86. return pc;
  87. }
  88. int emplaceDataChannel(shared_ptr<DataChannel> ptr) {
  89. std::lock_guard lock(mutex);
  90. int dc = ++lastId;
  91. dataChannelMap.emplace(std::make_pair(dc, ptr));
  92. userPointerMap.emplace(std::make_pair(dc, nullptr));
  93. return dc;
  94. }
  95. int emplaceTrack(shared_ptr<Track> ptr) {
  96. std::lock_guard lock(mutex);
  97. int tr = ++lastId;
  98. trackMap.emplace(std::make_pair(tr, ptr));
  99. userPointerMap.emplace(std::make_pair(tr, nullptr));
  100. return tr;
  101. }
  102. void erasePeerConnection(int pc) {
  103. std::lock_guard lock(mutex);
  104. if (peerConnectionMap.erase(pc) == 0)
  105. throw std::invalid_argument("PeerConnection ID does not exist");
  106. userPointerMap.erase(pc);
  107. }
  108. void eraseDataChannel(int dc) {
  109. std::lock_guard lock(mutex);
  110. if (dataChannelMap.erase(dc) == 0)
  111. throw std::invalid_argument("DataChannel ID does not exist");
  112. userPointerMap.erase(dc);
  113. }
  114. void eraseTrack(int tr) {
  115. std::lock_guard lock(mutex);
  116. if (trackMap.erase(tr) == 0)
  117. throw std::invalid_argument("Track ID does not exist");
  118. userPointerMap.erase(tr);
  119. }
  120. #if RTC_ENABLE_WEBSOCKET
  121. shared_ptr<WebSocket> getWebSocket(int id) {
  122. std::lock_guard lock(mutex);
  123. if (auto it = webSocketMap.find(id); it != webSocketMap.end())
  124. return it->second;
  125. else
  126. throw std::invalid_argument("WebSocket ID does not exist");
  127. }
  128. int emplaceWebSocket(shared_ptr<WebSocket> ptr) {
  129. std::lock_guard lock(mutex);
  130. int ws = ++lastId;
  131. webSocketMap.emplace(std::make_pair(ws, ptr));
  132. userPointerMap.emplace(std::make_pair(ws, nullptr));
  133. return ws;
  134. }
  135. void eraseWebSocket(int ws) {
  136. std::lock_guard lock(mutex);
  137. if (webSocketMap.erase(ws) == 0)
  138. throw std::invalid_argument("WebSocket ID does not exist");
  139. userPointerMap.erase(ws);
  140. }
  141. #endif
  142. shared_ptr<Channel> getChannel(int id) {
  143. std::lock_guard lock(mutex);
  144. if (auto it = dataChannelMap.find(id); it != dataChannelMap.end())
  145. return it->second;
  146. if (auto it = trackMap.find(id); it != trackMap.end())
  147. return it->second;
  148. #if RTC_ENABLE_WEBSOCKET
  149. if (auto it = webSocketMap.find(id); it != webSocketMap.end())
  150. return it->second;
  151. #endif
  152. throw std::invalid_argument("DataChannel, Track, or WebSocket ID does not exist");
  153. }
  154. template <typename F> int wrap(F func) {
  155. try {
  156. return int(func());
  157. } catch (const std::invalid_argument &e) {
  158. PLOG_ERROR << e.what();
  159. return RTC_ERR_INVALID;
  160. } catch (const std::exception &e) {
  161. PLOG_ERROR << e.what();
  162. return RTC_ERR_FAILURE;
  163. }
  164. }
  165. #define WRAP(statement) \
  166. wrap([&]() { \
  167. statement; \
  168. return RTC_ERR_SUCCESS; \
  169. })
  170. class plog_appender : public plog::IAppender {
  171. public:
  172. plog_appender(rtcLogCallbackFunc cb = nullptr) { set_callback(cb); }
  173. void set_callback(rtcLogCallbackFunc cb) {
  174. std::lock_guard lock(mutex);
  175. callback = cb;
  176. }
  177. void write(const plog::Record &record) override {
  178. plog::Severity severity = record.getSeverity();
  179. auto formatted = plog::FuncMessageFormatter::format(record);
  180. formatted.pop_back(); // remove newline
  181. #ifdef _WIN32
  182. using convert_type = std::codecvt_utf8<wchar_t>;
  183. std::wstring_convert<convert_type, wchar_t> converter;
  184. std::string str = converter.to_bytes(formatted);
  185. #else
  186. std::string str = formatted;
  187. #endif
  188. std::lock_guard lock(mutex);
  189. if (callback)
  190. callback(static_cast<rtcLogLevel>(record.getSeverity()), str.c_str());
  191. else
  192. std::cout << plog::severityToString(severity) << " " << str << std::endl;
  193. }
  194. private:
  195. rtcLogCallbackFunc callback;
  196. };
  197. } // namespace
  198. void rtcInitLogger(rtcLogLevel level, rtcLogCallbackFunc cb) {
  199. static std::optional<plog_appender> appender;
  200. auto severity = static_cast<plog::Severity>(level);
  201. if (appender) {
  202. appender->set_callback(cb);
  203. InitLogger(severity, nullptr); // change the severity
  204. } else if (cb) {
  205. appender.emplace(plog_appender(cb));
  206. InitLogger(severity, &appender.value());
  207. } else {
  208. InitLogger(severity, nullptr); // log to stdout
  209. }
  210. }
  211. void rtcSetUserPointer(int i, void *ptr) { setUserPointer(i, ptr); }
  212. int rtcCreatePeerConnection(const rtcConfiguration *config) {
  213. return WRAP({
  214. Configuration c;
  215. for (int i = 0; i < config->iceServersCount; ++i)
  216. c.iceServers.emplace_back(string(config->iceServers[i]));
  217. if (config->portRangeBegin || config->portRangeEnd) {
  218. c.portRangeBegin = config->portRangeBegin;
  219. c.portRangeEnd = config->portRangeEnd;
  220. }
  221. return emplacePeerConnection(std::make_shared<PeerConnection>(c));
  222. });
  223. }
  224. int rtcDeletePeerConnection(int pc) {
  225. return WRAP({
  226. auto peerConnection = getPeerConnection(pc);
  227. peerConnection->onDataChannel(nullptr);
  228. peerConnection->onLocalDescription(nullptr);
  229. peerConnection->onLocalCandidate(nullptr);
  230. peerConnection->onStateChange(nullptr);
  231. peerConnection->onGatheringStateChange(nullptr);
  232. erasePeerConnection(pc);
  233. });
  234. }
  235. int rtcAddDataChannel(int pc, const char *label) {
  236. return rtcAddDataChannelExt(pc, label, nullptr, nullptr);
  237. }
  238. int rtcAddDataChannelExt(int pc, const char *label, const char *protocol,
  239. const rtcReliability *reliability) {
  240. return WRAP({
  241. Reliability r = {};
  242. if (reliability) {
  243. r.unordered = reliability->unordered;
  244. if (reliability->unreliable) {
  245. if (reliability->maxPacketLifeTime > 0) {
  246. r.type = Reliability::Type::Timed;
  247. r.rexmit = milliseconds(reliability->maxPacketLifeTime);
  248. } else {
  249. r.type = Reliability::Type::Rexmit;
  250. r.rexmit = int(reliability->maxRetransmits);
  251. }
  252. } else {
  253. r.type = Reliability::Type::Reliable;
  254. }
  255. }
  256. auto peerConnection = getPeerConnection(pc);
  257. int dc = emplaceDataChannel(peerConnection->addDataChannel(
  258. string(label ? label : ""), string(protocol ? protocol : ""), r));
  259. if (auto ptr = getUserPointer(pc))
  260. rtcSetUserPointer(dc, *ptr);
  261. return dc;
  262. });
  263. }
  264. int rtcCreateDataChannel(int pc, const char *label) {
  265. return rtcCreateDataChannelExt(pc, label, nullptr, nullptr);
  266. }
  267. int rtcCreateDataChannelExt(int pc, const char *label, const char *protocol,
  268. const rtcReliability *reliability) {
  269. int dc = rtcAddDataChannelExt(pc, label, protocol, reliability);
  270. rtcSetLocalDescription(pc);
  271. return dc;
  272. }
  273. int rtcDeleteDataChannel(int dc) {
  274. return WRAP({
  275. auto dataChannel = getDataChannel(dc);
  276. dataChannel->onOpen(nullptr);
  277. dataChannel->onClosed(nullptr);
  278. dataChannel->onError(nullptr);
  279. dataChannel->onMessage(nullptr);
  280. dataChannel->onBufferedAmountLow(nullptr);
  281. dataChannel->onAvailable(nullptr);
  282. eraseDataChannel(dc);
  283. });
  284. }
  285. int rtcAddTrack(int pc, const char *mediaDescriptionSdp) {
  286. return WRAP({
  287. if (!mediaDescriptionSdp)
  288. throw std::invalid_argument("Unexpected null pointer for track media description");
  289. auto peerConnection = getPeerConnection(pc);
  290. Description::Media media{string(mediaDescriptionSdp)};
  291. int tr = emplaceTrack(peerConnection->addTrack(std::move(media)));
  292. if (auto ptr = getUserPointer(pc))
  293. rtcSetUserPointer(tr, *ptr);
  294. return tr;
  295. });
  296. }
  297. int rtcDeleteTrack(int tr) {
  298. return WRAP({
  299. auto track = getTrack(tr);
  300. track->onOpen(nullptr);
  301. track->onClosed(nullptr);
  302. track->onError(nullptr);
  303. track->onMessage(nullptr);
  304. track->onBufferedAmountLow(nullptr);
  305. track->onAvailable(nullptr);
  306. eraseTrack(tr);
  307. });
  308. }
  309. int rtcGetTrackDescription(int tr, char *buffer, int size) {
  310. return WRAP({
  311. auto track = getTrack(tr);
  312. if (size <= 0)
  313. return 0;
  314. if (!buffer)
  315. throw std::invalid_argument("Unexpected null pointer for buffer");
  316. string description(track->description());
  317. const char *data = description.data();
  318. size = std::min(size - 1, int(description.size()));
  319. std::copy(data, data + size, buffer);
  320. buffer[size] = '\0';
  321. return int(size + 1);
  322. });
  323. }
  324. #if RTC_ENABLE_WEBSOCKET
  325. int rtcCreateWebSocket(const char *url) {
  326. return WRAP({
  327. auto ws = std::make_shared<WebSocket>();
  328. ws->open(url);
  329. return emplaceWebSocket(ws);
  330. });
  331. }
  332. int rtcCreateWebSocketEx(const char *url, const rtcWsConfiguration *config) {
  333. return WRAP({
  334. WebSocket::Configuration c;
  335. c.disableTlsVerification = config->disableTlsVerification;
  336. auto ws = std::make_shared<WebSocket>(c);
  337. ws->open(url);
  338. return emplaceWebSocket(ws);
  339. });
  340. }
  341. int rtcDeleteWebsocket(int ws) {
  342. return WRAP({
  343. auto webSocket = getWebSocket(ws);
  344. webSocket->onOpen(nullptr);
  345. webSocket->onClosed(nullptr);
  346. webSocket->onError(nullptr);
  347. webSocket->onMessage(nullptr);
  348. webSocket->onBufferedAmountLow(nullptr);
  349. webSocket->onAvailable(nullptr);
  350. eraseWebSocket(ws);
  351. });
  352. }
  353. #endif
  354. int rtcSetLocalDescriptionCallback(int pc, rtcDescriptionCallbackFunc cb) {
  355. return WRAP({
  356. auto peerConnection = getPeerConnection(pc);
  357. if (cb)
  358. peerConnection->onLocalDescription([pc, cb](Description desc) {
  359. if (auto ptr = getUserPointer(pc))
  360. cb(string(desc).c_str(), desc.typeString().c_str(), *ptr);
  361. });
  362. else
  363. peerConnection->onLocalDescription(nullptr);
  364. });
  365. }
  366. int rtcSetLocalCandidateCallback(int pc, rtcCandidateCallbackFunc cb) {
  367. return WRAP({
  368. auto peerConnection = getPeerConnection(pc);
  369. if (cb)
  370. peerConnection->onLocalCandidate([pc, cb](Candidate cand) {
  371. if (auto ptr = getUserPointer(pc))
  372. cb(cand.candidate().c_str(), cand.mid().c_str(), *ptr);
  373. });
  374. else
  375. peerConnection->onLocalCandidate(nullptr);
  376. });
  377. }
  378. int rtcSetStateChangeCallback(int pc, rtcStateChangeCallbackFunc cb) {
  379. return WRAP({
  380. auto peerConnection = getPeerConnection(pc);
  381. if (cb)
  382. peerConnection->onStateChange([pc, cb](PeerConnection::State state) {
  383. if (auto ptr = getUserPointer(pc))
  384. cb(static_cast<rtcState>(state), *ptr);
  385. });
  386. else
  387. peerConnection->onStateChange(nullptr);
  388. });
  389. }
  390. int rtcSetGatheringStateChangeCallback(int pc, rtcGatheringStateCallbackFunc cb) {
  391. return WRAP({
  392. auto peerConnection = getPeerConnection(pc);
  393. if (cb)
  394. peerConnection->onGatheringStateChange([pc, cb](PeerConnection::GatheringState state) {
  395. if (auto ptr = getUserPointer(pc))
  396. cb(static_cast<rtcGatheringState>(state), *ptr);
  397. });
  398. else
  399. peerConnection->onGatheringStateChange(nullptr);
  400. });
  401. }
  402. int rtcSetDataChannelCallback(int pc, rtcDataChannelCallbackFunc cb) {
  403. return WRAP({
  404. auto peerConnection = getPeerConnection(pc);
  405. if (cb)
  406. peerConnection->onDataChannel([pc, cb](std::shared_ptr<DataChannel> dataChannel) {
  407. int dc = emplaceDataChannel(dataChannel);
  408. if (auto ptr = getUserPointer(pc)) {
  409. rtcSetUserPointer(dc, *ptr);
  410. cb(dc, *ptr);
  411. }
  412. });
  413. else
  414. peerConnection->onDataChannel(nullptr);
  415. });
  416. }
  417. int rtcSetTrackCallback(int pc, rtcTrackCallbackFunc cb) {
  418. return WRAP({
  419. auto peerConnection = getPeerConnection(pc);
  420. if (cb)
  421. peerConnection->onTrack([pc, cb](std::shared_ptr<Track> track) {
  422. int tr = emplaceTrack(track);
  423. if (auto ptr = getUserPointer(pc)) {
  424. rtcSetUserPointer(tr, *ptr);
  425. cb(tr, *ptr);
  426. }
  427. });
  428. else
  429. peerConnection->onTrack(nullptr);
  430. });
  431. }
  432. int rtcSetLocalDescription(int pc) {
  433. return WRAP({
  434. auto peerConnection = getPeerConnection(pc);
  435. peerConnection->setLocalDescription();
  436. });
  437. }
  438. int rtcSetRemoteDescription(int pc, const char *sdp, const char *type) {
  439. return WRAP({
  440. auto peerConnection = getPeerConnection(pc);
  441. if (!sdp)
  442. throw std::invalid_argument("Unexpected null pointer for remote description");
  443. peerConnection->setRemoteDescription({string(sdp), type ? string(type) : ""});
  444. });
  445. }
  446. int rtcAddRemoteCandidate(int pc, const char *cand, const char *mid) {
  447. return WRAP({
  448. auto peerConnection = getPeerConnection(pc);
  449. if (!cand)
  450. throw std::invalid_argument("Unexpected null pointer for remote candidate");
  451. peerConnection->addRemoteCandidate({string(cand), mid ? string(mid) : ""});
  452. });
  453. }
  454. int rtcGetLocalAddress(int pc, char *buffer, int size) {
  455. return WRAP({
  456. auto peerConnection = getPeerConnection(pc);
  457. if (size <= 0)
  458. return 0;
  459. if (!buffer)
  460. throw std::invalid_argument("Unexpected null pointer for buffer");
  461. if (auto addr = peerConnection->localAddress()) {
  462. const char *data = addr->data();
  463. size = std::min(size - 1, int(addr->size()));
  464. std::copy(data, data + size, buffer);
  465. buffer[size] = '\0';
  466. return size + 1;
  467. }
  468. });
  469. }
  470. int rtcGetRemoteAddress(int pc, char *buffer, int size) {
  471. return WRAP({
  472. auto peerConnection = getPeerConnection(pc);
  473. if (size <= 0)
  474. return 0;
  475. if (!buffer)
  476. throw std::invalid_argument("Unexpected null pointer for buffer");
  477. if (auto addr = peerConnection->remoteAddress()) {
  478. const char *data = addr->data();
  479. size = std::min(size - 1, int(addr->size()));
  480. std::copy(data, data + size, buffer);
  481. buffer[size] = '\0';
  482. return int(size + 1);
  483. }
  484. });
  485. }
  486. int rtcGetDataChannelLabel(int dc, char *buffer, int size) {
  487. return WRAP({
  488. auto dataChannel = getDataChannel(dc);
  489. if (size <= 0)
  490. return 0;
  491. if (!buffer)
  492. throw std::invalid_argument("Unexpected null pointer for buffer");
  493. string label = dataChannel->label();
  494. const char *data = label.data();
  495. size = std::min(size - 1, int(label.size()));
  496. std::copy(data, data + size, buffer);
  497. buffer[size] = '\0';
  498. return int(size + 1);
  499. });
  500. }
  501. int rtcGetDataChannelProtocol(int dc, char *buffer, int size) {
  502. return WRAP({
  503. auto dataChannel = getDataChannel(dc);
  504. if (size <= 0)
  505. return 0;
  506. if (!buffer)
  507. throw std::invalid_argument("Unexpected null pointer for buffer");
  508. string protocol = dataChannel->protocol();
  509. const char *data = protocol.data();
  510. size = std::min(size - 1, int(protocol.size()));
  511. std::copy(data, data + size, buffer);
  512. buffer[size] = '\0';
  513. return int(size + 1);
  514. });
  515. }
  516. int rtcGetDataChannelReliability(int dc, rtcReliability *reliability) {
  517. return WRAP({
  518. auto dataChannel = getDataChannel(dc);
  519. if (!reliability)
  520. throw std::invalid_argument("Unexpected null pointer for reliability");
  521. Reliability r = dataChannel->reliability();
  522. std::memset(reliability, 0, sizeof(*reliability));
  523. reliability->unordered = r.unordered;
  524. if (r.type == Reliability::Type::Timed) {
  525. reliability->unreliable = true;
  526. reliability->maxPacketLifeTime = unsigned(std::get<milliseconds>(r.rexmit).count());
  527. } else if (r.type == Reliability::Type::Rexmit) {
  528. reliability->unreliable = true;
  529. reliability->maxRetransmits = unsigned(std::get<int>(r.rexmit));
  530. } else {
  531. reliability->unreliable = false;
  532. }
  533. return 0;
  534. });
  535. }
  536. int rtcSetOpenCallback(int id, rtcOpenCallbackFunc cb) {
  537. return WRAP({
  538. auto channel = getChannel(id);
  539. if (cb)
  540. channel->onOpen([id, cb]() {
  541. if (auto ptr = getUserPointer(id))
  542. cb(*ptr);
  543. });
  544. else
  545. channel->onOpen(nullptr);
  546. });
  547. }
  548. int rtcSetClosedCallback(int id, rtcClosedCallbackFunc cb) {
  549. return WRAP({
  550. auto channel = getChannel(id);
  551. if (cb)
  552. channel->onClosed([id, cb]() {
  553. if (auto ptr = getUserPointer(id))
  554. cb(*ptr);
  555. });
  556. else
  557. channel->onClosed(nullptr);
  558. });
  559. }
  560. int rtcSetErrorCallback(int id, rtcErrorCallbackFunc cb) {
  561. return WRAP({
  562. auto channel = getChannel(id);
  563. if (cb)
  564. channel->onError([id, cb](string error) {
  565. if (auto ptr = getUserPointer(id))
  566. cb(error.c_str(), *ptr);
  567. });
  568. else
  569. channel->onError(nullptr);
  570. });
  571. }
  572. int rtcSetMessageCallback(int id, rtcMessageCallbackFunc cb) {
  573. return WRAP({
  574. auto channel = getChannel(id);
  575. if (cb)
  576. channel->onMessage(
  577. [id, cb](binary b) {
  578. if (auto ptr = getUserPointer(id))
  579. cb(reinterpret_cast<const char *>(b.data()), int(b.size()), *ptr);
  580. },
  581. [id, cb](string s) {
  582. if (auto ptr = getUserPointer(id))
  583. cb(s.c_str(), -int(s.size() + 1), *ptr);
  584. });
  585. else
  586. channel->onMessage(nullptr);
  587. });
  588. }
  589. int rtcSendMessage(int id, const char *data, int size) {
  590. return WRAP({
  591. auto channel = getChannel(id);
  592. if (!data && size != 0)
  593. throw std::invalid_argument("Unexpected null pointer for data");
  594. if (size >= 0) {
  595. auto b = reinterpret_cast<const byte *>(data);
  596. channel->send(binary(b, b + size));
  597. return size;
  598. } else {
  599. string str(data);
  600. int len = int(str.size());
  601. channel->send(std::move(str));
  602. return len;
  603. }
  604. });
  605. }
  606. int rtcGetBufferedAmount(int id) {
  607. return WRAP({
  608. auto channel = getChannel(id);
  609. return int(channel->bufferedAmount());
  610. });
  611. }
  612. int rtcSetBufferedAmountLowThreshold(int id, int amount) {
  613. return WRAP({
  614. auto channel = getChannel(id);
  615. channel->setBufferedAmountLowThreshold(size_t(amount));
  616. });
  617. }
  618. int rtcSetBufferedAmountLowCallback(int id, rtcBufferedAmountLowCallbackFunc cb) {
  619. return WRAP({
  620. auto channel = getChannel(id);
  621. if (cb)
  622. channel->onBufferedAmountLow([id, cb]() {
  623. if (auto ptr = getUserPointer(id))
  624. cb(*ptr);
  625. });
  626. else
  627. channel->onBufferedAmountLow(nullptr);
  628. });
  629. }
  630. int rtcGetAvailableAmount(int id) {
  631. return WRAP({ return int(getChannel(id)->availableAmount()); });
  632. }
  633. int rtcSetAvailableCallback(int id, rtcAvailableCallbackFunc cb) {
  634. return WRAP({
  635. auto channel = getChannel(id);
  636. if (cb)
  637. channel->onOpen([id, cb]() {
  638. if (auto ptr = getUserPointer(id))
  639. cb(*ptr);
  640. });
  641. else
  642. channel->onOpen(nullptr);
  643. });
  644. }
  645. int rtcReceiveMessage(int id, char *buffer, int *size) {
  646. return WRAP({
  647. auto channel = getChannel(id);
  648. if (!size)
  649. throw std::invalid_argument("Unexpected null pointer for size");
  650. if (!buffer && *size != 0)
  651. throw std::invalid_argument("Unexpected null pointer for buffer");
  652. if (auto message = channel->receive())
  653. return std::visit( //
  654. overloaded{ //
  655. [&](binary b) {
  656. if (*size > 0) {
  657. *size = std::min(*size, int(b.size()));
  658. auto data = reinterpret_cast<const char *>(b.data());
  659. std::copy(data, data + *size, buffer);
  660. }
  661. return 1;
  662. },
  663. [&](string s) {
  664. if (*size > 0) {
  665. int len = std::min(*size - 1, int(s.size()));
  666. if (len >= 0) {
  667. std::copy(s.data(), s.data() + len, buffer);
  668. buffer[len] = '\0';
  669. }
  670. *size = -(len + 1);
  671. }
  672. return 1;
  673. }},
  674. *message);
  675. else
  676. return 0;
  677. });
  678. }
  679. void rtcPreload() { rtc::Preload(); }
  680. void rtcCleanup() { rtc::Cleanup(); }