main.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 <iostream>
  31. #include <memory>
  32. #include <random>
  33. #include <stdexcept>
  34. #include <thread>
  35. #include <unordered_map>
  36. using namespace rtc;
  37. using namespace std;
  38. using namespace std::chrono_literals;
  39. using chrono::duration_cast;
  40. using chrono::microseconds;
  41. using chrono::milliseconds;
  42. using chrono::steady_clock;
  43. using json = nlohmann::json;
  44. template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
  45. unordered_map<string, shared_ptr<PeerConnection>> peerConnectionMap;
  46. unordered_map<string, shared_ptr<DataChannel>> dataChannelMap;
  47. string localId;
  48. shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
  49. weak_ptr<WebSocket> wws, string id);
  50. string randomId(size_t length);
  51. // Benchmark
  52. const size_t messageSize = 65535;
  53. binary messageData(messageSize);
  54. atomic<size_t> receivedSize = 0, sentSize = 0;
  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 = 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. const string label = "benchmark";
  158. cout << "Creating DataChannel with label \"" << label << "\"" << endl;
  159. auto dc = pc->createDataChannel(label);
  160. // Set Buffer Size
  161. dc->setBufferedAmountLowThreshold(bufferSize);
  162. dc->onOpen([id, wdc = make_weak_ptr(dc)]() {
  163. cout << "DataChannel from " << id << " open" << endl;
  164. if (noSend)
  165. return;
  166. if (enableThroughputSet)
  167. return;
  168. if (auto dcLocked = wdc.lock()) {
  169. try {
  170. while (dcLocked->bufferedAmount() <= bufferSize) {
  171. dcLocked->send(messageData);
  172. sentSize += messageData.size();
  173. }
  174. } catch (const std::exception &e) {
  175. std::cout << "Send failed: " << e.what() << std::endl;
  176. }
  177. }
  178. });
  179. dc->onBufferedAmountLow([wdc = make_weak_ptr(dc)]() {
  180. if (noSend)
  181. return;
  182. if (enableThroughputSet)
  183. return;
  184. auto dcLocked = wdc.lock();
  185. if (!dcLocked)
  186. return;
  187. // Continue sending
  188. try {
  189. while (dcLocked->isOpen() && dcLocked->bufferedAmount() <= bufferSize) {
  190. dcLocked->send(messageData);
  191. sentSize += messageData.size();
  192. }
  193. } catch (const std::exception &e) {
  194. std::cout << "Send failed: " << e.what() << std::endl;
  195. }
  196. });
  197. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  198. dc->onMessage([id, wdc = make_weak_ptr(dc)](variant<binary, string> data) {
  199. if (holds_alternative<binary>(data))
  200. receivedSize += get<binary>(data).size();
  201. });
  202. dataChannelMap.emplace(id, dc);
  203. const int duration = params.durationInSec() > 0 ? params.durationInSec() : INT32_MAX;
  204. cout << "Benchmark will run for " << duration << " seconds" << endl;
  205. int printCounter = 0;
  206. int printStatCounter = 0;
  207. steady_clock::time_point printTime = steady_clock::now();
  208. steady_clock::time_point stepTime = steady_clock::now();
  209. // Byte count to send for every loop
  210. int byteToSendOnEveryLoop = throughtputSetAsKB * stepDurationInMs;
  211. for (int i = 1; i <= duration * STEP_COUNT_FOR_1_SEC; ++i) {
  212. this_thread::sleep_for(milliseconds(stepDurationInMs));
  213. printCounter++;
  214. if (enableThroughputSet) {
  215. float dataCountMultiplier =
  216. duration_cast<microseconds>((steady_clock::now() - stepTime)).count() /
  217. (1000.0 * stepDurationInMs);
  218. stepTime = steady_clock::now();
  219. int byteToSendThisLoop = static_cast<int>(byteToSendOnEveryLoop * dataCountMultiplier);
  220. binary tempMessageData(byteToSendThisLoop);
  221. fill(tempMessageData.begin(), tempMessageData.end(), std::byte(0xFF));
  222. if (dc->isOpen() && dc->bufferedAmount() <= bufferSize * byteToSendOnEveryLoop) {
  223. dc->send(tempMessageData);
  224. sentSize += tempMessageData.size();
  225. }
  226. }
  227. if (printCounter >= STEP_COUNT_FOR_1_SEC) {
  228. unsigned long _receivedSize = receivedSize.exchange(0);
  229. unsigned long _sentSize = sentSize.exchange(0);
  230. float dataCountMultiplier =
  231. duration_cast<milliseconds>((steady_clock::now() - printTime)).count() /
  232. (1000.0); // sec
  233. printTime = steady_clock::now();
  234. cout << "#" << i / STEP_COUNT_FOR_1_SEC
  235. << " Received: " << static_cast<int>(_receivedSize / (dataCountMultiplier * 1000))
  236. << " KB/s"
  237. << " Sent: " << static_cast<int>(_sentSize / (dataCountMultiplier * 1000))
  238. << " KB/s"
  239. << " BufferSize: " << dc->bufferedAmount() << endl;
  240. printStatCounter++;
  241. printCounter = 0;
  242. }
  243. if (printStatCounter >= 5) {
  244. cout << "Stats# "
  245. << "Received Total: " << pc->bytesReceived() / (1000 * 1000) << " MB"
  246. << " Sent Total: " << pc->bytesSent() / (1000 * 1000) << " MB"
  247. << " RTT: " << pc->rtt().value_or(0ms).count() << " ms" << endl;
  248. cout << endl;
  249. printStatCounter = 0;
  250. }
  251. }
  252. cout << "Cleaning up..." << endl;
  253. dataChannelMap.clear();
  254. peerConnectionMap.clear();
  255. return 0;
  256. } catch (const std::exception &e) {
  257. std::cout << "Error: " << e.what() << std::endl;
  258. dataChannelMap.clear();
  259. peerConnectionMap.clear();
  260. return -1;
  261. }
  262. // Create and setup a PeerConnection
  263. shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
  264. weak_ptr<WebSocket> wws, string id) {
  265. auto pc = make_shared<PeerConnection>(config);
  266. pc->onStateChange([](PeerConnection::State state) { cout << "State: " << state << endl; });
  267. pc->onGatheringStateChange(
  268. [](PeerConnection::GatheringState state) { cout << "Gathering State: " << state << endl; });
  269. pc->onLocalDescription([wws, id](Description description) {
  270. json message = {
  271. {"id", id}, {"type", description.typeString()}, {"description", string(description)}};
  272. if (auto ws = wws.lock())
  273. ws->send(message.dump());
  274. });
  275. pc->onLocalCandidate([wws, id](Candidate candidate) {
  276. json message = {{"id", id},
  277. {"type", "candidate"},
  278. {"candidate", string(candidate)},
  279. {"mid", candidate.mid()}};
  280. if (auto ws = wws.lock())
  281. ws->send(message.dump());
  282. });
  283. pc->onDataChannel([id](shared_ptr<DataChannel> dc) {
  284. cout << "DataChannel from " << id << " received with label \"" << dc->label() << "\""
  285. << endl;
  286. cout << "###########################################" << endl;
  287. cout << "### Check other peer's screen for stats ###" << endl;
  288. cout << "###########################################" << endl;
  289. // Set Buffer Size
  290. dc->setBufferedAmountLowThreshold(bufferSize);
  291. if (!noSend && !enableThroughputSet) {
  292. try {
  293. while (dc->bufferedAmount() <= bufferSize) {
  294. dc->send(messageData);
  295. sentSize += messageData.size();
  296. }
  297. } catch (const std::exception &e) {
  298. std::cout << "Send failed: " << e.what() << std::endl;
  299. }
  300. }
  301. if (!noSend && enableThroughputSet) {
  302. // Create Send Data Thread
  303. // Thread will join when data channel destroyed or closed
  304. std::thread([wdc = make_weak_ptr(dc)]() {
  305. steady_clock::time_point stepTime = steady_clock::now();
  306. // Byte count to send for every loop
  307. int byteToSendOnEveryLoop = throughtputSetAsKB * stepDurationInMs;
  308. while (true) {
  309. this_thread::sleep_for(milliseconds(stepDurationInMs));
  310. auto dcLocked = wdc.lock();
  311. if (!dcLocked)
  312. break;
  313. if (!dcLocked->isOpen())
  314. break;
  315. try {
  316. float dataCountMultiplier =
  317. duration_cast<microseconds>((steady_clock::now() - stepTime)).count() /
  318. (1000.0 * stepDurationInMs);
  319. stepTime = steady_clock::now();
  320. int byteToSendThisLoop =
  321. static_cast<int>(byteToSendOnEveryLoop * dataCountMultiplier);
  322. binary tempMessageData(byteToSendThisLoop);
  323. fill(tempMessageData.begin(), tempMessageData.end(), std::byte(0xFF));
  324. if (dcLocked->bufferedAmount() <= bufferSize) {
  325. dcLocked->send(tempMessageData);
  326. sentSize += tempMessageData.size();
  327. }
  328. } catch (const std::exception &e) {
  329. std::cout << "Send failed: " << e.what() << std::endl;
  330. }
  331. }
  332. cout << "Send Data Thread exiting..." << endl;
  333. }).detach();
  334. }
  335. dc->onBufferedAmountLow([wdc = make_weak_ptr(dc)]() {
  336. if (noSend)
  337. return;
  338. if (enableThroughputSet)
  339. return;
  340. auto dcLocked = wdc.lock();
  341. if (!dcLocked)
  342. return;
  343. // Continue sending
  344. try {
  345. while (dcLocked->isOpen() && dcLocked->bufferedAmount() <= bufferSize) {
  346. dcLocked->send(messageData);
  347. sentSize += messageData.size();
  348. }
  349. } catch (const std::exception &e) {
  350. std::cout << "Send failed: " << e.what() << std::endl;
  351. }
  352. });
  353. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  354. dc->onMessage([id, wdc = make_weak_ptr(dc)](variant<binary, string> data) {
  355. if (holds_alternative<binary>(data))
  356. receivedSize += get<binary>(data).size();
  357. });
  358. dataChannelMap.emplace(id, dc);
  359. });
  360. peerConnectionMap.emplace(id, pc);
  361. return pc;
  362. };
  363. // Helper function to generate a random ID
  364. string randomId(size_t length) {
  365. static const string characters(
  366. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  367. string id(length, '0');
  368. default_random_engine rng(random_device{}());
  369. uniform_int_distribution<int> dist(0, int(characters.size() - 1));
  370. generate(id.begin(), id.end(), [&]() { return characters.at(dist(rng)); });
  371. return id;
  372. }