capi.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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. int copyAndReturn(string s, char *buffer, int size) {
  171. if (!buffer)
  172. return int(s.size() + 1);
  173. if (size < int(s.size()))
  174. return RTC_ERR_TOO_SMALL;
  175. std::copy(s.begin(), s.end(), buffer);
  176. buffer[s.size()] = '\0';
  177. return int(s.size() + 1);
  178. }
  179. int copyAndReturn(binary b, char *buffer, int size) {
  180. if (!buffer)
  181. return int(b.size());
  182. if (size < int(b.size()))
  183. return RTC_ERR_TOO_SMALL;
  184. auto data = reinterpret_cast<const char *>(b.data());
  185. std::copy(data, data + b.size(), buffer);
  186. buffer[b.size()] = '\0';
  187. return int(b.size());
  188. }
  189. class plogAppender : public plog::IAppender {
  190. public:
  191. plogAppender(rtcLogCallbackFunc cb = nullptr) { setCallback(cb); }
  192. plogAppender(plogAppender &&appender) : callback(nullptr) {
  193. std::lock_guard lock(appender.callbackMutex);
  194. std::swap(appender.callback, callback);
  195. }
  196. void setCallback(rtcLogCallbackFunc cb) {
  197. std::lock_guard lock(callbackMutex);
  198. callback = cb;
  199. }
  200. void write(const plog::Record &record) override {
  201. plog::Severity severity = record.getSeverity();
  202. auto formatted = plog::FuncMessageFormatter::format(record);
  203. formatted.pop_back(); // remove newline
  204. #ifdef _WIN32
  205. using convert_type = std::codecvt_utf8<wchar_t>;
  206. std::wstring_convert<convert_type, wchar_t> converter;
  207. std::string str = converter.to_bytes(formatted);
  208. #else
  209. std::string str = formatted;
  210. #endif
  211. std::lock_guard lock(callbackMutex);
  212. if (callback)
  213. callback(static_cast<rtcLogLevel>(record.getSeverity()), str.c_str());
  214. else
  215. std::cout << plog::severityToString(severity) << " " << str << std::endl;
  216. }
  217. private:
  218. rtcLogCallbackFunc callback;
  219. std::mutex callbackMutex;
  220. };
  221. } // namespace
  222. void rtcInitLogger(rtcLogLevel level, rtcLogCallbackFunc cb) {
  223. static std::optional<plogAppender> appender;
  224. const auto severity = static_cast<plog::Severity>(level);
  225. std::lock_guard lock(mutex);
  226. if (appender) {
  227. appender->setCallback(cb);
  228. InitLogger(severity, nullptr); // change the severity
  229. } else if (cb) {
  230. appender.emplace(plogAppender(cb));
  231. InitLogger(severity, &appender.value());
  232. } else {
  233. InitLogger(severity, nullptr); // log to stdout
  234. }
  235. }
  236. void rtcSetUserPointer(int i, void *ptr) { setUserPointer(i, ptr); }
  237. int rtcCreatePeerConnection(const rtcConfiguration *config) {
  238. return WRAP({
  239. Configuration c;
  240. for (int i = 0; i < config->iceServersCount; ++i)
  241. c.iceServers.emplace_back(string(config->iceServers[i]));
  242. if (config->portRangeBegin || config->portRangeEnd) {
  243. c.portRangeBegin = config->portRangeBegin;
  244. c.portRangeEnd = config->portRangeEnd;
  245. }
  246. return emplacePeerConnection(std::make_shared<PeerConnection>(c));
  247. });
  248. }
  249. int rtcDeletePeerConnection(int pc) {
  250. return WRAP({
  251. auto peerConnection = getPeerConnection(pc);
  252. peerConnection->onDataChannel(nullptr);
  253. peerConnection->onLocalDescription(nullptr);
  254. peerConnection->onLocalCandidate(nullptr);
  255. peerConnection->onStateChange(nullptr);
  256. peerConnection->onGatheringStateChange(nullptr);
  257. erasePeerConnection(pc);
  258. });
  259. }
  260. int rtcAddDataChannel(int pc, const char *label) {
  261. return rtcAddDataChannelEx(pc, label, nullptr);
  262. }
  263. int rtcAddDataChannelEx(int pc, const char *label, const rtcDataChannelInit *init) {
  264. return WRAP({
  265. DataChannelInit dci = {};
  266. if (init) {
  267. auto *reliability = &init->reliability;
  268. dci.reliability.unordered = reliability->unordered;
  269. if (reliability->unreliable) {
  270. if (reliability->maxPacketLifeTime > 0) {
  271. dci.reliability.type = Reliability::Type::Timed;
  272. dci.reliability.rexmit = milliseconds(reliability->maxPacketLifeTime);
  273. } else {
  274. dci.reliability.type = Reliability::Type::Rexmit;
  275. dci.reliability.rexmit = int(reliability->maxRetransmits);
  276. }
  277. } else {
  278. dci.reliability.type = Reliability::Type::Reliable;
  279. }
  280. dci.negotiated = init->negotiated;
  281. dci.id = init->manualStream ? std::make_optional(init->stream) : nullopt;
  282. dci.protocol = init->protocol ? init->protocol : "";
  283. }
  284. auto peerConnection = getPeerConnection(pc);
  285. int dc = emplaceDataChannel(
  286. peerConnection->addDataChannel(string(label ? label : ""), std::move(dci)));
  287. if (auto ptr = getUserPointer(pc))
  288. rtcSetUserPointer(dc, *ptr);
  289. return dc;
  290. });
  291. }
  292. int rtcCreateDataChannel(int pc, const char *label) {
  293. return rtcCreateDataChannelEx(pc, label, nullptr);
  294. }
  295. int rtcCreateDataChannelEx(int pc, const char *label, const rtcDataChannelInit *init) {
  296. int dc = rtcAddDataChannelEx(pc, label, init);
  297. rtcSetLocalDescription(pc, NULL);
  298. return dc;
  299. }
  300. int rtcDeleteDataChannel(int dc) {
  301. return WRAP({
  302. auto dataChannel = getDataChannel(dc);
  303. dataChannel->onOpen(nullptr);
  304. dataChannel->onClosed(nullptr);
  305. dataChannel->onError(nullptr);
  306. dataChannel->onMessage(nullptr);
  307. dataChannel->onBufferedAmountLow(nullptr);
  308. dataChannel->onAvailable(nullptr);
  309. eraseDataChannel(dc);
  310. });
  311. }
  312. int rtcAddTrack(int pc, const char *mediaDescriptionSdp) {
  313. return WRAP({
  314. if (!mediaDescriptionSdp)
  315. throw std::invalid_argument("Unexpected null pointer for track media description");
  316. auto peerConnection = getPeerConnection(pc);
  317. Description::Media media{string(mediaDescriptionSdp)};
  318. int tr = emplaceTrack(peerConnection->addTrack(std::move(media)));
  319. if (auto ptr = getUserPointer(pc))
  320. rtcSetUserPointer(tr, *ptr);
  321. return tr;
  322. });
  323. }
  324. int rtcDeleteTrack(int tr) {
  325. return WRAP({
  326. auto track = getTrack(tr);
  327. track->onOpen(nullptr);
  328. track->onClosed(nullptr);
  329. track->onError(nullptr);
  330. track->onMessage(nullptr);
  331. track->onBufferedAmountLow(nullptr);
  332. track->onAvailable(nullptr);
  333. eraseTrack(tr);
  334. });
  335. }
  336. int rtcGetTrackDescription(int tr, char *buffer, int size) {
  337. return WRAP({
  338. auto track = getTrack(tr);
  339. return copyAndReturn(track->description(), buffer, size);
  340. });
  341. }
  342. #if RTC_ENABLE_WEBSOCKET
  343. int rtcCreateWebSocket(const char *url) {
  344. return WRAP({
  345. auto ws = std::make_shared<WebSocket>();
  346. ws->open(url);
  347. return emplaceWebSocket(ws);
  348. });
  349. }
  350. int rtcCreateWebSocketEx(const char *url, const rtcWsConfiguration *config) {
  351. return WRAP({
  352. WebSocket::Configuration c;
  353. c.disableTlsVerification = config->disableTlsVerification;
  354. auto ws = std::make_shared<WebSocket>(c);
  355. ws->open(url);
  356. return emplaceWebSocket(ws);
  357. });
  358. }
  359. int rtcDeleteWebsocket(int ws) {
  360. return WRAP({
  361. auto webSocket = getWebSocket(ws);
  362. webSocket->onOpen(nullptr);
  363. webSocket->onClosed(nullptr);
  364. webSocket->onError(nullptr);
  365. webSocket->onMessage(nullptr);
  366. webSocket->onBufferedAmountLow(nullptr);
  367. webSocket->onAvailable(nullptr);
  368. eraseWebSocket(ws);
  369. });
  370. }
  371. #endif
  372. int rtcSetLocalDescriptionCallback(int pc, rtcDescriptionCallbackFunc cb) {
  373. return WRAP({
  374. auto peerConnection = getPeerConnection(pc);
  375. if (cb)
  376. peerConnection->onLocalDescription([pc, cb](Description desc) {
  377. if (auto ptr = getUserPointer(pc))
  378. cb(pc, string(desc).c_str(), desc.typeString().c_str(), *ptr);
  379. });
  380. else
  381. peerConnection->onLocalDescription(nullptr);
  382. });
  383. }
  384. int rtcSetLocalCandidateCallback(int pc, rtcCandidateCallbackFunc cb) {
  385. return WRAP({
  386. auto peerConnection = getPeerConnection(pc);
  387. if (cb)
  388. peerConnection->onLocalCandidate([pc, cb](Candidate cand) {
  389. if (auto ptr = getUserPointer(pc))
  390. cb(pc, cand.candidate().c_str(), cand.mid().c_str(), *ptr);
  391. });
  392. else
  393. peerConnection->onLocalCandidate(nullptr);
  394. });
  395. }
  396. int rtcSetStateChangeCallback(int pc, rtcStateChangeCallbackFunc cb) {
  397. return WRAP({
  398. auto peerConnection = getPeerConnection(pc);
  399. if (cb)
  400. peerConnection->onStateChange([pc, cb](PeerConnection::State state) {
  401. if (auto ptr = getUserPointer(pc))
  402. cb(pc, static_cast<rtcState>(state), *ptr);
  403. });
  404. else
  405. peerConnection->onStateChange(nullptr);
  406. });
  407. }
  408. int rtcSetGatheringStateChangeCallback(int pc, rtcGatheringStateCallbackFunc cb) {
  409. return WRAP({
  410. auto peerConnection = getPeerConnection(pc);
  411. if (cb)
  412. peerConnection->onGatheringStateChange([pc, cb](PeerConnection::GatheringState state) {
  413. if (auto ptr = getUserPointer(pc))
  414. cb(pc, static_cast<rtcGatheringState>(state), *ptr);
  415. });
  416. else
  417. peerConnection->onGatheringStateChange(nullptr);
  418. });
  419. }
  420. int rtcSetSignalingStateChangeCallback(int pc, rtcSignalingStateCallbackFunc cb) {
  421. return WRAP({
  422. auto peerConnection = getPeerConnection(pc);
  423. if (cb)
  424. peerConnection->onSignalingStateChange([pc, cb](PeerConnection::SignalingState state) {
  425. if (auto ptr = getUserPointer(pc))
  426. cb(pc, static_cast<rtcSignalingState>(state), *ptr);
  427. });
  428. else
  429. peerConnection->onGatheringStateChange(nullptr);
  430. });
  431. }
  432. int rtcSetDataChannelCallback(int pc, rtcDataChannelCallbackFunc cb) {
  433. return WRAP({
  434. auto peerConnection = getPeerConnection(pc);
  435. if (cb)
  436. peerConnection->onDataChannel([pc, cb](std::shared_ptr<DataChannel> dataChannel) {
  437. int dc = emplaceDataChannel(dataChannel);
  438. if (auto ptr = getUserPointer(pc)) {
  439. rtcSetUserPointer(dc, *ptr);
  440. cb(pc, dc, *ptr);
  441. }
  442. });
  443. else
  444. peerConnection->onDataChannel(nullptr);
  445. });
  446. }
  447. int rtcSetTrackCallback(int pc, rtcTrackCallbackFunc cb) {
  448. return WRAP({
  449. auto peerConnection = getPeerConnection(pc);
  450. if (cb)
  451. peerConnection->onTrack([pc, cb](std::shared_ptr<Track> track) {
  452. int tr = emplaceTrack(track);
  453. if (auto ptr = getUserPointer(pc)) {
  454. rtcSetUserPointer(tr, *ptr);
  455. cb(pc, tr, *ptr);
  456. }
  457. });
  458. else
  459. peerConnection->onTrack(nullptr);
  460. });
  461. }
  462. int rtcSetLocalDescription(int pc, const char *type) {
  463. return WRAP({
  464. auto peerConnection = getPeerConnection(pc);
  465. peerConnection->setLocalDescription(type ? Description::stringToType(type)
  466. : Description::Type::Unspec);
  467. });
  468. }
  469. int rtcSetRemoteDescription(int pc, const char *sdp, const char *type) {
  470. return WRAP({
  471. auto peerConnection = getPeerConnection(pc);
  472. if (!sdp)
  473. throw std::invalid_argument("Unexpected null pointer for remote description");
  474. peerConnection->setRemoteDescription({string(sdp), type ? string(type) : ""});
  475. });
  476. }
  477. int rtcAddRemoteCandidate(int pc, const char *cand, const char *mid) {
  478. return WRAP({
  479. auto peerConnection = getPeerConnection(pc);
  480. if (!cand)
  481. throw std::invalid_argument("Unexpected null pointer for remote candidate");
  482. peerConnection->addRemoteCandidate({string(cand), mid ? string(mid) : ""});
  483. });
  484. }
  485. int rtcGetLocalDescription(int pc, char *buffer, int size) {
  486. return WRAP({
  487. auto peerConnection = getPeerConnection(pc);
  488. if (auto desc = peerConnection->localDescription())
  489. return copyAndReturn(string(*desc), buffer, size);
  490. else
  491. return RTC_ERR_NOT_AVAIL;
  492. });
  493. }
  494. int rtcGetRemoteDescription(int pc, char *buffer, int size) {
  495. return WRAP({
  496. auto peerConnection = getPeerConnection(pc);
  497. if (auto desc = peerConnection->remoteDescription())
  498. return copyAndReturn(string(*desc), buffer, size);
  499. else
  500. return RTC_ERR_NOT_AVAIL;
  501. });
  502. }
  503. int rtcGetLocalAddress(int pc, char *buffer, int size) {
  504. return WRAP({
  505. auto peerConnection = getPeerConnection(pc);
  506. if (auto addr = peerConnection->localAddress())
  507. return copyAndReturn(std::move(*addr), buffer, size);
  508. else
  509. return RTC_ERR_NOT_AVAIL;
  510. });
  511. }
  512. int rtcGetRemoteAddress(int pc, char *buffer, int size) {
  513. return WRAP({
  514. auto peerConnection = getPeerConnection(pc);
  515. if (auto addr = peerConnection->remoteAddress())
  516. return copyAndReturn(std::move(*addr), buffer, size);
  517. else
  518. return RTC_ERR_NOT_AVAIL;
  519. });
  520. }
  521. int rtcGetSelectedCandidatePair(int pc, char *local, int localSize, char *remote, int remoteSize) {
  522. return WRAP({
  523. auto peerConnection = getPeerConnection(pc);
  524. Candidate localCand;
  525. Candidate remoteCand;
  526. if (!peerConnection->getSelectedCandidatePair(&localCand, &remoteCand))
  527. return RTC_ERR_NOT_AVAIL;
  528. int localRet = copyAndReturn(string(localCand), local, localSize);
  529. if (localRet < 0)
  530. return localRet;
  531. int remoteRet = copyAndReturn(string(remoteCand), remote, remoteSize);
  532. if (remoteRet < 0)
  533. return remoteRet;
  534. return std::max(localRet, remoteRet);
  535. });
  536. }
  537. int rtcGetDataChannelStream(int dc) {
  538. return WRAP({
  539. auto dataChannel = getDataChannel(dc);
  540. return int(dataChannel->id());
  541. });
  542. }
  543. int rtcGetDataChannelLabel(int dc, char *buffer, int size) {
  544. return WRAP({
  545. auto dataChannel = getDataChannel(dc);
  546. return copyAndReturn(dataChannel->label(), buffer, size);
  547. });
  548. }
  549. int rtcGetDataChannelProtocol(int dc, char *buffer, int size) {
  550. return WRAP({
  551. auto dataChannel = getDataChannel(dc);
  552. return copyAndReturn(dataChannel->protocol(), buffer, size);
  553. });
  554. }
  555. int rtcGetDataChannelReliability(int dc, rtcReliability *reliability) {
  556. return WRAP({
  557. auto dataChannel = getDataChannel(dc);
  558. if (!reliability)
  559. throw std::invalid_argument("Unexpected null pointer for reliability");
  560. Reliability dcr = dataChannel->reliability();
  561. std::memset(reliability, 0, sizeof(*reliability));
  562. reliability->unordered = dcr.unordered;
  563. if (dcr.type == Reliability::Type::Timed) {
  564. reliability->unreliable = true;
  565. reliability->maxPacketLifeTime = unsigned(std::get<milliseconds>(dcr.rexmit).count());
  566. } else if (dcr.type == Reliability::Type::Rexmit) {
  567. reliability->unreliable = true;
  568. reliability->maxRetransmits = unsigned(std::get<int>(dcr.rexmit));
  569. } else {
  570. reliability->unreliable = false;
  571. }
  572. return RTC_ERR_SUCCESS;
  573. });
  574. }
  575. int rtcSetOpenCallback(int id, rtcOpenCallbackFunc cb) {
  576. return WRAP({
  577. auto channel = getChannel(id);
  578. if (cb)
  579. channel->onOpen([id, cb]() {
  580. if (auto ptr = getUserPointer(id))
  581. cb(id, *ptr);
  582. });
  583. else
  584. channel->onOpen(nullptr);
  585. });
  586. }
  587. int rtcSetClosedCallback(int id, rtcClosedCallbackFunc cb) {
  588. return WRAP({
  589. auto channel = getChannel(id);
  590. if (cb)
  591. channel->onClosed([id, cb]() {
  592. if (auto ptr = getUserPointer(id))
  593. cb(id, *ptr);
  594. });
  595. else
  596. channel->onClosed(nullptr);
  597. });
  598. }
  599. int rtcSetErrorCallback(int id, rtcErrorCallbackFunc cb) {
  600. return WRAP({
  601. auto channel = getChannel(id);
  602. if (cb)
  603. channel->onError([id, cb](string error) {
  604. if (auto ptr = getUserPointer(id))
  605. cb(id, error.c_str(), *ptr);
  606. });
  607. else
  608. channel->onError(nullptr);
  609. });
  610. }
  611. int rtcSetMessageCallback(int id, rtcMessageCallbackFunc cb) {
  612. return WRAP({
  613. auto channel = getChannel(id);
  614. if (cb)
  615. channel->onMessage(
  616. [id, cb](binary b) {
  617. if (auto ptr = getUserPointer(id))
  618. cb(id, reinterpret_cast<const char *>(b.data()), int(b.size()), *ptr);
  619. },
  620. [id, cb](string s) {
  621. if (auto ptr = getUserPointer(id))
  622. cb(id, s.c_str(), -int(s.size() + 1), *ptr);
  623. });
  624. else
  625. channel->onMessage(nullptr);
  626. });
  627. }
  628. int rtcSendMessage(int id, const char *data, int size) {
  629. return WRAP({
  630. auto channel = getChannel(id);
  631. if (!data && size != 0)
  632. throw std::invalid_argument("Unexpected null pointer for data");
  633. if (size >= 0) {
  634. auto b = reinterpret_cast<const byte *>(data);
  635. channel->send(binary(b, b + size));
  636. return size;
  637. } else {
  638. string str(data);
  639. int len = int(str.size());
  640. channel->send(std::move(str));
  641. return len;
  642. }
  643. });
  644. }
  645. int rtcGetBufferedAmount(int id) {
  646. return WRAP({
  647. auto channel = getChannel(id);
  648. return int(channel->bufferedAmount());
  649. });
  650. }
  651. int rtcSetBufferedAmountLowThreshold(int id, int amount) {
  652. return WRAP({
  653. auto channel = getChannel(id);
  654. channel->setBufferedAmountLowThreshold(size_t(amount));
  655. });
  656. }
  657. int rtcSetBufferedAmountLowCallback(int id, rtcBufferedAmountLowCallbackFunc cb) {
  658. return WRAP({
  659. auto channel = getChannel(id);
  660. if (cb)
  661. channel->onBufferedAmountLow([id, cb]() {
  662. if (auto ptr = getUserPointer(id))
  663. cb(id, *ptr);
  664. });
  665. else
  666. channel->onBufferedAmountLow(nullptr);
  667. });
  668. }
  669. int rtcGetAvailableAmount(int id) {
  670. return WRAP({ return int(getChannel(id)->availableAmount()); });
  671. }
  672. int rtcSetAvailableCallback(int id, rtcAvailableCallbackFunc cb) {
  673. return WRAP({
  674. auto channel = getChannel(id);
  675. if (cb)
  676. channel->onAvailable([id, cb]() {
  677. if (auto ptr = getUserPointer(id))
  678. cb(id, *ptr);
  679. });
  680. else
  681. channel->onAvailable(nullptr);
  682. });
  683. }
  684. int rtcReceiveMessage(int id, char *buffer, int *size) {
  685. return WRAP({
  686. auto channel = getChannel(id);
  687. if (!size)
  688. throw std::invalid_argument("Unexpected null pointer for size");
  689. *size = std::abs(*size);
  690. auto message = channel->peek();
  691. if (!message)
  692. return RTC_ERR_NOT_AVAIL;
  693. return std::visit( //
  694. overloaded{
  695. [&](binary b) {
  696. int ret = copyAndReturn(std::move(b), buffer, *size);
  697. if (ret >= 0) {
  698. channel->receive(); // discard
  699. *size = ret;
  700. return RTC_ERR_SUCCESS;
  701. } else {
  702. *size = int(b.size());
  703. return ret;
  704. }
  705. },
  706. [&](string s) {
  707. int ret = copyAndReturn(std::move(s), buffer, *size);
  708. if (ret >= 0) {
  709. channel->receive(); // discard
  710. *size = -ret;
  711. return RTC_ERR_SUCCESS;
  712. } else {
  713. *size = -int(s.size() + 1);
  714. return ret;
  715. }
  716. },
  717. },
  718. *message);
  719. });
  720. }
  721. void rtcPreload() { rtc::Preload(); }
  722. void rtcCleanup() { rtc::Cleanup(); }