main.cpp 10.0 KB

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