main.cpp 14 KB

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