main.cpp 9.7 KB

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