2
0

capi.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  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 "rtc.h"
  19. #include "rtc.hpp"
  20. #include "impl/internals.hpp"
  21. #include <chrono>
  22. #include <exception>
  23. #include <mutex>
  24. #include <type_traits>
  25. #include <unordered_map>
  26. #include <utility>
  27. using namespace rtc;
  28. using std::chrono::milliseconds;
  29. namespace {
  30. std::unordered_map<int, shared_ptr<PeerConnection>> peerConnectionMap;
  31. std::unordered_map<int, shared_ptr<DataChannel>> dataChannelMap;
  32. std::unordered_map<int, shared_ptr<Track>> trackMap;
  33. #if RTC_ENABLE_MEDIA
  34. std::unordered_map<int, shared_ptr<MediaChainableHandler>> rtcpChainableHandlerMap;
  35. std::unordered_map<int, shared_ptr<RtcpSrReporter>> rtcpSrReporterMap;
  36. std::unordered_map<int, shared_ptr<RtpPacketizationConfig>> rtpConfigMap;
  37. #endif
  38. #if RTC_ENABLE_WEBSOCKET
  39. std::unordered_map<int, shared_ptr<WebSocket>> webSocketMap;
  40. #endif
  41. std::unordered_map<int, void *> userPointerMap;
  42. std::mutex mutex;
  43. int lastId = 0;
  44. optional<void *> getUserPointer(int id) {
  45. std::lock_guard lock(mutex);
  46. auto it = userPointerMap.find(id);
  47. return it != userPointerMap.end() ? std::make_optional(it->second) : nullopt;
  48. }
  49. void setUserPointer(int i, void *ptr) {
  50. std::lock_guard lock(mutex);
  51. userPointerMap[i] = ptr;
  52. }
  53. shared_ptr<PeerConnection> getPeerConnection(int id) {
  54. std::lock_guard lock(mutex);
  55. if (auto it = peerConnectionMap.find(id); it != peerConnectionMap.end())
  56. return it->second;
  57. else
  58. throw std::invalid_argument("PeerConnection ID does not exist");
  59. }
  60. shared_ptr<DataChannel> getDataChannel(int id) {
  61. std::lock_guard lock(mutex);
  62. if (auto it = dataChannelMap.find(id); it != dataChannelMap.end())
  63. return it->second;
  64. else
  65. throw std::invalid_argument("DataChannel ID does not exist");
  66. }
  67. shared_ptr<Track> getTrack(int id) {
  68. std::lock_guard lock(mutex);
  69. if (auto it = trackMap.find(id); it != trackMap.end())
  70. return it->second;
  71. else
  72. throw std::invalid_argument("Track ID does not exist");
  73. }
  74. int emplacePeerConnection(shared_ptr<PeerConnection> ptr) {
  75. std::lock_guard lock(mutex);
  76. int pc = ++lastId;
  77. peerConnectionMap.emplace(std::make_pair(pc, ptr));
  78. userPointerMap.emplace(std::make_pair(pc, nullptr));
  79. return pc;
  80. }
  81. int emplaceDataChannel(shared_ptr<DataChannel> ptr) {
  82. std::lock_guard lock(mutex);
  83. int dc = ++lastId;
  84. dataChannelMap.emplace(std::make_pair(dc, ptr));
  85. userPointerMap.emplace(std::make_pair(dc, nullptr));
  86. return dc;
  87. }
  88. int emplaceTrack(shared_ptr<Track> ptr) {
  89. std::lock_guard lock(mutex);
  90. int tr = ++lastId;
  91. trackMap.emplace(std::make_pair(tr, ptr));
  92. userPointerMap.emplace(std::make_pair(tr, nullptr));
  93. return tr;
  94. }
  95. void erasePeerConnection(int pc) {
  96. std::lock_guard lock(mutex);
  97. if (peerConnectionMap.erase(pc) == 0)
  98. throw std::invalid_argument("Peer Connection ID does not exist");
  99. userPointerMap.erase(pc);
  100. }
  101. void eraseDataChannel(int dc) {
  102. std::lock_guard lock(mutex);
  103. if (dataChannelMap.erase(dc) == 0)
  104. throw std::invalid_argument("Data Channel ID does not exist");
  105. userPointerMap.erase(dc);
  106. }
  107. void eraseTrack(int tr) {
  108. std::lock_guard lock(mutex);
  109. if (trackMap.erase(tr) == 0)
  110. throw std::invalid_argument("Track ID does not exist");
  111. #if RTC_ENABLE_MEDIA
  112. rtcpSrReporterMap.erase(tr);
  113. rtcpChainableHandlerMap.erase(tr);
  114. rtpConfigMap.erase(tr);
  115. #endif
  116. userPointerMap.erase(tr);
  117. }
  118. #if RTC_ENABLE_MEDIA
  119. shared_ptr<RtcpSrReporter> getRtcpSrReporter(int id) {
  120. std::lock_guard lock(mutex);
  121. if (auto it = rtcpSrReporterMap.find(id); it != rtcpSrReporterMap.end()) {
  122. return it->second;
  123. } else {
  124. throw std::invalid_argument("RTCP SR reporter ID does not exist");
  125. }
  126. }
  127. void emplaceRtcpSrReporter(shared_ptr<RtcpSrReporter> ptr, int tr) {
  128. std::lock_guard lock(mutex);
  129. rtcpSrReporterMap.emplace(std::make_pair(tr, ptr));
  130. }
  131. shared_ptr<MediaChainableHandler> getMediaChainableHandler(int id) {
  132. std::lock_guard lock(mutex);
  133. if (auto it = rtcpChainableHandlerMap.find(id); it != rtcpChainableHandlerMap.end()) {
  134. return it->second;
  135. } else {
  136. throw std::invalid_argument("RTCP chainable handler ID does not exist");
  137. }
  138. }
  139. void emplaceMediaChainableHandler(shared_ptr<MediaChainableHandler> ptr, int tr) {
  140. std::lock_guard lock(mutex);
  141. rtcpChainableHandlerMap.emplace(std::make_pair(tr, ptr));
  142. }
  143. shared_ptr<RtpPacketizationConfig> getRtpConfig(int id) {
  144. std::lock_guard lock(mutex);
  145. if (auto it = rtpConfigMap.find(id); it != rtpConfigMap.end()) {
  146. return it->second;
  147. } else {
  148. throw std::invalid_argument("RTP configuration ID does not exist");
  149. }
  150. }
  151. void emplaceRtpConfig(shared_ptr<RtpPacketizationConfig> ptr, int tr) {
  152. std::lock_guard lock(mutex);
  153. rtpConfigMap.emplace(std::make_pair(tr, ptr));
  154. }
  155. shared_ptr<RtpPacketizationConfig>
  156. createRtpPacketizationConfig(const rtcPacketizationHandlerInit *init) {
  157. if (!init)
  158. throw std::invalid_argument("Unexpected null pointer for packetization handler init");
  159. if (!init->cname)
  160. throw std::invalid_argument("Unexpected null pointer for cname");
  161. return std::make_shared<RtpPacketizationConfig>(init->ssrc, init->cname, init->payloadType,
  162. init->clockRate, init->sequenceNumber,
  163. init->timestamp);
  164. }
  165. #endif // RTC_ENABLE_MEDIA
  166. #if RTC_ENABLE_WEBSOCKET
  167. shared_ptr<WebSocket> getWebSocket(int id) {
  168. std::lock_guard lock(mutex);
  169. if (auto it = webSocketMap.find(id); it != webSocketMap.end())
  170. return it->second;
  171. else
  172. throw std::invalid_argument("WebSocket ID does not exist");
  173. }
  174. int emplaceWebSocket(shared_ptr<WebSocket> ptr) {
  175. std::lock_guard lock(mutex);
  176. int ws = ++lastId;
  177. webSocketMap.emplace(std::make_pair(ws, ptr));
  178. userPointerMap.emplace(std::make_pair(ws, nullptr));
  179. return ws;
  180. }
  181. void eraseWebSocket(int ws) {
  182. std::lock_guard lock(mutex);
  183. if (webSocketMap.erase(ws) == 0)
  184. throw std::invalid_argument("WebSocket ID does not exist");
  185. userPointerMap.erase(ws);
  186. }
  187. #endif
  188. shared_ptr<Channel> getChannel(int id) {
  189. std::lock_guard lock(mutex);
  190. if (auto it = dataChannelMap.find(id); it != dataChannelMap.end())
  191. return it->second;
  192. if (auto it = trackMap.find(id); it != trackMap.end())
  193. return it->second;
  194. #if RTC_ENABLE_WEBSOCKET
  195. if (auto it = webSocketMap.find(id); it != webSocketMap.end())
  196. return it->second;
  197. #endif
  198. throw std::invalid_argument("DataChannel, Track, or WebSocket ID does not exist");
  199. }
  200. template <typename F> int wrap(F func) {
  201. try {
  202. return int(func());
  203. } catch (const std::invalid_argument &e) {
  204. PLOG_ERROR << e.what();
  205. return RTC_ERR_INVALID;
  206. } catch (const std::exception &e) {
  207. PLOG_ERROR << e.what();
  208. return RTC_ERR_FAILURE;
  209. }
  210. }
  211. int copyAndReturn(string s, char *buffer, int size) {
  212. if (!buffer)
  213. return int(s.size() + 1);
  214. if (size < int(s.size()))
  215. return RTC_ERR_TOO_SMALL;
  216. std::copy(s.begin(), s.end(), buffer);
  217. buffer[s.size()] = '\0';
  218. return int(s.size() + 1);
  219. }
  220. int copyAndReturn(binary b, char *buffer, int size) {
  221. if (!buffer)
  222. return int(b.size());
  223. if (size < int(b.size()))
  224. return RTC_ERR_TOO_SMALL;
  225. auto data = reinterpret_cast<const char *>(b.data());
  226. std::copy(data, data + b.size(), buffer);
  227. buffer[b.size()] = '\0';
  228. return int(b.size());
  229. }
  230. template<typename T>
  231. int copyAndReturn(std::vector<T> b, T *buffer, int size) {
  232. if (!buffer)
  233. return int(b.size());
  234. if (size < int(b.size()))
  235. return RTC_ERR_TOO_SMALL;
  236. memcpy(buffer, b.data(), size * sizeof(*buffer));
  237. return int(b.size());
  238. }
  239. string lowercased(string str) {
  240. std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { return std::tolower(c); });
  241. return str;
  242. }
  243. } // namespace
  244. void rtcInitLogger(rtcLogLevel level, rtcLogCallbackFunc cb) {
  245. LogCallback callback = nullptr;
  246. if (cb)
  247. callback = [cb](LogLevel level, string message) {
  248. cb(static_cast<rtcLogLevel>(level), message.c_str());
  249. };
  250. InitLogger(static_cast<LogLevel>(level), callback);
  251. }
  252. void rtcSetUserPointer(int i, void *ptr) { setUserPointer(i, ptr); }
  253. void *rtcGetUserPointer(int i) { return getUserPointer(i).value_or(nullptr); }
  254. int rtcCreatePeerConnection(const rtcConfiguration *config) {
  255. return wrap([config] {
  256. Configuration c;
  257. for (int i = 0; i < config->iceServersCount; ++i)
  258. c.iceServers.emplace_back(string(config->iceServers[i]));
  259. if (config->bindAddress)
  260. c.bindAddress = string(config->bindAddress);
  261. if (config->portRangeBegin > 0 || config->portRangeEnd > 0) {
  262. c.portRangeBegin = config->portRangeBegin;
  263. c.portRangeEnd = config->portRangeEnd;
  264. }
  265. c.certificateType = static_cast<CertificateType>(config->certificateType);
  266. c.enableIceTcp = config->enableIceTcp;
  267. c.disableAutoNegotiation = config->disableAutoNegotiation;
  268. if (config->mtu > 0)
  269. c.mtu = size_t(config->mtu);
  270. if (config->maxMessageSize)
  271. c.maxMessageSize = size_t(config->maxMessageSize);
  272. return emplacePeerConnection(std::make_shared<PeerConnection>(c));
  273. });
  274. }
  275. int rtcDeletePeerConnection(int pc) {
  276. return wrap([pc] {
  277. auto peerConnection = getPeerConnection(pc);
  278. peerConnection->onDataChannel(nullptr);
  279. peerConnection->onTrack(nullptr);
  280. peerConnection->onLocalDescription(nullptr);
  281. peerConnection->onLocalCandidate(nullptr);
  282. peerConnection->onStateChange(nullptr);
  283. peerConnection->onGatheringStateChange(nullptr);
  284. erasePeerConnection(pc);
  285. return RTC_ERR_SUCCESS;
  286. });
  287. }
  288. int rtcCreateDataChannel(int pc, const char *label) {
  289. return rtcCreateDataChannelEx(pc, label, nullptr);
  290. }
  291. int rtcCreateDataChannelEx(int pc, const char *label, const rtcDataChannelInit *init) {
  292. return wrap([&] {
  293. DataChannelInit dci = {};
  294. if (init) {
  295. auto *reliability = &init->reliability;
  296. dci.reliability.unordered = reliability->unordered;
  297. if (reliability->unreliable) {
  298. if (reliability->maxPacketLifeTime > 0) {
  299. dci.reliability.type = Reliability::Type::Timed;
  300. dci.reliability.rexmit = milliseconds(reliability->maxPacketLifeTime);
  301. } else {
  302. dci.reliability.type = Reliability::Type::Rexmit;
  303. dci.reliability.rexmit = reliability->maxRetransmits;
  304. }
  305. } else {
  306. dci.reliability.type = Reliability::Type::Reliable;
  307. }
  308. dci.negotiated = init->negotiated;
  309. dci.id = init->manualStream ? std::make_optional(init->stream) : nullopt;
  310. dci.protocol = init->protocol ? init->protocol : "";
  311. }
  312. auto peerConnection = getPeerConnection(pc);
  313. int dc = emplaceDataChannel(
  314. peerConnection->createDataChannel(string(label ? label : ""), std::move(dci)));
  315. if (auto ptr = getUserPointer(pc))
  316. rtcSetUserPointer(dc, *ptr);
  317. return dc;
  318. });
  319. }
  320. int rtcIsDataChannelOpen(int dc) {
  321. return wrap([dc] {
  322. return getDataChannel(dc)->isOpen() ? RTC_ERR_SUCCESS : RTC_ERR_FAILURE;
  323. });
  324. }
  325. int rtcDeleteDataChannel(int dc) {
  326. return wrap([dc] {
  327. auto dataChannel = getDataChannel(dc);
  328. dataChannel->onOpen(nullptr);
  329. dataChannel->onClosed(nullptr);
  330. dataChannel->onError(nullptr);
  331. dataChannel->onMessage(nullptr);
  332. dataChannel->onBufferedAmountLow(nullptr);
  333. dataChannel->onAvailable(nullptr);
  334. eraseDataChannel(dc);
  335. return RTC_ERR_SUCCESS;
  336. });
  337. }
  338. int rtcIsDataChannelOpen(int dc) {
  339. return wrap([dc] {
  340. return getDataChannel(dc)->isOpen() ? RTC_ERR_SUCCESS : RTC_ERR_FAILURE;
  341. });
  342. }
  343. #if RTC_ENABLE_MEDIA
  344. void setSSRC(Description::Media *description, uint32_t ssrc, const char *_name, const char *_msid, const char *_trackID) {
  345. optional<string> name = nullopt;
  346. if (_name) {
  347. name = string(_name);
  348. }
  349. optional<string> msid = nullopt;
  350. if (_msid) {
  351. msid = string(_msid);
  352. }
  353. optional<string> trackID = nullopt;
  354. if (_trackID) {
  355. trackID = string(_trackID);
  356. }
  357. description->addSSRC(ssrc, name, msid, trackID);
  358. }
  359. int rtcAddTrack(int pc, const char *mediaDescriptionSdp) {
  360. return wrap([&] {
  361. if (!mediaDescriptionSdp)
  362. throw std::invalid_argument("Unexpected null pointer for track media description");
  363. auto peerConnection = getPeerConnection(pc);
  364. Description::Media media{string(mediaDescriptionSdp)};
  365. int tr = emplaceTrack(peerConnection->addTrack(std::move(media)));
  366. if (auto ptr = getUserPointer(pc))
  367. rtcSetUserPointer(tr, *ptr);
  368. return tr;
  369. });
  370. }
  371. int rtcAddTrackEx(int pc, const rtcTrackInit *init) {
  372. return wrap([&] {
  373. auto peerConnection = getPeerConnection(pc);
  374. if (!init)
  375. throw std::invalid_argument("Unexpected null pointer for track init");
  376. auto direction = static_cast<Description::Direction>(init->direction);
  377. string mid;
  378. if (init->mid) {
  379. mid = string(init->mid);
  380. } else {
  381. switch (init->codec) {
  382. case RTC_CODEC_H264:
  383. case RTC_CODEC_VP8:
  384. case RTC_CODEC_VP9:
  385. mid = "video";
  386. break;
  387. case RTC_CODEC_OPUS:
  388. mid = "audio";
  389. break;
  390. default:
  391. mid = "video";
  392. break;
  393. }
  394. }
  395. optional<Description::Media> optDescription = nullopt;
  396. switch (init->codec) {
  397. case RTC_CODEC_H264:
  398. case RTC_CODEC_VP8:
  399. case RTC_CODEC_VP9: {
  400. auto desc = Description::Video(mid, direction);
  401. switch (init->codec) {
  402. case RTC_CODEC_H264:
  403. desc.addH264Codec(init->payloadType);
  404. break;
  405. case RTC_CODEC_VP8:
  406. desc.addVP8Codec(init->payloadType);
  407. break;
  408. case RTC_CODEC_VP9:
  409. desc.addVP8Codec(init->payloadType);
  410. break;
  411. default:
  412. break;
  413. }
  414. optDescription = desc;
  415. break;
  416. }
  417. case RTC_CODEC_OPUS: {
  418. auto desc = Description::Audio(mid, direction);
  419. switch (init->codec) {
  420. case RTC_CODEC_OPUS:
  421. desc.addOpusCodec(init->payloadType);
  422. break;
  423. default:
  424. break;
  425. }
  426. optDescription = desc;
  427. break;
  428. }
  429. default:
  430. break;
  431. }
  432. if (!optDescription)
  433. throw std::invalid_argument("Unexpected codec");
  434. auto desc = std::move(*optDescription);
  435. desc.addSSRC(init->ssrc, init->name ? std::make_optional(string(init->name)) : nullopt,
  436. init->msid ? std::make_optional(string(init->msid)) : nullopt,
  437. init->trackId ? std::make_optional(string(init->trackId)) : nullopt);
  438. int tr = emplaceTrack(peerConnection->addTrack(std::move(desc)));
  439. if (auto ptr = getUserPointer(pc))
  440. rtcSetUserPointer(tr, *ptr);
  441. return tr;
  442. });
  443. }
  444. int rtcDeleteTrack(int tr) {
  445. return wrap([&] {
  446. auto track = getTrack(tr);
  447. track->onOpen(nullptr);
  448. track->onClosed(nullptr);
  449. track->onError(nullptr);
  450. track->onMessage(nullptr);
  451. track->onBufferedAmountLow(nullptr);
  452. track->onAvailable(nullptr);
  453. eraseTrack(tr);
  454. return RTC_ERR_SUCCESS;
  455. });
  456. }
  457. int rtcGetTrackDescription(int tr, char *buffer, int size) {
  458. return wrap([&] {
  459. auto track = getTrack(tr);
  460. return copyAndReturn(track->description(), buffer, size);
  461. });
  462. }
  463. #if RTC_ENABLE_MEDIA
  464. void setSSRC(Description::Media *description, uint32_t ssrc, const char *_name, const char *_msid, const char *_trackID) {
  465. optional<string> name = nullopt;
  466. if (_name) {
  467. name = string(_name);
  468. }
  469. optional<string> msid = nullopt;
  470. if (_msid) {
  471. msid = string(_msid);
  472. }
  473. optional<string> trackID = nullopt;
  474. if (_trackID) {
  475. trackID = string(_trackID);
  476. }
  477. description->addSSRC(ssrc, name, msid, trackID);
  478. }
  479. int rtcSetH264PacketizationHandler(int tr, const rtcPacketizationHandlerInit *init) {
  480. return wrap([&] {
  481. auto track = getTrack(tr);
  482. // create RTP configuration
  483. auto rtpConfig = createRtpPacketizationConfig(init);
  484. // create packetizer
  485. auto maxFragmentSize = init && init->maxFragmentSize ? init->maxFragmentSize
  486. : RTC_DEFAULT_MAXIMUM_FRAGMENT_SIZE;
  487. auto packetizer = std::make_shared<H264RtpPacketizer>(rtpConfig, maxFragmentSize);
  488. // create H264 handler
  489. auto h264Handler = std::make_shared<H264PacketizationHandler>(packetizer);
  490. emplaceMediaChainableHandler(h264Handler, tr);
  491. emplaceRtpConfig(rtpConfig, tr);
  492. // set handler
  493. track->setMediaHandler(h264Handler);
  494. return RTC_ERR_SUCCESS;
  495. });
  496. }
  497. int rtcSetOpusPacketizationHandler(int tr, const rtcPacketizationHandlerInit *init) {
  498. return wrap([&] {
  499. auto track = getTrack(tr);
  500. // create RTP configuration
  501. auto rtpConfig = createRtpPacketizationConfig(init);
  502. // create packetizer
  503. auto packetizer = std::make_shared<OpusRtpPacketizer>(rtpConfig);
  504. // create Opus handler
  505. auto opusHandler = std::make_shared<OpusPacketizationHandler>(packetizer);
  506. emplaceMediaChainableHandler(opusHandler, tr);
  507. emplaceRtpConfig(rtpConfig, tr);
  508. // set handler
  509. track->setMediaHandler(opusHandler);
  510. return RTC_ERR_SUCCESS;
  511. });
  512. }
  513. int rtcChainRtcpSrReporter(int tr) {
  514. return wrap([tr] {
  515. auto config = getRtpConfig(tr);
  516. auto reporter = std::make_shared<RtcpSrReporter>(config);
  517. emplaceRtcpSrReporter(reporter, tr);
  518. auto chainableHandler = getMediaChainableHandler(tr);
  519. chainableHandler->addToChain(reporter);
  520. return RTC_ERR_SUCCESS;
  521. });
  522. }
  523. int rtcChainRtcpNackResponder(int tr, unsigned int maxStoredPacketsCount) {
  524. return wrap([tr, maxStoredPacketsCount] {
  525. auto responder = std::make_shared<RtcpNackResponder>(maxStoredPacketsCount);
  526. auto chainableHandler = getMediaChainableHandler(tr);
  527. chainableHandler->addToChain(responder);
  528. return RTC_ERR_SUCCESS;
  529. });
  530. }
  531. int rtcSetRtpConfigurationStartTime(int id, const rtcStartTime *startTime) {
  532. return wrap([&] {
  533. auto config = getRtpConfig(id);
  534. auto epoch = startTime->since1970 ? RtpPacketizationConfig::EpochStart::T1970
  535. : RtpPacketizationConfig::EpochStart::T1900;
  536. config->setStartTime(startTime->seconds, epoch, startTime->timestamp);
  537. return RTC_ERR_SUCCESS;
  538. });
  539. }
  540. int rtcStartRtcpSenderReporterRecording(int id) {
  541. return wrap([id] {
  542. auto sender = getRtcpSrReporter(id);
  543. sender->startRecording();
  544. return RTC_ERR_SUCCESS;
  545. });
  546. }
  547. int rtcTransformSecondsToTimestamp(int id, double seconds, uint32_t *timestamp) {
  548. return wrap([&] {
  549. auto config = getRtpConfig(id);
  550. *timestamp = config->secondsToTimestamp(seconds);
  551. return RTC_ERR_SUCCESS;
  552. });
  553. }
  554. int rtcTransformTimestampToSeconds(int id, uint32_t timestamp, double *seconds) {
  555. return wrap([&] {
  556. auto config = getRtpConfig(id);
  557. *seconds = config->timestampToSeconds(timestamp);
  558. return RTC_ERR_SUCCESS;
  559. });
  560. }
  561. int rtcGetCurrentTrackTimestamp(int id, uint32_t *timestamp) {
  562. return wrap([&] {
  563. auto config = getRtpConfig(id);
  564. *timestamp = config->timestamp;
  565. return RTC_ERR_SUCCESS;
  566. });
  567. }
  568. int rtcGetTrackStartTimestamp(int id, uint32_t *timestamp) {
  569. return wrap([&] {
  570. auto config = getRtpConfig(id);
  571. *timestamp = config->startTimestamp;
  572. return RTC_ERR_SUCCESS;
  573. });
  574. }
  575. int rtcSetTrackRtpTimestamp(int id, uint32_t timestamp) {
  576. return wrap([&] {
  577. auto config = getRtpConfig(id);
  578. config->timestamp = timestamp;
  579. return RTC_ERR_SUCCESS;
  580. });
  581. }
  582. int rtcGetPreviousTrackSenderReportTimestamp(int id, uint32_t *timestamp) {
  583. return wrap([&] {
  584. auto sender = getRtcpSrReporter(id);
  585. *timestamp = sender->previousReportedTimestamp;
  586. return RTC_ERR_SUCCESS;
  587. });
  588. }
  589. int rtcSetNeedsToSendRtcpSr(int id) {
  590. return wrap([id] {
  591. auto sender = getRtcpSrReporter(id);
  592. sender->setNeedsToReport();
  593. return RTC_ERR_SUCCESS;
  594. });
  595. }
  596. int rtcGetTrackPayloadTypesForCodec(int tr, const char * ccodec, int * buffer, int size) {
  597. return wrap([&] {
  598. auto track = getTrack(tr);
  599. auto codec = lowercased(string(ccodec));
  600. auto description = track->description();
  601. std::vector<int> payloadTypes{};
  602. payloadTypes.reserve(std::max(size, 0));
  603. for (auto it = description.beginMaps(); it != description.endMaps(); it++) {
  604. auto element = *it;
  605. if (lowercased(element.second.format) == codec) {
  606. payloadTypes.push_back(element.first);
  607. }
  608. }
  609. return copyAndReturn(payloadTypes, buffer, size);
  610. });
  611. }
  612. #endif // RTC_ENABLE_MEDIA
  613. #if RTC_ENABLE_WEBSOCKET
  614. int rtcCreateWebSocket(const char *url) {
  615. return wrap([&] {
  616. auto ws = std::make_shared<WebSocket>();
  617. ws->open(url);
  618. return emplaceWebSocket(ws);
  619. });
  620. }
  621. int rtcCreateWebSocketEx(const char *url, const rtcWsConfiguration *config) {
  622. return wrap([&] {
  623. WebSocket::Configuration c;
  624. c.disableTlsVerification = config->disableTlsVerification;
  625. auto ws = std::make_shared<WebSocket>(c);
  626. ws->open(url);
  627. return emplaceWebSocket(ws);
  628. });
  629. }
  630. int rtcDeleteWebsocket(int ws) {
  631. return wrap([&] {
  632. auto webSocket = getWebSocket(ws);
  633. webSocket->onOpen(nullptr);
  634. webSocket->onClosed(nullptr);
  635. webSocket->onError(nullptr);
  636. webSocket->onMessage(nullptr);
  637. webSocket->onBufferedAmountLow(nullptr);
  638. webSocket->onAvailable(nullptr);
  639. eraseWebSocket(ws);
  640. return RTC_ERR_SUCCESS;
  641. });
  642. }
  643. #endif
  644. int rtcSetLocalDescriptionCallback(int pc, rtcDescriptionCallbackFunc cb) {
  645. return wrap([&] {
  646. auto peerConnection = getPeerConnection(pc);
  647. if (cb)
  648. peerConnection->onLocalDescription([pc, cb](Description desc) {
  649. if (auto ptr = getUserPointer(pc))
  650. cb(pc, string(desc).c_str(), desc.typeString().c_str(), *ptr);
  651. });
  652. else
  653. peerConnection->onLocalDescription(nullptr);
  654. return RTC_ERR_SUCCESS;
  655. });
  656. }
  657. int rtcSetLocalCandidateCallback(int pc, rtcCandidateCallbackFunc cb) {
  658. return wrap([&] {
  659. auto peerConnection = getPeerConnection(pc);
  660. if (cb)
  661. peerConnection->onLocalCandidate([pc, cb](Candidate cand) {
  662. if (auto ptr = getUserPointer(pc))
  663. cb(pc, cand.candidate().c_str(), cand.mid().c_str(), *ptr);
  664. });
  665. else
  666. peerConnection->onLocalCandidate(nullptr);
  667. return RTC_ERR_SUCCESS;
  668. });
  669. }
  670. int rtcSetStateChangeCallback(int pc, rtcStateChangeCallbackFunc cb) {
  671. return wrap([&] {
  672. auto peerConnection = getPeerConnection(pc);
  673. if (cb)
  674. peerConnection->onStateChange([pc, cb](PeerConnection::State state) {
  675. if (auto ptr = getUserPointer(pc))
  676. cb(pc, static_cast<rtcState>(state), *ptr);
  677. });
  678. else
  679. peerConnection->onStateChange(nullptr);
  680. return RTC_ERR_SUCCESS;
  681. });
  682. }
  683. int rtcSetGatheringStateChangeCallback(int pc, rtcGatheringStateCallbackFunc cb) {
  684. return wrap([&] {
  685. auto peerConnection = getPeerConnection(pc);
  686. if (cb)
  687. peerConnection->onGatheringStateChange([pc, cb](PeerConnection::GatheringState state) {
  688. if (auto ptr = getUserPointer(pc))
  689. cb(pc, static_cast<rtcGatheringState>(state), *ptr);
  690. });
  691. else
  692. peerConnection->onGatheringStateChange(nullptr);
  693. return RTC_ERR_SUCCESS;
  694. });
  695. }
  696. int rtcSetSignalingStateChangeCallback(int pc, rtcSignalingStateCallbackFunc cb) {
  697. return wrap([&] {
  698. auto peerConnection = getPeerConnection(pc);
  699. if (cb)
  700. peerConnection->onSignalingStateChange([pc, cb](PeerConnection::SignalingState state) {
  701. if (auto ptr = getUserPointer(pc))
  702. cb(pc, static_cast<rtcSignalingState>(state), *ptr);
  703. });
  704. else
  705. peerConnection->onGatheringStateChange(nullptr);
  706. return RTC_ERR_SUCCESS;
  707. });
  708. }
  709. int rtcSetDataChannelCallback(int pc, rtcDataChannelCallbackFunc cb) {
  710. return wrap([&] {
  711. auto peerConnection = getPeerConnection(pc);
  712. if (cb)
  713. peerConnection->onDataChannel([pc, cb](shared_ptr<DataChannel> dataChannel) {
  714. int dc = emplaceDataChannel(dataChannel);
  715. if (auto ptr = getUserPointer(pc)) {
  716. rtcSetUserPointer(dc, *ptr);
  717. cb(pc, dc, *ptr);
  718. }
  719. });
  720. else
  721. peerConnection->onDataChannel(nullptr);
  722. return RTC_ERR_SUCCESS;
  723. });
  724. }
  725. int rtcSetTrackCallback(int pc, rtcTrackCallbackFunc cb) {
  726. return wrap([&] {
  727. auto peerConnection = getPeerConnection(pc);
  728. if (cb)
  729. peerConnection->onTrack([pc, cb](shared_ptr<Track> track) {
  730. int tr = emplaceTrack(track);
  731. if (auto ptr = getUserPointer(pc)) {
  732. rtcSetUserPointer(tr, *ptr);
  733. cb(pc, tr, *ptr);
  734. }
  735. });
  736. else
  737. peerConnection->onTrack(nullptr);
  738. return RTC_ERR_SUCCESS;
  739. });
  740. }
  741. int rtcSetLocalDescription(int pc, const char *type) {
  742. return wrap([&] {
  743. auto peerConnection = getPeerConnection(pc);
  744. peerConnection->setLocalDescription(type ? Description::stringToType(type)
  745. : Description::Type::Unspec);
  746. return RTC_ERR_SUCCESS;
  747. });
  748. }
  749. int rtcGetSsrcsForTrack(int tr, uint32_t * buffer, int bufferSize) {
  750. return wrap([&] {
  751. auto track = getTrack(tr);
  752. auto ssrcs = track->description().getSSRCs();
  753. return copyAndReturn(ssrcs, buffer, bufferSize);
  754. });
  755. }
  756. int rtcGetCNameForSsrc(int tr, uint32_t ssrc, char * cname, int cnameSize) {
  757. return wrap([&] {
  758. auto track = getTrack(tr);
  759. auto description = track->description();
  760. auto optCName = description.getCNameForSsrc(ssrc);
  761. if (optCName.has_value()) {
  762. return copyAndReturn(optCName.value(), cname, cnameSize);
  763. } else {
  764. return 0;
  765. }
  766. });
  767. }
  768. int rtcGetSsrcsForType(const char * mediaType, const char * sdp, uint32_t * buffer, int bufferSize) {
  769. return wrap([&] {
  770. auto type = lowercased(string(mediaType));
  771. auto oldSDP = string(sdp);
  772. auto description = Description(oldSDP, "unspec");
  773. auto mediaCount = description.mediaCount();
  774. for (auto i = 0; i < mediaCount; i++) {
  775. if (std::holds_alternative<Description::Media *>(description.media(i))) {
  776. auto media = std::get<Description::Media *>(description.media(i));
  777. auto currentMediaType = lowercased(media->type());
  778. if (currentMediaType == type) {
  779. auto ssrcs = media->getSSRCs();
  780. return copyAndReturn(ssrcs, buffer, bufferSize);
  781. }
  782. }
  783. }
  784. return 0;
  785. });
  786. }
  787. int rtcSetSsrcForType(const char * mediaType, const char * sdp, char * buffer, const int bufferSize,
  788. rtcSsrcForTypeInit * init) {
  789. return wrap([&] {
  790. auto type = lowercased(string(mediaType));
  791. auto prevSDP = string(sdp);
  792. auto description = Description(prevSDP, "unspec");
  793. auto mediaCount = description.mediaCount();
  794. for (auto i = 0; i < mediaCount; i++) {
  795. if (std::holds_alternative<Description::Media *>(description.media(i))) {
  796. auto media = std::get<Description::Media *>(description.media(i));
  797. auto currentMediaType = lowercased(media->type());
  798. if (currentMediaType == type) {
  799. setSSRC(media, init->ssrc, init->name, init->msid, init->trackId);
  800. break;
  801. }
  802. }
  803. }
  804. return copyAndReturn(string(description), buffer, bufferSize);
  805. });
  806. }
  807. int rtcSetRemoteDescription(int pc, const char *sdp, const char *type) {
  808. return wrap([&] {
  809. auto peerConnection = getPeerConnection(pc);
  810. if (!sdp)
  811. throw std::invalid_argument("Unexpected null pointer for remote description");
  812. peerConnection->setRemoteDescription({string(sdp), type ? string(type) : ""});
  813. return RTC_ERR_SUCCESS;
  814. });
  815. }
  816. int rtcAddRemoteCandidate(int pc, const char *cand, const char *mid) {
  817. return wrap([&] {
  818. auto peerConnection = getPeerConnection(pc);
  819. if (!cand)
  820. throw std::invalid_argument("Unexpected null pointer for remote candidate");
  821. peerConnection->addRemoteCandidate({string(cand), mid ? string(mid) : ""});
  822. return RTC_ERR_SUCCESS;
  823. });
  824. }
  825. int rtcGetLocalDescription(int pc, char *buffer, int size) {
  826. return wrap([&] {
  827. auto peerConnection = getPeerConnection(pc);
  828. if (auto desc = peerConnection->localDescription())
  829. return copyAndReturn(string(*desc), buffer, size);
  830. else
  831. return RTC_ERR_NOT_AVAIL;
  832. });
  833. }
  834. int rtcGetRemoteDescription(int pc, char *buffer, int size) {
  835. return wrap([&] {
  836. auto peerConnection = getPeerConnection(pc);
  837. if (auto desc = peerConnection->remoteDescription())
  838. return copyAndReturn(string(*desc), buffer, size);
  839. else
  840. return RTC_ERR_NOT_AVAIL;
  841. });
  842. }
  843. int rtcGetLocalDescriptionType(int pc, char *buffer, int size) {
  844. return wrap([&] {
  845. auto peerConnection = getPeerConnection(pc);
  846. if (auto desc = peerConnection->localDescription())
  847. return copyAndReturn(desc->typeString(), buffer, size);
  848. else
  849. return RTC_ERR_NOT_AVAIL;
  850. });
  851. }
  852. int rtcGetRemoteDescriptionType(int pc, char *buffer, int size) {
  853. return wrap([&] {
  854. auto peerConnection = getPeerConnection(pc);
  855. if (auto desc = peerConnection->remoteDescription())
  856. return copyAndReturn(desc->typeString(), buffer, size);
  857. else
  858. return RTC_ERR_NOT_AVAIL;
  859. });
  860. }
  861. int rtcGetLocalAddress(int pc, char *buffer, int size) {
  862. return wrap([&] {
  863. auto peerConnection = getPeerConnection(pc);
  864. if (auto addr = peerConnection->localAddress())
  865. return copyAndReturn(std::move(*addr), buffer, size);
  866. else
  867. return RTC_ERR_NOT_AVAIL;
  868. });
  869. }
  870. int rtcGetRemoteAddress(int pc, char *buffer, int size) {
  871. return wrap([&] {
  872. auto peerConnection = getPeerConnection(pc);
  873. if (auto addr = peerConnection->remoteAddress())
  874. return copyAndReturn(std::move(*addr), buffer, size);
  875. else
  876. return RTC_ERR_NOT_AVAIL;
  877. });
  878. }
  879. int rtcGetSelectedCandidatePair(int pc, char *local, int localSize, char *remote, int remoteSize) {
  880. return wrap([&] {
  881. auto peerConnection = getPeerConnection(pc);
  882. Candidate localCand;
  883. Candidate remoteCand;
  884. if (!peerConnection->getSelectedCandidatePair(&localCand, &remoteCand))
  885. return RTC_ERR_NOT_AVAIL;
  886. int localRet = copyAndReturn(string(localCand), local, localSize);
  887. if (localRet < 0)
  888. return localRet;
  889. int remoteRet = copyAndReturn(string(remoteCand), remote, remoteSize);
  890. if (remoteRet < 0)
  891. return remoteRet;
  892. return std::max(localRet, remoteRet);
  893. });
  894. }
  895. int rtcGetDataChannelStream(int dc) {
  896. return wrap([dc] {
  897. auto dataChannel = getDataChannel(dc);
  898. return int(dataChannel->id());
  899. });
  900. }
  901. int rtcGetDataChannelLabel(int dc, char *buffer, int size) {
  902. return wrap([&] {
  903. auto dataChannel = getDataChannel(dc);
  904. return copyAndReturn(dataChannel->label(), buffer, size);
  905. });
  906. }
  907. int rtcGetDataChannelProtocol(int dc, char *buffer, int size) {
  908. return wrap([&] {
  909. auto dataChannel = getDataChannel(dc);
  910. return copyAndReturn(dataChannel->protocol(), buffer, size);
  911. });
  912. }
  913. int rtcGetDataChannelReliability(int dc, rtcReliability *reliability) {
  914. return wrap([&] {
  915. auto dataChannel = getDataChannel(dc);
  916. if (!reliability)
  917. throw std::invalid_argument("Unexpected null pointer for reliability");
  918. Reliability dcr = dataChannel->reliability();
  919. std::memset(reliability, 0, sizeof(*reliability));
  920. reliability->unordered = dcr.unordered;
  921. if (dcr.type == Reliability::Type::Timed) {
  922. reliability->unreliable = true;
  923. reliability->maxPacketLifeTime = int(std::get<milliseconds>(dcr.rexmit).count());
  924. } else if (dcr.type == Reliability::Type::Rexmit) {
  925. reliability->unreliable = true;
  926. reliability->maxRetransmits = std::get<int>(dcr.rexmit);
  927. } else {
  928. reliability->unreliable = false;
  929. }
  930. return RTC_ERR_SUCCESS;
  931. });
  932. }
  933. int rtcSetOpenCallback(int id, rtcOpenCallbackFunc cb) {
  934. return wrap([&] {
  935. auto channel = getChannel(id);
  936. if (cb)
  937. channel->onOpen([id, cb]() {
  938. if (auto ptr = getUserPointer(id))
  939. cb(id, *ptr);
  940. });
  941. else
  942. channel->onOpen(nullptr);
  943. return RTC_ERR_SUCCESS;
  944. });
  945. }
  946. int rtcSetClosedCallback(int id, rtcClosedCallbackFunc cb) {
  947. return wrap([&] {
  948. auto channel = getChannel(id);
  949. if (cb)
  950. channel->onClosed([id, cb]() {
  951. if (auto ptr = getUserPointer(id))
  952. cb(id, *ptr);
  953. });
  954. else
  955. channel->onClosed(nullptr);
  956. return RTC_ERR_SUCCESS;
  957. });
  958. }
  959. int rtcSetErrorCallback(int id, rtcErrorCallbackFunc cb) {
  960. return wrap([&] {
  961. auto channel = getChannel(id);
  962. if (cb)
  963. channel->onError([id, cb](string error) {
  964. if (auto ptr = getUserPointer(id))
  965. cb(id, error.c_str(), *ptr);
  966. });
  967. else
  968. channel->onError(nullptr);
  969. return RTC_ERR_SUCCESS;
  970. });
  971. }
  972. int rtcSetMessageCallback(int id, rtcMessageCallbackFunc cb) {
  973. return wrap([&] {
  974. auto channel = getChannel(id);
  975. if (cb)
  976. channel->onMessage(
  977. [id, cb](binary b) {
  978. if (auto ptr = getUserPointer(id))
  979. cb(id, reinterpret_cast<const char *>(b.data()), int(b.size()), *ptr);
  980. },
  981. [id, cb](string s) {
  982. if (auto ptr = getUserPointer(id))
  983. cb(id, s.c_str(), -int(s.size() + 1), *ptr);
  984. });
  985. else
  986. channel->onMessage(nullptr);
  987. return RTC_ERR_SUCCESS;
  988. });
  989. }
  990. int rtcSendMessage(int id, const char *data, int size) {
  991. return wrap([&] {
  992. auto channel = getChannel(id);
  993. if (!data && size != 0)
  994. throw std::invalid_argument("Unexpected null pointer for data");
  995. if (size >= 0) {
  996. auto b = reinterpret_cast<const byte *>(data);
  997. channel->send(binary(b, b + size));
  998. return size;
  999. } else {
  1000. string str(data);
  1001. int len = int(str.size());
  1002. channel->send(std::move(str));
  1003. return len;
  1004. }
  1005. });
  1006. }
  1007. int rtcGetBufferedAmount(int id) {
  1008. return wrap([id] {
  1009. auto channel = getChannel(id);
  1010. return int(channel->bufferedAmount());
  1011. });
  1012. }
  1013. int rtcSetBufferedAmountLowThreshold(int id, int amount) {
  1014. return wrap([&] {
  1015. auto channel = getChannel(id);
  1016. channel->setBufferedAmountLowThreshold(size_t(amount));
  1017. return RTC_ERR_SUCCESS;
  1018. });
  1019. }
  1020. int rtcSetBufferedAmountLowCallback(int id, rtcBufferedAmountLowCallbackFunc cb) {
  1021. return wrap([&] {
  1022. auto channel = getChannel(id);
  1023. if (cb)
  1024. channel->onBufferedAmountLow([id, cb]() {
  1025. if (auto ptr = getUserPointer(id))
  1026. cb(id, *ptr);
  1027. });
  1028. else
  1029. channel->onBufferedAmountLow(nullptr);
  1030. return RTC_ERR_SUCCESS;
  1031. });
  1032. }
  1033. int rtcGetAvailableAmount(int id) {
  1034. return wrap([id] { return int(getChannel(id)->availableAmount()); });
  1035. }
  1036. int rtcSetAvailableCallback(int id, rtcAvailableCallbackFunc cb) {
  1037. return wrap([&] {
  1038. auto channel = getChannel(id);
  1039. if (cb)
  1040. channel->onAvailable([id, cb]() {
  1041. if (auto ptr = getUserPointer(id))
  1042. cb(id, *ptr);
  1043. });
  1044. else
  1045. channel->onAvailable(nullptr);
  1046. return RTC_ERR_SUCCESS;
  1047. });
  1048. }
  1049. int rtcReceiveMessage(int id, char *buffer, int *size) {
  1050. return wrap([&] {
  1051. auto channel = getChannel(id);
  1052. if (!size)
  1053. throw std::invalid_argument("Unexpected null pointer for size");
  1054. *size = std::abs(*size);
  1055. auto message = channel->peek();
  1056. if (!message)
  1057. return RTC_ERR_NOT_AVAIL;
  1058. return std::visit( //
  1059. overloaded{
  1060. [&](binary b) {
  1061. int ret = copyAndReturn(std::move(b), buffer, *size);
  1062. if (ret >= 0) {
  1063. channel->receive(); // discard
  1064. *size = ret;
  1065. return RTC_ERR_SUCCESS;
  1066. } else {
  1067. *size = int(b.size());
  1068. return ret;
  1069. }
  1070. },
  1071. [&](string s) {
  1072. int ret = copyAndReturn(std::move(s), buffer, *size);
  1073. if (ret >= 0) {
  1074. channel->receive(); // discard
  1075. *size = -ret;
  1076. return RTC_ERR_SUCCESS;
  1077. } else {
  1078. *size = -int(s.size() + 1);
  1079. return ret;
  1080. }
  1081. },
  1082. },
  1083. *message);
  1084. });
  1085. }
  1086. void rtcPreload() { rtc::Preload(); }
  1087. void rtcCleanup() { rtc::Cleanup(); }
  1088. int rtcSetSctpSettings(const rtcSctpSettings *settings) {
  1089. return wrap([&] {
  1090. SctpSettings s = {};
  1091. if (settings->recvBufferSize > 0)
  1092. s.recvBufferSize = size_t(settings->recvBufferSize);
  1093. if (settings->sendBufferSize > 0)
  1094. s.sendBufferSize = size_t(settings->sendBufferSize);
  1095. if (settings->maxChunksOnQueue > 0)
  1096. s.maxChunksOnQueue = size_t(settings->maxChunksOnQueue);
  1097. if (settings->initialCongestionWindow > 0)
  1098. s.initialCongestionWindow = size_t(settings->initialCongestionWindow);
  1099. if (settings->maxBurst > 0)
  1100. s.maxBurst = size_t(settings->maxBurst);
  1101. else if (settings->maxBurst < 0)
  1102. s.maxBurst = size_t(0); // setting to 0 disables, not setting chooses optimized default
  1103. if (settings->congestionControlModule >= 0)
  1104. s.congestionControlModule = unsigned(settings->congestionControlModule);
  1105. if (settings->delayedSackTimeMs > 0)
  1106. s.delayedSackTime = std::chrono::milliseconds(settings->delayedSackTimeMs);
  1107. else if (settings->delayedSackTimeMs < 0)
  1108. s.delayedSackTime = std::chrono::milliseconds(0);
  1109. if (settings->minRetransmitTimeoutMs > 0)
  1110. s.minRetransmitTimeout = std::chrono::milliseconds(settings->minRetransmitTimeoutMs);
  1111. if (settings->maxRetransmitTimeoutMs > 0)
  1112. s.maxRetransmitTimeout = std::chrono::milliseconds(settings->maxRetransmitTimeoutMs);
  1113. if (settings->initialRetransmitTimeoutMs > 0)
  1114. s.initialRetransmitTimeout = std::chrono::milliseconds(settings->initialRetransmitTimeoutMs);
  1115. if (settings->maxRetransmitAttempts > 0)
  1116. s.maxRetransmitAttempts = settings->maxRetransmitAttempts;
  1117. if (settings->heartbeatIntervalMs > 0)
  1118. s.heartbeatInterval = std::chrono::milliseconds(settings->heartbeatIntervalMs);
  1119. SetSctpSettings(std::move(s));
  1120. return RTC_ERR_SUCCESS;
  1121. });
  1122. }