188 lines
7.5 KiB
C++
188 lines
7.5 KiB
C++
|
#include "Client.h"
|
||
|
|
||
|
#include "BoostLog.h"
|
||
|
#include <boost/json/object.hpp>
|
||
|
#include <boost/json/parse.hpp>
|
||
|
#include <boost/json/serialize.hpp>
|
||
|
#include <random>
|
||
|
#include <rtc/rtc.hpp>
|
||
|
|
||
|
class ClientPrivate {
|
||
|
public:
|
||
|
Client *p = nullptr;
|
||
|
rtc::Configuration config;
|
||
|
std::shared_ptr<rtc::WebSocket> ws;
|
||
|
std::unordered_map<std::string, std::shared_ptr<rtc::PeerConnection>> peerConnectionMap;
|
||
|
std::unordered_map<std::string, std::shared_ptr<rtc::DataChannel>> dataChannelMap;
|
||
|
std::shared_ptr<rtc::DataChannel> m_sender;
|
||
|
ClientPrivate(Client *p) : p(p) {
|
||
|
}
|
||
|
std::shared_ptr<rtc::PeerConnection> createPeerConnection(const rtc::Configuration &config, std::weak_ptr<rtc::WebSocket> wws,
|
||
|
std::string id) {
|
||
|
auto pc = std::make_shared<rtc::PeerConnection>(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([this, id](std::shared_ptr<rtc::DataChannel> dc) {
|
||
|
LOG(info) << "DataChannel from " << id << " received with label \"" << dc->label() << "\"";
|
||
|
|
||
|
dc->onOpen([this, wdc = std::weak_ptr(dc)]() {
|
||
|
if (auto dc = wdc.lock()) dc->send("Hello from " + p->m_id);
|
||
|
});
|
||
|
|
||
|
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<std::string>(data))
|
||
|
LOG(info) << "Message from " << id << " received: " << std::get<std::string>(data);
|
||
|
else
|
||
|
LOG(info) << "Binary message from " << id << " received, size=" << std::get<rtc::binary>(data).size();
|
||
|
});
|
||
|
dataChannelMap.emplace(id, dc);
|
||
|
});
|
||
|
peerConnectionMap.emplace(id, pc);
|
||
|
return pc;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
bool Client::sendMessage(const std::string &message) {
|
||
|
bool ret = false;
|
||
|
if (m_d->m_sender) {
|
||
|
ret = m_d->m_sender->send(message);
|
||
|
}
|
||
|
return ret;
|
||
|
}
|
||
|
|
||
|
bool Client::setRemoteId(const std::string &id) {
|
||
|
bool ret = false;
|
||
|
if (id.empty() || !m_d->ws->isOpen()) return ret;
|
||
|
if (id == m_id) {
|
||
|
LOG(error) << "Invalid remote ID (This is the local ID)";
|
||
|
log("Invalid remote ID (This is the local ID)");
|
||
|
return ret;
|
||
|
}
|
||
|
LOG(info) << "Offering to " << id;
|
||
|
log(std::format("Offering to {}", id));
|
||
|
auto pc = m_d->createPeerConnection(m_d->config, m_d->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 << "\"";
|
||
|
log(std::format("Creating DataChannel with label \"{}\"", label));
|
||
|
m_d->m_sender = pc->createDataChannel(label);
|
||
|
m_d->m_sender->onOpen([this, id, wdc = std::weak_ptr(m_d->m_sender)]() {
|
||
|
LOG(info) << "DataChannel from " << id << " open";
|
||
|
if (auto dc = wdc.lock()) dc->send("Hello from " + m_id);
|
||
|
});
|
||
|
m_d->m_sender->onClosed([id]() { LOG(info) << "DataChannel from " << id << " closed"; });
|
||
|
m_d->m_sender->onMessage([id, wdc = std::weak_ptr(m_d->m_sender)](auto data) {
|
||
|
// data holds either std::string or rtc::binary
|
||
|
if (std::holds_alternative<std::string>(data))
|
||
|
LOG(info) << "Message from " << id << " received: " << std::get<std::string>(data);
|
||
|
else
|
||
|
LOG(info) << "Binary message from " << id << " received, size=" << std::get<rtc::binary>(data).size();
|
||
|
});
|
||
|
m_d->dataChannelMap.emplace(id, m_d->m_sender);
|
||
|
return ret;
|
||
|
}
|
||
|
|
||
|
std::string Client::randomId(size_t length) {
|
||
|
using std::chrono::high_resolution_clock;
|
||
|
static thread_local std::mt19937 rng(static_cast<unsigned int>(high_resolution_clock::now().time_since_epoch().count()));
|
||
|
static const std::string characters("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
|
||
|
std::string id(length, '0');
|
||
|
std::uniform_int_distribution<int> uniform(0, int(characters.size() - 1));
|
||
|
std::generate(id.begin(), id.end(), [&]() { return characters.at(uniform(rng)); });
|
||
|
return id;
|
||
|
}
|
||
|
|
||
|
Client::Client() : m_d{new ClientPrivate(this)} {
|
||
|
rtc::InitLogger(rtc::LogLevel::Info);
|
||
|
m_id = randomId(4);
|
||
|
LOG(info) << "The local ID is " << m_id;
|
||
|
log(std::format("The local ID is {}", m_id));
|
||
|
|
||
|
m_d->ws = std::make_shared<rtc::WebSocket>();
|
||
|
|
||
|
m_d->ws->onOpen([this]() {
|
||
|
LOG(info) << "WebSocket connected, signaling ready";
|
||
|
log("WebSocket connected, signaling ready");
|
||
|
});
|
||
|
m_d->ws->onError([this](std::string s) {
|
||
|
LOG(error) << "WebSocket error: " << s;
|
||
|
log(std::format("WebSocket error: {}", s));
|
||
|
});
|
||
|
m_d->ws->onClosed([]() { LOG(info) << "WebSocket closed"; });
|
||
|
m_d->ws->onMessage([this](auto data) {
|
||
|
if (!std::holds_alternative<std::string>(data)) return;
|
||
|
auto jsonValue = boost::json::parse(std::get<std::string>(data));
|
||
|
auto &json = jsonValue.as_object();
|
||
|
if (!json.contains("id") || !json.contains("type")) {
|
||
|
return;
|
||
|
}
|
||
|
auto id = static_cast<std::string>(json.at("id").as_string());
|
||
|
auto type = static_cast<std::string>(json.at("type").as_string());
|
||
|
|
||
|
std::shared_ptr<rtc::PeerConnection> pc;
|
||
|
if (auto jt = m_d->peerConnectionMap.find(id); jt != m_d->peerConnectionMap.end()) {
|
||
|
pc = jt->second;
|
||
|
} else if (type == "offer") {
|
||
|
std::cout << "Answering to " + id << std::endl;
|
||
|
pc = m_d->createPeerConnection(m_d->config, m_d->ws, id);
|
||
|
} else {
|
||
|
return;
|
||
|
}
|
||
|
if (type == "offer" || type == "answer") {
|
||
|
auto sdp = static_cast<std::string>(json.at("description").as_string());
|
||
|
pc->setRemoteDescription(rtc::Description(sdp, type));
|
||
|
} else if (type == "candidate") {
|
||
|
auto sdp = static_cast<std::string>(json.at("candidate").as_string());
|
||
|
auto mid = static_cast<std::string>(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/{}", m_id);
|
||
|
LOG(info) << "WebSocket URL is " << url;
|
||
|
log(std::format("WebSocket URL is {}", url));
|
||
|
m_d->ws->open(url);
|
||
|
|
||
|
LOG(info) << "Waiting for signaling to be connected...";
|
||
|
log("Waiting for signaling to be connected...");
|
||
|
}
|
||
|
|
||
|
Client::~Client() {
|
||
|
LOG(info) << "Cleaning up...";
|
||
|
if (m_d != nullptr) {
|
||
|
delete m_d;
|
||
|
m_d = nullptr;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
std::string Client::id() const {
|
||
|
return m_id;
|
||
|
}
|
||
|
|
||
|
void Client::log(const std::string &message) {
|
||
|
m_oss << message << std::endl;
|
||
|
}
|
||
|
|
||
|
std::string Client::log() const {
|
||
|
return m_oss.str();
|
||
|
}
|