main.cpp 15 KB

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