main.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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::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. atomic<size_t> receivedSize = 0, sentSize = 0;
  54. bool noSend = false;
  55. int main(int argc, char **argv) try {
  56. Cmdline params(argc, argv);
  57. rtc::InitLogger(LogLevel::Info);
  58. // Benchmark - construct message to send
  59. fill(messageData.begin(), messageData.end(), std::byte(0xFF));
  60. // No Send option
  61. noSend = params.noSend();
  62. if (noSend)
  63. cout << "Not Sending data. (One way benchmark)." << endl;
  64. Configuration config;
  65. string stunServer = "";
  66. if (params.noStun()) {
  67. cout << "No STUN server is configured. Only local hosts and public IP addresses supported."
  68. << endl;
  69. } else {
  70. if (params.stunServer().substr(0, 5).compare("stun:") != 0) {
  71. stunServer = "stun:";
  72. }
  73. stunServer += params.stunServer() + ":" + to_string(params.stunPort());
  74. cout << "Stun server is " << stunServer << endl;
  75. config.iceServers.emplace_back(stunServer);
  76. }
  77. localId = randomId(4);
  78. cout << "The local ID is: " << localId << endl;
  79. auto ws = make_shared<WebSocket>();
  80. std::promise<void> wsPromise;
  81. auto wsFuture = wsPromise.get_future();
  82. ws->onOpen([&wsPromise]() {
  83. cout << "WebSocket connected, signaling ready" << endl;
  84. wsPromise.set_value();
  85. });
  86. ws->onError([&wsPromise](string s) {
  87. cout << "WebSocket error" << endl;
  88. wsPromise.set_exception(std::make_exception_ptr(std::runtime_error(s)));
  89. });
  90. ws->onClosed([]() { cout << "WebSocket closed" << endl; });
  91. ws->onMessage([&](variant<binary, string> data) {
  92. if (!holds_alternative<string>(data))
  93. return;
  94. json message = json::parse(get<string>(data));
  95. auto it = message.find("id");
  96. if (it == message.end())
  97. return;
  98. string id = it->get<string>();
  99. it = message.find("type");
  100. if (it == message.end())
  101. return;
  102. string type = it->get<string>();
  103. shared_ptr<PeerConnection> pc;
  104. if (auto jt = peerConnectionMap.find(id); jt != peerConnectionMap.end()) {
  105. pc = jt->second;
  106. } else if (type == "offer") {
  107. cout << "Answering to " + id << endl;
  108. pc = createPeerConnection(config, ws, id);
  109. } else {
  110. return;
  111. }
  112. if (type == "offer" || type == "answer") {
  113. auto sdp = message["description"].get<string>();
  114. pc->setRemoteDescription(Description(sdp, type));
  115. } else if (type == "candidate") {
  116. auto sdp = message["candidate"].get<string>();
  117. auto mid = message["mid"].get<string>();
  118. pc->addRemoteCandidate(Candidate(sdp, mid));
  119. }
  120. });
  121. string wsPrefix = "";
  122. if (params.webSocketServer().substr(0, 5).compare("ws://") != 0) {
  123. wsPrefix = "ws://";
  124. }
  125. const string url = wsPrefix + params.webSocketServer() + ":" +
  126. to_string(params.webSocketPort()) + "/" + localId;
  127. cout << "Url is " << url << endl;
  128. ws->open(url);
  129. cout << "Waiting for signaling to be connected..." << endl;
  130. wsFuture.get();
  131. string id;
  132. cout << "Enter a remote ID to send an offer:" << endl;
  133. cin >> id;
  134. cin.ignore();
  135. if (id.empty()) {
  136. // Nothing to do
  137. return 0;
  138. }
  139. if (id == localId) {
  140. cout << "Invalid remote ID (This is my local ID). Exiting..." << endl;
  141. return 0;
  142. }
  143. cout << "Offering to " + id << endl;
  144. auto pc = createPeerConnection(config, ws, id);
  145. // We are the offerer, so create a data channel to initiate the process
  146. const string label = "benchmark";
  147. cout << "Creating DataChannel with label \"" << label << "\"" << endl;
  148. auto dc = pc->createDataChannel(label);
  149. dc->onOpen([id, wdc = make_weak_ptr(dc)]() {
  150. cout << "DataChannel from " << id << " open" << endl;
  151. if (noSend)
  152. return;
  153. if (auto dcLocked = wdc.lock()) {
  154. cout << "Starting benchmark test. Sending data..." << endl;
  155. try {
  156. while (dcLocked->bufferedAmount() == 0) {
  157. dcLocked->send(messageData);
  158. sentSize += messageData.size();
  159. }
  160. } catch (const std::exception &e) {
  161. std::cout << "Send failed: " << e.what() << std::endl;
  162. }
  163. }
  164. });
  165. dc->onBufferedAmountLow([wdc = make_weak_ptr(dc)]() {
  166. if (noSend)
  167. return;
  168. auto dcLocked = wdc.lock();
  169. if (!dcLocked)
  170. return;
  171. // Continue sending
  172. try {
  173. while (dcLocked->isOpen() && dcLocked->bufferedAmount() == 0) {
  174. dcLocked->send(messageData);
  175. sentSize += messageData.size();
  176. }
  177. } catch (const std::exception &e) {
  178. std::cout << "Send failed: " << e.what() << std::endl;
  179. }
  180. });
  181. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  182. dc->onMessage([id, wdc = make_weak_ptr(dc)](variant<binary, string> data) {
  183. if (holds_alternative<binary>(data))
  184. receivedSize += get<binary>(data).size();
  185. });
  186. dataChannelMap.emplace(id, dc);
  187. const int duration = params.durationInSec() > 0 ? params.durationInSec() : INT32_MAX;
  188. cout << "Becnhmark will run for " << duration << " seconds" << endl;
  189. int printStatCounter = 0;
  190. steady_clock::time_point startTime = steady_clock::now();
  191. for (int i = 1; i <= duration; ++i) {
  192. this_thread::sleep_for(1000ms);
  193. unsigned long _receivedSize = receivedSize.exchange(0);
  194. unsigned long _sentSize = sentSize.exchange(0);
  195. float timePassedAsSec = ((steady_clock::now() - startTime).count()) / (1000.0 * 1000.0); // sec
  196. startTime = steady_clock::now();
  197. cout << "#" << i << " Received: " << static_cast<int>(_receivedSize / timePassedAsSec) << " KB/s"
  198. << " Sent: " << static_cast<int>(_sentSize / timePassedAsSec) << " KB/s"
  199. << " BufferSize: " << dc->bufferedAmount() << endl;
  200. printStatCounter++;
  201. if (printStatCounter % 5 == 0) {
  202. cout << "Stats# "
  203. << "Received Total: " << pc->bytesReceived() / (1000 * 1000) << " MB"
  204. << " Sent Total: " << pc->bytesSent() / (1000 * 1000) << " MB"
  205. << " RTT: " << pc->rtt().value_or(0ms).count() << " ms" << endl;
  206. cout << endl;
  207. }
  208. }
  209. cout << "Cleaning up..." << endl;
  210. dataChannelMap.clear();
  211. peerConnectionMap.clear();
  212. return 0;
  213. } catch (const std::exception &e) {
  214. std::cout << "Error: " << e.what() << std::endl;
  215. dataChannelMap.clear();
  216. peerConnectionMap.clear();
  217. return -1;
  218. }
  219. // Create and setup a PeerConnection
  220. shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
  221. weak_ptr<WebSocket> wws, string id) {
  222. auto pc = make_shared<PeerConnection>(config);
  223. pc->onStateChange([](PeerConnection::State state) { cout << "State: " << state << endl; });
  224. pc->onGatheringStateChange(
  225. [](PeerConnection::GatheringState state) { cout << "Gathering State: " << state << endl; });
  226. pc->onLocalDescription([wws, id](Description description) {
  227. json message = {
  228. {"id", id}, {"type", description.typeString()}, {"description", string(description)}};
  229. if (auto ws = wws.lock())
  230. ws->send(message.dump());
  231. });
  232. pc->onLocalCandidate([wws, id](Candidate candidate) {
  233. json message = {{"id", id},
  234. {"type", "candidate"},
  235. {"candidate", string(candidate)},
  236. {"mid", candidate.mid()}};
  237. if (auto ws = wws.lock())
  238. ws->send(message.dump());
  239. });
  240. pc->onDataChannel([id](shared_ptr<DataChannel> dc) {
  241. cout << "DataChannel from " << id << " received with label \"" << dc->label() << "\""
  242. << endl;
  243. cout << "###########################################" << endl;
  244. cout << "### Check other peer's screen for stats ###" << endl;
  245. cout << "###########################################" << endl;
  246. if (!noSend) {
  247. cout << "Starting benchmark test. Sending data ..." << endl;
  248. try {
  249. while (dc->bufferedAmount() == 0) {
  250. dc->send(messageData);
  251. sentSize += messageData.size();
  252. }
  253. } catch (const std::exception &e) {
  254. std::cout << "Send failed: " << e.what() << std::endl;
  255. }
  256. }
  257. dc->onBufferedAmountLow([wdc = make_weak_ptr(dc)]() {
  258. if (noSend)
  259. return;
  260. auto dcLocked = wdc.lock();
  261. if (!dcLocked)
  262. return;
  263. // Continue sending
  264. try {
  265. while (dcLocked->isOpen() && dcLocked->bufferedAmount() == 0) {
  266. dcLocked->send(messageData);
  267. sentSize += messageData.size();
  268. }
  269. } catch (const std::exception &e) {
  270. std::cout << "Send failed: " << e.what() << std::endl;
  271. }
  272. });
  273. dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
  274. dc->onMessage([id, wdc = make_weak_ptr(dc)](variant<binary, string> data) {
  275. if (holds_alternative<binary>(data))
  276. receivedSize += get<binary>(data).size();
  277. });
  278. dataChannelMap.emplace(id, dc);
  279. });
  280. peerConnectionMap.emplace(id, pc);
  281. return pc;
  282. };
  283. // Helper function to generate a random ID
  284. string randomId(size_t length) {
  285. static const string characters(
  286. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  287. string id(length, '0');
  288. default_random_engine rng(random_device{}());
  289. uniform_int_distribution<int> dist(0, int(characters.size() - 1));
  290. generate(id.begin(), id.end(), [&]() { return characters.at(dist(rng)); });
  291. return id;
  292. }