#include "BoostLog.h" #include #include #include #include #include std::string localId; std::unordered_map> peerConnectionMap; std::unordered_map> dataChannelMap; std::shared_ptr createPeerConnection(const rtc::Configuration &config, std::weak_ptr wws, std::string id); std::string randomId(size_t length); int main(int argc, char const *argv[]) try { rtc::InitLogger(rtc::LogLevel::Info); rtc::Configuration config; localId = randomId(4); LOG(info) << "The local ID is " << localId; auto ws = std::make_shared(); std::promise wsPromise; auto wsFuture = wsPromise.get_future(); ws->onOpen([&wsPromise]() { LOG(info) << "WebSocket connected, signaling ready"; wsPromise.set_value(); }); ws->onError([&wsPromise](std::string s) { LOG(error) << "WebSocket error"; wsPromise.set_exception(std::make_exception_ptr(std::runtime_error(s))); }); ws->onClosed([]() { LOG(info) << "WebSocket closed"; }); ws->onMessage([&config, wws = std::weak_ptr(ws)](auto data) { if (!std::holds_alternative(data)) return; auto jsonValue = boost::json::parse(std::get(data)); auto &json = jsonValue.as_object(); if (!json.contains("id") || !json.contains("type")) { return; } auto id = static_cast(json.at("id").as_string()); auto type = static_cast(json.at("type").as_string()); std::shared_ptr pc; if (auto jt = peerConnectionMap.find(id); jt != peerConnectionMap.end()) { pc = jt->second; } else if (type == "offer") { std::cout << "Answering to " + id << std::endl; pc = createPeerConnection(config, wws, id); } else { return; } if (type == "offer" || type == "answer") { auto sdp = static_cast(json.at("description").as_string()); pc->setRemoteDescription(rtc::Description(sdp, type)); } else if (type == "candidate") { auto sdp = static_cast(json.at("candidate").as_string()); auto mid = static_cast(json.at("mid").as_string()); pc->addRemoteCandidate(rtc::Candidate(sdp, mid)); } }); const std::string url = std::format("ws://127.0.0.1:8081/api/v1/webrtc/signal/{}", localId); LOG(info) << "WebSocket URL is " << url; ws->open(url); LOG(info) << "Waiting for signaling to be connected..."; wsFuture.get(); while (true) { std::string id; std::cout << "Enter a remote ID to send an offer:" << std::endl; std::cin >> id; std::cin.ignore(); if (id.empty()) break; if (id == localId) { LOG(error) << "Invalid remote ID (This is the local ID)" << std::endl; continue; } LOG(info) << "Offering to " + id; auto pc = createPeerConnection(config, ws, id); // We are the offerer, so create a data channel to initiate the process const std::string label = "test"; LOG(info) << "Creating DataChannel with label \"" << label << "\""; auto dc = pc->createDataChannel(label); dc->onOpen([id, wdc = std::weak_ptr(dc)]() { LOG(info) << "DataChannel from " << id << " open"; if (auto dc = wdc.lock()) dc->send("Hello from " + localId); }); dc->onClosed([id]() { LOG(info) << "DataChannel from " << id << " closed"; }); dc->onMessage([id, wdc = std::weak_ptr(dc)](auto data) { // data holds either std::string or rtc::binary if (std::holds_alternative(data)) LOG(info) << "Message from " << id << " received: " << std::get(data); else LOG(info) << "Binary message from " << id << " received, size=" << std::get(data).size(); }); dataChannelMap.emplace(id, dc); } LOG(info) << "Cleaning up..."; dataChannelMap.clear(); peerConnectionMap.clear(); return 0; } catch (const std::exception &e) { LOG(error) << "Error: " << e.what() << std::endl; dataChannelMap.clear(); peerConnectionMap.clear(); return -1; } std::shared_ptr createPeerConnection(const rtc::Configuration &config, std::weak_ptr wws, std::string id) { auto pc = std::make_shared(config); pc->onStateChange([](rtc::PeerConnection::State state) { LOG(info) << "State: " << state; }); pc->onGatheringStateChange([](rtc::PeerConnection::GatheringState state) { LOG(info) << "Gathering State: " << state; }); pc->onLocalDescription([wws, id](rtc::Description description) { boost::json::object message; message["id"] = id; message["type"] = description.typeString(); message["description"] = std::string(description); if (auto ws = wws.lock()) ws->send(boost::json::serialize(message)); }); pc->onLocalCandidate([wws, id](rtc::Candidate candidate) { boost::json::object message; message["id"] = id; message["type"] = "candidate"; message["candidate"] = std::string(candidate); message["mid"] = candidate.mid(); if (auto ws = wws.lock()) ws->send(boost::json::serialize(message)); }); pc->onDataChannel([id](std::shared_ptr dc) { LOG(info) << "DataChannel from " << id << " received with label \"" << dc->label() << "\""; dc->onOpen([wdc = std::weak_ptr(dc)]() { if (auto dc = wdc.lock()) dc->send("Hello from " + localId); }); dc->onClosed([id]() { LOG(info) << "DataChannel from " << id << " closed"; }); dc->onMessage([id](auto data) { // data holds either std::string or rtc::binary if (std::holds_alternative(data)) LOG(info) << "Message from " << id << " received: " << std::get(data); else LOG(info) << "Binary message from " << id << " received, size=" << std::get(data).size(); }); dataChannelMap.emplace(id, dc); }); peerConnectionMap.emplace(id, pc); return pc; } std::string randomId(size_t length) { using std::chrono::high_resolution_clock; static thread_local std::mt19937 rng(static_cast(high_resolution_clock::now().time_since_epoch().count())); static const std::string characters("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); std::string id(length, '0'); std::uniform_int_distribution uniform(0, int(characters.size() - 1)); std::generate(id.begin(), id.end(), [&]() { return characters.at(uniform(rng)); }); return id; }