main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /*
  2. * libdatachannel client-benchmark example
  3. * Copyright (c) 2019-2020 Paul-Louis Ageneau
  4. * Copyright (c) 2019-2021 Murat Dogan
  5. * Copyright (c) 2020 Will Munn
  6. * Copyright (c) 2020 Nico Chatzi
  7. * Copyright (c) 2020 Lara Mackey
  8. * Copyright (c) 2020 Erik Cota-Robles
  9. *
  10. * This program is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU General Public License
  12. * as published by the Free Software Foundation; either version 2
  13. * of the License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program; If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. #include "rtc/rtc.hpp"
  24. #include "parse_cl.h"
  25. #include <nlohmann/json.hpp>
  26. #include <algorithm>
  27. #include <atomic>
  28. #include <chrono>
  29. #include <future>
  30. #include <iomanip>
  31. #include <iostream>
  32. #include <memory>
  33. #include <random>
  34. #include <stdexcept>
  35. #include <thread>
  36. #include <unordered_map>
  37. using namespace rtc;
  38. using namespace std;
  39. using namespace std::chrono_literals;
  40. using chrono::milliseconds;
  41. using chrono::steady_clock;
  42. using json = nlohmann::json;
  43. template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
  44. unordered_map<string, shared_ptr<PeerConnection>> peerConnectionMap;
  45. unordered_map<string, shared_ptr<DataChannel>> dataChannelMap;
  46. string localId;
  47. shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
  48. weak_ptr<WebSocket> wws, string id);
  49. string randomId(size_t length);
  50. // Benchmark
  51. const size_t messageSize = 65535;
  52. binary messageData(messageSize);
  53. unordered_map<string, atomic<size_t>> receivedSizeMap;
  54. unordered_map<string, atomic<size_t>> sentSizeMap;
  55. // atomic<size_t> receivedSize = 0, sentSize = 0;
  56. bool noSend = false;
  57. // Benchmark - enableThroughputSet params
  58. bool enableThroughputSet;
  59. int throughtputSetAsKB;
  60. int bufferSize;
  61. const float STEP_COUNT_FOR_1_SEC = 100.0;
  62. const int stepDurationInMs = 1000 / STEP_COUNT_FOR_1_SEC;
  63. int main(int argc, char **argv) try {
  64. Cmdline params(argc, argv);
  65. rtc::InitLogger(LogLevel::Info);
  66. // Benchmark - construct message to send
  67. fill(messageData.begin(), messageData.end(), std::byte(0xFF));
  68. // Benchmark - enableThroughputSet params
  69. enableThroughputSet = params.enableThroughputSet();
  70. throughtputSetAsKB = params.throughtputSetAsKB();
  71. bufferSize = params.bufferSize();
  72. // No Send option
  73. noSend = params.noSend();
  74. if (noSend)
  75. cout << "Not Sending data. (One way benchmark)." << endl;
  76. Configuration config;
  77. string stunServer = "";
  78. if (params.noStun()) {
  79. cout << "No STUN server is configured. Only local hosts and public IP addresses supported."
  80. << endl;
  81. } else {
  82. if (params.stunServer().substr(0, 5).compare("stun:") != 0) {
  83. stunServer = "stun:";
  84. }
  85. stunServer += params.stunServer() + ":" + to_string(params.stunPort());
  86. cout << "Stun server is " << stunServer << endl;
  87. config.iceServers.emplace_back(stunServer);
  88. }
  89. localId = randomId(4);
  90. cout << "The local ID is: " << localId << endl;
  91. auto ws = make_shared<WebSocket>();
  92. std::promise<void> wsPromise;
  93. auto wsFuture = wsPromise.get_future();
  94. ws->onOpen([&wsPromise]() {
  95. cout << "WebSocket connected, signaling ready" << endl;
  96. wsPromise.set_value();
  97. });
  98. ws->onError([&wsPromise](string s) {
  99. cout << "WebSocket error" << endl;
  100. wsPromise.set_exception(std::make_exception_ptr(std::runtime_error(s)));
  101. });
  102. ws->onClosed([]() { cout << "WebSocket closed" << endl; });
  103. ws->onMessage([&](variant<binary, string> data) {
  104. if (!holds_alternative<string>(data))
  105. return;
  106. json message = json::parse(get<string>(data));
  107. auto it = message.find("id");
  108. if (it == message.end())
  109. return;
  110. string id = it->get<string>();
  111. it = message.find("type");
  112. if (it == message.end())
  113. return;
  114. string type = it->get<string>();
  115. shared_ptr<PeerConnection> pc;
  116. if (auto jt = peerConnectionMap.find(id); jt != peerConnectionMap.end()) {
  117. pc = jt->second;
  118. } else if (type == "offer") {
  119. cout << "Answering to " + id << endl;
  120. pc = createPeerConnection(config, ws, id);
  121. } else {
  122. return;
  123. }
  124. if (type == "offer" || type == "answer") {
  125. auto sdp = message["description"].get<string>();
  126. pc->setRemoteDescription(Description(sdp, type));
  127. } else if (type == "candidate") {
  128. auto sdp = message["candidate"].get<string>();
  129. auto mid = message["mid"].get<string>();
  130. pc->addRemoteCandidate(Candidate(sdp, mid));
  131. }
  132. });
  133. string wsPrefix = "";
  134. if (params.webSocketServer().substr(0, 5).compare("ws://") != 0) {
  135. wsPrefix = "ws://";
  136. }
  137. const string url = wsPrefix + params.webSocketServer() + ":" +
  138. to_string(params.webSocketPort()) + "/" + localId;
  139. cout << "Url is " << url << endl;
  140. ws->open(url);
  141. cout << "Waiting for signaling to be connected..." << endl;
  142. wsFuture.get();
  143. string id;
  144. cout << "Enter a remote ID to send an offer:" << endl;
  145. cin >> id;
  146. cin.ignore();
  147. if (id.empty()) {
  148. // Nothing to do
  149. return 0;
  150. }
  151. if (id == localId) {
  152. cout << "Invalid remote ID (This is my local ID). Exiting..." << endl;
  153. return 0;
  154. }
  155. cout << "Offering to " + id << endl;
  156. auto pc = createPeerConnection(config, ws, id);
  157. // We are the offerer, so create a data channel to initiate the process
  158. for (int i = 1; i <= params.dataChannelCount(); i++) {
  159. const string label = "DC-" + std::to_string(i);
  160. cout << "Creating DataChannel with label \"" << label << "\"" << endl;
  161. auto dc = pc->createDataChannel(label);
  162. receivedSizeMap.emplace(label, 0);
  163. sentSizeMap.emplace(label, 0);
  164. // Set Buffer Size
  165. dc->setBufferedAmountLowThreshold(bufferSize);
  166. dc->onOpen([id, wdc = make_weak_ptr(dc), label]() {
  167. cout << "DataChannel from " << id << " open" << endl;
  168. if (noSend)
  169. return;
  170. if (enableThroughputSet)
  171. return;
  172. if (auto dcLocked = wdc.lock()) {
  173. try {
  174. while (dcLocked->bufferedAmount() <= bufferSize) {
  175. dcLocked->send(messageData);
  176. sentSizeMap[label] += messageData.size();
  177. }
  178. } catch (const std::exception &e) {
  179. std::cout << "Send failed: " << e.what() << std::endl;
  180. }
  181. }
  182. });
  183. dc->onBufferedAmountLow([wdc = make_weak_ptr(dc), label]() {
  184. if (noSend)
  185. return;
  186. if (enableThroughputSet)
  187. return;
  188. auto dcLocked = wdc.lock();
  189. if (!dcLocked)
  190. return;
  191. // Continue sending
  192. try {
  193. while (dcLocked->isOpen() && dcLocked->bufferedAmount() <= bufferSize) {
  194. dcLocked->send(messageData);
  195. sentSizeMap[label] += messageData.size();
  196. }
  197. } catch (const std::exception &e) {
  198. std::cout << "Send failed: " << e.what() << std::endl;
  199. }
  200. });
  201. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  202. dc->onMessage([id, wdc = make_weak_ptr(dc), label](variant<binary, string> data) {
  203. if (holds_alternative<binary>(data))
  204. receivedSizeMap[label] += get<binary>(data).size();
  205. });
  206. dataChannelMap.emplace(label, dc);
  207. }
  208. const int duration = params.durationInSec() > 0 ? params.durationInSec() : INT32_MAX;
  209. cout << "Benchmark will run for " << duration << " seconds" << endl;
  210. int printCounter = 0;
  211. int printStatCounter = 0;
  212. steady_clock::time_point printTime = steady_clock::now();
  213. steady_clock::time_point stepTime = steady_clock::now();
  214. // Byte count to send for every loop
  215. int byteToSendOnEveryLoop = throughtputSetAsKB * stepDurationInMs;
  216. for (int i = 1; i <= duration * STEP_COUNT_FOR_1_SEC; ++i) {
  217. this_thread::sleep_for(milliseconds(stepDurationInMs));
  218. printCounter++;
  219. if (enableThroughputSet) {
  220. const double elapsedTimeInSecs =
  221. std::chrono::duration<double>(steady_clock::now() - stepTime).count();
  222. stepTime = steady_clock::now();
  223. int byteToSendThisLoop = static_cast<int>(
  224. byteToSendOnEveryLoop * ((elapsedTimeInSecs * 1000.0) / stepDurationInMs));
  225. binary tempMessageData(byteToSendThisLoop);
  226. fill(tempMessageData.begin(), tempMessageData.end(), std::byte(0xFF));
  227. for (const auto &[label, dc] : dataChannelMap) {
  228. if (dc->isOpen() && dc->bufferedAmount() <= bufferSize * byteToSendOnEveryLoop) {
  229. dc->send(tempMessageData);
  230. sentSizeMap[label] += tempMessageData.size();
  231. }
  232. }
  233. }
  234. if (printCounter >= STEP_COUNT_FOR_1_SEC) {
  235. const double elapsedTimeInSecs =
  236. std::chrono::duration<double>(steady_clock::now() - printTime).count();
  237. printTime = steady_clock::now();
  238. unsigned long receiveSpeedTotal = 0;
  239. unsigned long sendSpeedTotal = 0;
  240. cout << "#" << i / STEP_COUNT_FOR_1_SEC << endl;
  241. for (const auto &[label, dc] : dataChannelMap) {
  242. unsigned long channelReceiveSpeed = static_cast<int>(
  243. receivedSizeMap[label].exchange(0) / (elapsedTimeInSecs * 1000));
  244. unsigned long channelSendSpeed =
  245. static_cast<int>(sentSizeMap[label].exchange(0) / (elapsedTimeInSecs * 1000));
  246. cout << std::setw(10) << label << " Received: " << channelReceiveSpeed << " KB/s"
  247. << " Sent: " << channelSendSpeed << " KB/s"
  248. << " BufferSize: " << dc->bufferedAmount() << endl;
  249. receiveSpeedTotal += channelReceiveSpeed;
  250. sendSpeedTotal += channelSendSpeed;
  251. }
  252. cout << std::setw(10) << "TOTL"
  253. << " Received: " << receiveSpeedTotal << " KB/s"
  254. << " Sent: " << sendSpeedTotal << " KB/s" << endl;
  255. printStatCounter++;
  256. printCounter = 0;
  257. }
  258. if (printStatCounter >= 5) {
  259. cout << "Stats# "
  260. << "Received Total: " << pc->bytesReceived() / (1000 * 1000) << " MB"
  261. << " Sent Total: " << pc->bytesSent() / (1000 * 1000) << " MB"
  262. << " RTT: " << pc->rtt().value_or(0ms).count() << " ms" << endl;
  263. cout << endl;
  264. printStatCounter = 0;
  265. }
  266. }
  267. cout << "Cleaning up..." << endl;
  268. dataChannelMap.clear();
  269. peerConnectionMap.clear();
  270. receivedSizeMap.clear();
  271. sentSizeMap.clear();
  272. return 0;
  273. } catch (const std::exception &e) {
  274. std::cout << "Error: " << e.what() << std::endl;
  275. dataChannelMap.clear();
  276. peerConnectionMap.clear();
  277. receivedSizeMap.clear();
  278. sentSizeMap.clear();
  279. return -1;
  280. }
  281. // Create and setup a PeerConnection
  282. shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
  283. weak_ptr<WebSocket> wws, string id) {
  284. auto pc = make_shared<PeerConnection>(config);
  285. pc->onStateChange([](PeerConnection::State state) { cout << "State: " << state << endl; });
  286. pc->onGatheringStateChange(
  287. [](PeerConnection::GatheringState state) { cout << "Gathering State: " << state << endl; });
  288. pc->onLocalDescription([wws, id](Description description) {
  289. json message = {
  290. {"id", id}, {"type", description.typeString()}, {"description", string(description)}};
  291. if (auto ws = wws.lock())
  292. ws->send(message.dump());
  293. });
  294. pc->onLocalCandidate([wws, id](Candidate candidate) {
  295. json message = {{"id", id},
  296. {"type", "candidate"},
  297. {"candidate", string(candidate)},
  298. {"mid", candidate.mid()}};
  299. if (auto ws = wws.lock())
  300. ws->send(message.dump());
  301. });
  302. pc->onDataChannel([id](shared_ptr<DataChannel> dc) {
  303. const string label = dc->label();
  304. cout << "DataChannel from " << id << " received with label \"" << label << "\"" << endl;
  305. cout << "###########################################" << endl;
  306. cout << "### Check other peer's screen for stats ###" << endl;
  307. cout << "###########################################" << endl;
  308. receivedSizeMap.emplace(dc->label(), 0);
  309. sentSizeMap.emplace(dc->label(), 0);
  310. // Set Buffer Size
  311. dc->setBufferedAmountLowThreshold(bufferSize);
  312. if (!noSend && !enableThroughputSet) {
  313. try {
  314. while (dc->bufferedAmount() <= bufferSize) {
  315. dc->send(messageData);
  316. sentSizeMap[label] += messageData.size();
  317. }
  318. } catch (const std::exception &e) {
  319. std::cout << "Send failed: " << e.what() << std::endl;
  320. }
  321. }
  322. if (!noSend && enableThroughputSet) {
  323. // Create Send Data Thread
  324. // Thread will join when data channel destroyed or closed
  325. std::thread([wdc = make_weak_ptr(dc), label]() {
  326. steady_clock::time_point stepTime = steady_clock::now();
  327. // Byte count to send for every loop
  328. int byteToSendOnEveryLoop = throughtputSetAsKB * stepDurationInMs;
  329. while (true) {
  330. this_thread::sleep_for(milliseconds(stepDurationInMs));
  331. auto dcLocked = wdc.lock();
  332. if (!dcLocked)
  333. break;
  334. if (!dcLocked->isOpen())
  335. break;
  336. try {
  337. const double elapsedTimeInSecs =
  338. std::chrono::duration<double>(steady_clock::now() - stepTime).count();
  339. stepTime = steady_clock::now();
  340. int byteToSendThisLoop =
  341. static_cast<int>(byteToSendOnEveryLoop *
  342. ((elapsedTimeInSecs * 1000.0) / stepDurationInMs));
  343. binary tempMessageData(byteToSendThisLoop);
  344. fill(tempMessageData.begin(), tempMessageData.end(), std::byte(0xFF));
  345. if (dcLocked->bufferedAmount() <= bufferSize) {
  346. dcLocked->send(tempMessageData);
  347. sentSizeMap[label] += tempMessageData.size();
  348. }
  349. } catch (const std::exception &e) {
  350. std::cout << "Send failed: " << e.what() << std::endl;
  351. }
  352. }
  353. cout << "Send Data Thread exiting..." << endl;
  354. }).detach();
  355. }
  356. dc->onBufferedAmountLow([wdc = make_weak_ptr(dc), label]() {
  357. if (noSend)
  358. return;
  359. if (enableThroughputSet)
  360. return;
  361. auto dcLocked = wdc.lock();
  362. if (!dcLocked)
  363. return;
  364. // Continue sending
  365. try {
  366. while (dcLocked->isOpen() && dcLocked->bufferedAmount() <= bufferSize) {
  367. dcLocked->send(messageData);
  368. sentSizeMap[label] += messageData.size();
  369. }
  370. } catch (const std::exception &e) {
  371. std::cout << "Send failed: " << e.what() << std::endl;
  372. }
  373. });
  374. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  375. dc->onMessage([id, wdc = make_weak_ptr(dc), label](variant<binary, string> data) {
  376. if (holds_alternative<binary>(data))
  377. receivedSizeMap[label] += get<binary>(data).size();
  378. });
  379. dataChannelMap.emplace(label, dc);
  380. });
  381. peerConnectionMap.emplace(id, pc);
  382. return pc;
  383. };
  384. // Helper function to generate a random ID
  385. string randomId(size_t length) {
  386. static const string characters(
  387. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  388. string id(length, '0');
  389. default_random_engine rng(random_device{}());
  390. uniform_int_distribution<int> dist(0, int(characters.size() - 1));
  391. generate(id.begin(), id.end(), [&]() { return characters.at(dist(rng)); });
  392. return id;
  393. }