capi.cpp 23 KB

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