main.cpp 13 KB

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