refactor(gateway): remove screen-share / GoLive feature entirely
Drop the Discord Go Live (screen share) stack across the discord-gateway: - delete src/goLive/ (19 modules: Streamer, Demuxer, encoders, WebRTC wrapper, native loader, etc.) - delete native/libdatachannel-min/ N-API binding + flake native build + LD_LIBRARY_PATH wiring - delete screenShareController.ts and screen-share tests (goLive-port, golive-*, demuxerNut, screenShareInput) - mediaSource.ts: remove Invidious helpers + downloadScreenInput (YouTube full-file download) - mediaTypes.ts: drop ScreenShare* types, narrow MediaMode to 'music' and DiscordPlayerOwner to non-screen - media.handler.ts: remove screen branch, screenController/screenPlayback, voice-disconnect/reconnect accessor - commandHandler.ts: stop passing getVoiceStatus / setVoiceController into MediaHandler - media handler now only handles music; music queue/playback/status untouched Verification: tsc --noEmit clean, biome clean on touched files, no lingering goLive/screenShare refs in BE/FE/gateway.
This commit is contained in:
@@ -1,3 +0,0 @@
|
||||
node_modules/
|
||||
build/
|
||||
package-lock.json
|
||||
@@ -1,526 +0,0 @@
|
||||
// libdatachannel-min — minimal N-API binding to libdatachannel.
|
||||
// Exposes ONLY what GMW GoLive needs:
|
||||
// PeerConnection (offer/answer, ICE, SDP), DataChannel (signaling),
|
||||
// Track send (added in media phase).
|
||||
// Built against libdatachannel 0.24.0 (built from source in /tmp/ldc-build).
|
||||
|
||||
#include <napi.h>
|
||||
#include <rtc/rtc.hpp>
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
|
||||
using namespace Napi;
|
||||
|
||||
namespace {
|
||||
|
||||
std::string stateToString(rtc::PeerConnection::State s) {
|
||||
switch (s) {
|
||||
case rtc::PeerConnection::State::New: return "new";
|
||||
case rtc::PeerConnection::State::Connecting: return "connecting";
|
||||
case rtc::PeerConnection::State::Connected: return "connected";
|
||||
case rtc::PeerConnection::State::Disconnected: return "disconnected";
|
||||
case rtc::PeerConnection::State::Failed: return "failed";
|
||||
case rtc::PeerConnection::State::Closed: return "closed";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
std::string binaryToString(const rtc::binary& data) {
|
||||
// rtc::binary is std::vector<std::byte> in libdatachannel >= 0.21
|
||||
std::string msg(data.size(), '\0');
|
||||
for (size_t i = 0; i < data.size(); i++) {
|
||||
msg[i] = static_cast<char>(data[i]);
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
// Holds a Napi::Promise::Deferred so it can be moved into TSFN lambdas
|
||||
// without invalid copies (node-addon-api 8.x Deferred is not movable).
|
||||
struct DeferredHolder {
|
||||
Promise::Deferred deferred;
|
||||
explicit DeferredHolder(Promise::Deferred d) : deferred(d) {}
|
||||
};
|
||||
|
||||
class DataChannelWrap : public Napi::ObjectWrap<DataChannelWrap> {
|
||||
public:
|
||||
static Function Init(Napi::Env env) {
|
||||
Function func = DefineClass(env, "DataChannel", {
|
||||
InstanceMethod("send", &DataChannelWrap::Send),
|
||||
InstanceMethod("isOpen", &DataChannelWrap::IsOpen),
|
||||
InstanceMethod("close", &DataChannelWrap::Close),
|
||||
InstanceMethod("onMessage", &DataChannelWrap::OnMessage),
|
||||
InstanceMethod("onOpen", &DataChannelWrap::OnOpen),
|
||||
});
|
||||
dcConstructor = Napi::Persistent(func);
|
||||
return func;
|
||||
}
|
||||
|
||||
// Create a JS wrapper (calls the JS constructor, returns instance).
|
||||
static Object NewInstance(Napi::Env env) {
|
||||
return dcConstructor.New({});
|
||||
}
|
||||
|
||||
DataChannelWrap(const Napi::CallbackInfo& info)
|
||||
: Napi::ObjectWrap<DataChannelWrap>(info) {}
|
||||
|
||||
void Init(std::shared_ptr<rtc::DataChannel> dc) {
|
||||
dc_ = dc;
|
||||
dc_->onMessage([this](rtc::message_variant data) {
|
||||
std::string msg;
|
||||
if (std::holds_alternative<rtc::binary>(data)) {
|
||||
msg = binaryToString(std::get<rtc::binary>(data));
|
||||
} else {
|
||||
msg = std::get<std::string>(data);
|
||||
}
|
||||
if (msgCb_) {
|
||||
msgCb_->BlockingCall([msg](Napi::Env env, Function cb) {
|
||||
cb.Call({String::New(env, msg)});
|
||||
});
|
||||
}
|
||||
});
|
||||
dc_->onOpen([this]() {
|
||||
if (openCb_) {
|
||||
openCb_->BlockingCall([](Napi::Env env, Function cb) {
|
||||
cb.Call({});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
static FunctionReference dcConstructor;
|
||||
std::shared_ptr<rtc::DataChannel> dc_;
|
||||
std::shared_ptr<ThreadSafeFunction> msgCb_;
|
||||
std::shared_ptr<ThreadSafeFunction> openCb_;
|
||||
|
||||
void Send(const Napi::CallbackInfo& info) {
|
||||
std::string msg = info[0].As<String>().Utf8Value();
|
||||
if (dc_) dc_->send(msg);
|
||||
}
|
||||
|
||||
Napi::Value IsOpen(const Napi::CallbackInfo& info) {
|
||||
bool open = dc_ && dc_->isOpen();
|
||||
return Boolean::New(info.Env(), open);
|
||||
}
|
||||
|
||||
void Close(const Napi::CallbackInfo& info) {
|
||||
if (dc_) dc_->close();
|
||||
}
|
||||
|
||||
void OnMessage(const Napi::CallbackInfo& info) {
|
||||
Function cb = info[0].As<Function>();
|
||||
msgCb_ = std::make_shared<ThreadSafeFunction>(
|
||||
ThreadSafeFunction::New(info.Env(), cb, "dc-message", 0, 1));
|
||||
}
|
||||
|
||||
void OnOpen(const Napi::CallbackInfo& info) {
|
||||
Function cb = info[0].As<Function>();
|
||||
openCb_ = std::make_shared<ThreadSafeFunction>(
|
||||
ThreadSafeFunction::New(info.Env(), cb, "dc-open", 0, 1));
|
||||
}
|
||||
};
|
||||
|
||||
class TrackWrap : public Napi::ObjectWrap<TrackWrap> {
|
||||
public:
|
||||
static Function Init(Napi::Env env) {
|
||||
Function func = DefineClass(env, "Track", {
|
||||
InstanceMethod("send", &TrackWrap::Send),
|
||||
InstanceMethod("isOpen", &TrackWrap::IsOpen),
|
||||
InstanceMethod("close", &TrackWrap::Close),
|
||||
InstanceMethod("setPacketizer", &TrackWrap::SetPacketizer),
|
||||
InstanceMethod("sendFrame", &TrackWrap::SendFrame),
|
||||
InstanceMethod("addTimestamp", &TrackWrap::AddTimestamp),
|
||||
});
|
||||
trackConstructor = Napi::Persistent(func);
|
||||
return func;
|
||||
}
|
||||
|
||||
static Object NewInstance(Napi::Env env) {
|
||||
return trackConstructor.New({});
|
||||
}
|
||||
|
||||
TrackWrap(const Napi::CallbackInfo& info)
|
||||
: Napi::ObjectWrap<TrackWrap>(info) {}
|
||||
|
||||
void Init(std::shared_ptr<rtc::Track> track, Napi::Env env) {
|
||||
track_ = track;
|
||||
(void)env;
|
||||
}
|
||||
|
||||
private:
|
||||
static FunctionReference trackConstructor;
|
||||
std::shared_ptr<rtc::Track> track_;
|
||||
std::shared_ptr<rtc::RtpPacketizationConfig> rtpConfig_;
|
||||
|
||||
void Send(const Napi::CallbackInfo& info) {
|
||||
Buffer<uint8_t> buf = info[0].As<Buffer<uint8_t>>();
|
||||
if (!track_) return;
|
||||
rtc::binary data(buf.Length());
|
||||
for (size_t i = 0; i < buf.Length(); i++) data[i] = (std::byte)buf[i];
|
||||
try {
|
||||
track_->send(data);
|
||||
} catch (const std::exception& e) {
|
||||
fprintf(stderr, "[binding] track.send THREW: %s\n", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
// setPacketizer(kind, ssrc, payloadType, clockRate, playoutDelayId,
|
||||
// playoutDelayMin, playoutDelayMax)
|
||||
// kind: "audio" | "h264" | "h265" | "av1"
|
||||
// Builds the media-handler chain (packetizer → RTCP SR → NACK → pacing for
|
||||
// video) exactly like @dank074's WebRtcWrapper does via node-datachannel.
|
||||
void SetPacketizer(const Napi::CallbackInfo& info) {
|
||||
Napi::Env env = info.Env();
|
||||
if (!track_) throw Error::New(env, "track closed");
|
||||
std::string kind = info[0].As<String>().Utf8Value();
|
||||
uint32_t ssrc = info[1].As<Number>().Uint32Value();
|
||||
uint8_t pt = (uint8_t)info[2].As<Number>().Uint32Value();
|
||||
uint32_t clockRate = info[3].As<Number>().Uint32Value();
|
||||
uint8_t playoutDelayId = (uint8_t)info[4].As<Number>().Uint32Value();
|
||||
uint16_t playoutDelayMin = (uint16_t)info[5].As<Number>().Uint32Value();
|
||||
uint16_t playoutDelayMax = (uint16_t)info[6].As<Number>().Uint32Value();
|
||||
try {
|
||||
auto cfg = std::make_shared<rtc::RtpPacketizationConfig>(
|
||||
ssrc, "", pt, clockRate);
|
||||
cfg->playoutDelayId = playoutDelayId;
|
||||
cfg->playoutDelayMin = playoutDelayMin;
|
||||
cfg->playoutDelayMax = playoutDelayMax;
|
||||
std::shared_ptr<rtc::MediaHandler> handler;
|
||||
if (kind == "audio") {
|
||||
handler = std::make_shared<rtc::OpusRtpPacketizer>(cfg);
|
||||
} else if (kind == "h264") {
|
||||
handler = std::make_shared<rtc::H264RtpPacketizer>(
|
||||
rtc::NalUnit::Separator::StartSequence, cfg);
|
||||
} else if (kind == "h265") {
|
||||
handler = std::make_shared<rtc::H265RtpPacketizer>(
|
||||
rtc::NalUnit::Separator::StartSequence, cfg);
|
||||
} else if (kind == "av1") {
|
||||
handler = std::make_shared<rtc::AV1RtpPacketizer>(
|
||||
rtc::AV1RtpPacketizer::Packetization::Obu, cfg);
|
||||
} else {
|
||||
throw std::runtime_error("unknown packetizer kind: " + kind);
|
||||
}
|
||||
handler->addToChain(std::make_shared<rtc::RtcpSrReporter>(cfg));
|
||||
handler->addToChain(std::make_shared<rtc::RtcpNackResponder>());
|
||||
if (kind != "audio") {
|
||||
handler->addToChain(std::make_shared<rtc::PacingHandler>(
|
||||
25.0 * 1000 * 1000, std::chrono::milliseconds(1)));
|
||||
}
|
||||
track_->setMediaHandler(handler);
|
||||
rtpConfig_ = cfg;
|
||||
} catch (const std::exception& e) {
|
||||
fprintf(stderr, "[binding] setPacketizer THREW: %s\n", e.what());
|
||||
throw Error::New(env, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
// sendFrame(buffer) — sends an ENCODED frame (AnnexB H264 / raw opus /
|
||||
// OBU AV1). The media-handler chain packetizes it into RTP.
|
||||
void SendFrame(const Napi::CallbackInfo& info) {
|
||||
Buffer<uint8_t> buf = info[0].As<Buffer<uint8_t>>();
|
||||
if (!track_) return;
|
||||
rtc::binary data(buf.Length());
|
||||
for (size_t i = 0; i < buf.Length(); i++) data[i] = (std::byte)buf[i];
|
||||
try {
|
||||
track_->send(data);
|
||||
} catch (const std::exception& e) {
|
||||
fprintf(stderr, "[binding] track.sendFrame THREW: %s\n", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
// addTimestamp(delta) — advances the packetizer RTP timestamp by delta
|
||||
// (clock-rate units). Called by JS after each frame, matching the
|
||||
// node-datachannel contract (WebRtcWrapper does the same increment).
|
||||
void AddTimestamp(const Napi::CallbackInfo& info) {
|
||||
uint32_t delta = info[0].As<Number>().Uint32Value();
|
||||
if (rtpConfig_) rtpConfig_->timestamp += delta;
|
||||
}
|
||||
|
||||
Napi::Value IsOpen(const Napi::CallbackInfo& info) {
|
||||
bool open = track_ && track_->isOpen();
|
||||
return Boolean::New(info.Env(), open);
|
||||
}
|
||||
|
||||
void Close(const Napi::CallbackInfo& info) {
|
||||
if (track_) track_->close();
|
||||
}
|
||||
|
||||
void OnStateChange(const Napi::CallbackInfo& info) {
|
||||
// libdatachannel Track has no state-change callback; kept for API parity.
|
||||
(void)info;
|
||||
}
|
||||
};
|
||||
class PeerConnectionWrap : public Napi::ObjectWrap<PeerConnectionWrap> {
|
||||
public:
|
||||
static Function Init(Napi::Env env) {
|
||||
Function func = DefineClass(env, "PeerConnection", {
|
||||
InstanceMethod("state", &PeerConnectionWrap::State),
|
||||
InstanceMethod("createOffer", &PeerConnectionWrap::CreateOffer),
|
||||
InstanceMethod("createAnswer", &PeerConnectionWrap::CreateAnswer),
|
||||
InstanceMethod("setRemoteDescription",
|
||||
&PeerConnectionWrap::SetRemoteDescription),
|
||||
InstanceMethod("close", &PeerConnectionWrap::Close),
|
||||
InstanceMethod("onStateChange", &PeerConnectionWrap::OnStateChange),
|
||||
InstanceMethod("createDataChannel", &PeerConnectionWrap::CreateDataChannel),
|
||||
InstanceMethod("onDataChannel", &PeerConnectionWrap::OnDataChannel),
|
||||
InstanceMethod("addTrack", &PeerConnectionWrap::AddTrack),
|
||||
});
|
||||
return func;
|
||||
}
|
||||
|
||||
PeerConnectionWrap(const Napi::CallbackInfo& info)
|
||||
: Napi::ObjectWrap<PeerConnectionWrap>(info) {
|
||||
Napi::Env env = info.Env();
|
||||
if (!info[0].IsObject()) {
|
||||
throw TypeError::New(env, "config object required");
|
||||
}
|
||||
Object config = info[0].As<Object>();
|
||||
rtc::Configuration rtcConfig;
|
||||
if (config.Has("iceServers")) {
|
||||
Array servers = config.Get("iceServers").As<Array>();
|
||||
for (uint32_t i = 0; i < servers.Length(); i++) {
|
||||
std::string url = servers.Get(i).As<String>().Utf8Value();
|
||||
rtcConfig.iceServers.emplace_back(url);
|
||||
}
|
||||
}
|
||||
pc_ = std::make_shared<rtc::PeerConnection>(rtcConfig);
|
||||
|
||||
// IMPORTANT: register description/gathering callbacks HERE (constructor),
|
||||
// BEFORE any createDataChannel call. libdatachannel only fires
|
||||
// onLocalDescription for negotiations that start AFTER the callback is
|
||||
// registered — if createDataChannel runs first, the offer callback never
|
||||
// fires (verified in C++ spike: test3 vs test2).
|
||||
pc_->onLocalDescription([this](rtc::Description desc) {
|
||||
latestLocalDesc_ = std::string(desc);
|
||||
fprintf(stderr, "[binding] trickle desc, %zu bytes\n",
|
||||
latestLocalDesc_.size());
|
||||
});
|
||||
pc_->onGatheringStateChange([this](rtc::PeerConnection::GatheringState gs) {
|
||||
fprintf(stderr, "[binding] gathering state: %d\n", (int)gs);
|
||||
if (gs == rtc::PeerConnection::GatheringState::Complete) {
|
||||
// Use the getter — it returns the FULL SDP including candidates after
|
||||
// gathering (trickle callbacks only carry the initial fragment).
|
||||
auto ld = pc_->localDescription();
|
||||
if (ld) {
|
||||
latestLocalDesc_ = std::string(*ld);
|
||||
fprintf(stderr, "[binding] final desc, %zu bytes\n",
|
||||
latestLocalDesc_.size());
|
||||
}
|
||||
resolvePendingLocalDesc_();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<rtc::PeerConnection> pc_;
|
||||
std::shared_ptr<ThreadSafeFunction> stateCb_;
|
||||
std::shared_ptr<ThreadSafeFunction> dcCb_;
|
||||
std::string latestLocalDesc_;
|
||||
std::shared_ptr<DeferredHolder> pendingDescDeferred_;
|
||||
std::shared_ptr<ThreadSafeFunction> pendingDescTsfn_;
|
||||
|
||||
void resolvePendingLocalDesc_() {
|
||||
if (!pendingDescDeferred_ || !pendingDescTsfn_) return;
|
||||
auto holder = pendingDescDeferred_;
|
||||
auto tsfn = pendingDescTsfn_;
|
||||
pendingDescDeferred_.reset();
|
||||
pendingDescTsfn_.reset();
|
||||
std::string sdp = latestLocalDesc_;
|
||||
tsfn->BlockingCall([sdp, holder](Napi::Env e, Function) {
|
||||
holder->deferred.Resolve(String::New(e, sdp));
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value State(const Napi::CallbackInfo& info) {
|
||||
return String::New(info.Env(),
|
||||
pc_ ? stateToString(pc_->state()) : "closed");
|
||||
}
|
||||
|
||||
// createOffer() -> Promise<string> — sets local description, waits for
|
||||
// ICE gathering to complete (so candidates are in the SDP), resolves SDP.
|
||||
Napi::Value CreateOffer(const Napi::CallbackInfo& info) {
|
||||
Napi::Env env = info.Env();
|
||||
auto holder = std::make_shared<DeferredHolder>(Promise::Deferred::New(env));
|
||||
if (!pc_) {
|
||||
holder->deferred.Reject(Error::New(env, "peer closed").Value());
|
||||
return holder->deferred.Promise();
|
||||
}
|
||||
// createDataChannel already triggers negotiation in libdatachannel 0.24 —
|
||||
// if gathering already completed, resolve immediately from the cached SDP.
|
||||
if (!latestLocalDesc_.empty()) {
|
||||
auto tsfn = std::make_shared<ThreadSafeFunction>(ThreadSafeFunction::New(
|
||||
env, Function::New(env, [](const CallbackInfo&) {}), "desc", 0, 1));
|
||||
std::string sdp = latestLocalDesc_;
|
||||
tsfn->BlockingCall([sdp, holder](Napi::Env e, Function) {
|
||||
holder->deferred.Resolve(String::New(e, sdp));
|
||||
});
|
||||
return holder->deferred.Promise();
|
||||
}
|
||||
if (pendingDescDeferred_) {
|
||||
pendingDescDeferred_->deferred.Reject(
|
||||
Error::New(env, "previous negotiation still pending").Value());
|
||||
}
|
||||
pendingDescDeferred_ = holder;
|
||||
pendingDescTsfn_ = std::make_shared<ThreadSafeFunction>(
|
||||
ThreadSafeFunction::New(env, Function::New(env, [](const CallbackInfo&) {}),
|
||||
"desc", 0, 1));
|
||||
fprintf(stderr, "[binding] calling setLocalDescription(Offer)\n");
|
||||
try {
|
||||
pc_->setLocalDescription(rtc::Description::Type::Offer);
|
||||
fprintf(stderr, "[binding] setLocalDescription returned OK\n");
|
||||
} catch (const std::exception& e) {
|
||||
pendingDescDeferred_.reset();
|
||||
fprintf(stderr, "[binding] setLocalDescription THREW: %s\n", e.what());
|
||||
throw Error::New(env, e.what());
|
||||
}
|
||||
return holder->deferred.Promise();
|
||||
}
|
||||
|
||||
// createAnswer(offerSdp: string) -> Promise<string>
|
||||
Napi::Value CreateAnswer(const Napi::CallbackInfo& info) {
|
||||
Napi::Env env = info.Env();
|
||||
std::string offer = info[0].As<String>().Utf8Value();
|
||||
auto holder = std::make_shared<DeferredHolder>(Promise::Deferred::New(env));
|
||||
if (!pc_) {
|
||||
holder->deferred.Reject(Error::New(env, "peer closed").Value());
|
||||
return holder->deferred.Promise();
|
||||
}
|
||||
if (pendingDescDeferred_) {
|
||||
pendingDescDeferred_->deferred.Reject(
|
||||
Error::New(env, "previous negotiation still pending").Value());
|
||||
}
|
||||
pendingDescDeferred_ = holder;
|
||||
pendingDescTsfn_ = std::make_shared<ThreadSafeFunction>(
|
||||
ThreadSafeFunction::New(env, Function::New(env, [](const CallbackInfo&) {}),
|
||||
"desc", 0, 1));
|
||||
try {
|
||||
pc_->setRemoteDescription(
|
||||
rtc::Description(offer, rtc::Description::Type::Offer));
|
||||
fprintf(stderr, "[binding] answer: setRemoteDescription OK\n");
|
||||
// libdatachannel 0.24 AUTO-GENERATES the answer when a remote offer is
|
||||
// applied (verified in C++ spike test8/9: B desc type=Answer fires
|
||||
// immediately with a=setup:active). Calling setLocalDescription() again
|
||||
// would OVERWRITE it with a role=actpass SDP, which A rejects with
|
||||
// "Illegal role actpass in remote answer description". So we do NOT call
|
||||
// setLocalDescription here — we just wait for gathering complete and
|
||||
// resolve with the auto-generated answer. This also matches @dank074's
|
||||
// Discord voice flow.
|
||||
} catch (const std::exception& e) {
|
||||
pendingDescDeferred_.reset();
|
||||
fprintf(stderr, "[binding] answer THREW: %s\n", e.what());
|
||||
holder->deferred.Reject(Error::New(env, e.what()).Value());
|
||||
}
|
||||
return holder->deferred.Promise();
|
||||
}
|
||||
|
||||
void SetRemoteDescription(const Napi::CallbackInfo& info) {
|
||||
std::string sdp = info[0].As<String>().Utf8Value();
|
||||
std::string type = info[1].As<String>().Utf8Value();
|
||||
rtc::Description::Type t = (type == "answer")
|
||||
? rtc::Description::Type::Answer
|
||||
: rtc::Description::Type::Offer;
|
||||
if (pc_) pc_->setRemoteDescription(rtc::Description(sdp, t));
|
||||
}
|
||||
|
||||
void Close(const Napi::CallbackInfo& info) {
|
||||
if (pc_) pc_->close();
|
||||
}
|
||||
|
||||
void OnStateChange(const Napi::CallbackInfo& info) {
|
||||
Function cb = info[0].As<Function>();
|
||||
stateCb_ = std::make_shared<ThreadSafeFunction>(
|
||||
ThreadSafeFunction::New(info.Env(), cb, "pc-state", 0, 1));
|
||||
std::shared_ptr<rtc::PeerConnection> pc = pc_;
|
||||
pc->onStateChange([this](rtc::PeerConnection::State state) {
|
||||
if (stateCb_) {
|
||||
std::string s = stateToString(state);
|
||||
stateCb_->BlockingCall([s](Napi::Env env, Function cb) {
|
||||
cb.Call({String::New(env, s)});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value CreateDataChannel(const Napi::CallbackInfo& info) {
|
||||
Napi::Env env = info.Env();
|
||||
std::string label = info[0].As<String>().Utf8Value();
|
||||
fprintf(stderr, "[binding] createDataChannel(%s)\n", label.c_str());
|
||||
auto dc = pc_->createDataChannel(label);
|
||||
Object obj = DataChannelWrap::NewInstance(env);
|
||||
DataChannelWrap::Unwrap(obj)->Init(dc);
|
||||
return obj;
|
||||
}
|
||||
|
||||
Napi::Value AddTrack(const Napi::CallbackInfo& info) {
|
||||
Napi::Env env = info.Env();
|
||||
std::string mid = info[0].As<String>().Utf8Value();
|
||||
std::string kind = info[1].As<String>().Utf8Value();
|
||||
if (!pc_) throw Error::New(env, "peer closed");
|
||||
fprintf(stderr, "[binding] addTrack(%s, %s) start\n", mid.c_str(), kind.c_str());
|
||||
try {
|
||||
std::shared_ptr<rtc::Track> track;
|
||||
if (kind == "audio") {
|
||||
// Opus payload type 120 (matches @dank074 CodecPayloadType.opus)
|
||||
auto desc = rtc::Description::Audio(mid);
|
||||
desc.addOpusCodec(120);
|
||||
track = pc_->addTrack(desc);
|
||||
} else {
|
||||
// All video codecs with their payload types, matching WebRtcWrapper:
|
||||
// H264 101/102, H265 103/104, VP8 105/106, VP9 107/108, AV1 109/110
|
||||
auto desc = rtc::Description::Video(mid);
|
||||
desc.addH264Codec(101);
|
||||
desc.addRtxCodec(102, 101, 90000);
|
||||
desc.addH265Codec(103);
|
||||
desc.addRtxCodec(104, 103, 90000);
|
||||
desc.addVP8Codec(105);
|
||||
desc.addRtxCodec(106, 105, 90000);
|
||||
desc.addVP9Codec(107);
|
||||
desc.addRtxCodec(108, 107, 90000);
|
||||
desc.addAV1Codec(109);
|
||||
desc.addRtxCodec(110, 109, 90000);
|
||||
track = pc_->addTrack(desc);
|
||||
}
|
||||
Object obj = TrackWrap::NewInstance(env);
|
||||
TrackWrap::Unwrap(obj)->Init(track, env);
|
||||
return obj;
|
||||
} catch (const std::exception& e) {
|
||||
fprintf(stderr, "[binding] addTrack THREW: %s\n", e.what());
|
||||
throw Error::New(env, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void OnDataChannel(const Napi::CallbackInfo& info) {
|
||||
Function cb = info[0].As<Function>();
|
||||
dcCb_ = std::make_shared<ThreadSafeFunction>(
|
||||
ThreadSafeFunction::New(info.Env(), cb, "dc", 0, 1));
|
||||
std::shared_ptr<rtc::PeerConnection> pc = pc_;
|
||||
pc->onDataChannel([this](std::shared_ptr<rtc::DataChannel> dc) {
|
||||
if (dcCb_) {
|
||||
auto dcPtr = dc;
|
||||
dcCb_->BlockingCall([dcPtr](Napi::Env env, Function cb) {
|
||||
Object obj = DataChannelWrap::NewInstance(env);
|
||||
DataChannelWrap::Unwrap(obj)->Init(dcPtr);
|
||||
cb.Call({obj});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Object InitAll(Napi::Env env, Object exports) {
|
||||
exports.Set("PeerConnection", PeerConnectionWrap::Init(env));
|
||||
exports.Set("DataChannel", DataChannelWrap::Init(env));
|
||||
exports.Set("Track", TrackWrap::Init(env));
|
||||
return exports;
|
||||
}
|
||||
|
||||
NODE_API_MODULE(libdatachannel_min, InitAll)
|
||||
|
||||
// Definition for the static constructor references.
|
||||
FunctionReference DataChannelWrap::dcConstructor;
|
||||
FunctionReference TrackWrap::trackConstructor;
|
||||
|
||||
} // namespace
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"targets": [
|
||||
{
|
||||
"target_name": "libdatachannel_min",
|
||||
"sources": ["binding.cpp"],
|
||||
"include_dirs": [
|
||||
"<!(node -e \"console.log(process.env.NAPI_INCLUDE || (() => { try { return require('node-addon-api').include; } catch { return '/nonexistent'; } })())\")",
|
||||
"<!(node -e \"const s=process.env.LDC_INCLUDE||'/nix/store/39a85gpfjqy3h3k8jwrwh7m9yc3inqw7-source';console.log(s+'/include')\")"
|
||||
],
|
||||
"libraries": [
|
||||
"<!(node -e \"console.log(process.env.LDC_LIB || '/tmp/ldc-build/libdatachannel.so.0.24.0')\")"
|
||||
],
|
||||
"cflags": ["-std=c++17", "-fexceptions"],
|
||||
"cflags_cc": ["-std=c++17", "-fexceptions"],
|
||||
"defines": ["NAPI_CPP_EXCEPTIONS"],
|
||||
"conditions": [
|
||||
["OS=='linux'", { "cflags": ["-fvisibility=hidden"] }]
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
// libdatachannel-min — JS entry.
|
||||
const native = require("./build/Release/datachannel_min.node");
|
||||
module.exports = native;
|
||||
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"name": "libdatachannel-min",
|
||||
"version": "0.1.0",
|
||||
"description": "Minimal N-API binding to libdatachannel — PeerConnection, DataChannel, ICE, SDP (+ media tracks for GoLive)",
|
||||
"main": "index.js",
|
||||
"gypfile": true,
|
||||
"scripts": {
|
||||
"build": "node-gyp rebuild",
|
||||
"test": "node test-handshake.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"node-addon-api": "^8.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"node-gyp": "^11.5.0"
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
// Phase 0 spike: prove the minimal binding can do a full WebRTC handshake
|
||||
// (offer/answer + ICE + DataChannel) between two local PeerConnections.
|
||||
"use strict";
|
||||
const { PeerConnection } = require("./build/Release/datachannel_min.node");
|
||||
|
||||
function log(...args) {
|
||||
console.log("[spike]", ...args);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const pcA = new PeerConnection({ iceServers: [] });
|
||||
const pcB = new PeerConnection({ iceServers: [] });
|
||||
|
||||
const stateLog = [];
|
||||
pcA.onStateChange((s) => {
|
||||
stateLog.push(`A:${s}`);
|
||||
log("A state:", s);
|
||||
});
|
||||
pcB.onStateChange((s) => {
|
||||
stateLog.push(`B:${s}`);
|
||||
log("B state:", s);
|
||||
});
|
||||
|
||||
// B waits for incoming DataChannel
|
||||
const received = new Promise((resolve) => {
|
||||
pcB.onDataChannel((dc) => {
|
||||
log("B got incoming DataChannel");
|
||||
dc.onOpen(() => log("B DataChannel open"));
|
||||
dc.onMessage((msg) => {
|
||||
log("B received message:", msg);
|
||||
dc.send("pong from B");
|
||||
resolve(msg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// A creates an outgoing DataChannel
|
||||
const dcA = pcA.createDataChannel("test");
|
||||
dcA.onOpen(() => {
|
||||
log("A DataChannel open — sending hello");
|
||||
dcA.send("hello from A");
|
||||
});
|
||||
dcA.onMessage((msg) => {
|
||||
log("A received reply:", msg);
|
||||
});
|
||||
|
||||
// Offer/answer dance
|
||||
log("A createOffer...");
|
||||
const offer = await pcA.createOffer();
|
||||
log("Offer SDP bytes:", offer.length);
|
||||
log("B createAnswer...");
|
||||
const answer = await pcB.createAnswer(offer);
|
||||
log("Answer SDP bytes:", answer.length);
|
||||
const setupMatch = answer.match(/a=setup:(\S+)/);
|
||||
log("Answer setup role:", setupMatch ? setupMatch[1] : "NONE");
|
||||
pcA.setRemoteDescription(answer, "answer");
|
||||
|
||||
// Wait for message roundtrip
|
||||
const msg = await Promise.race([
|
||||
received,
|
||||
new Promise((_, rej) => setTimeout(() => rej(new Error("TIMEOUT waiting for datachannel message")), 15000)),
|
||||
]);
|
||||
|
||||
log("ROUNDTRIP OK — B got:", msg);
|
||||
log("States:", stateLog.join(" | "));
|
||||
|
||||
const aState = pcA.state();
|
||||
const bState = pcB.state();
|
||||
log("Final states — A:", aState, "B:", bState);
|
||||
|
||||
pcA.close();
|
||||
pcB.close();
|
||||
|
||||
if (msg !== "hello from A") throw new Error("wrong message");
|
||||
if (aState !== "connected" && aState !== "disconnected") throw new Error("A not connected: " + aState);
|
||||
log("SPIKE PASSED ✅");
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error("SPIKE FAILED:", e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,80 +0,0 @@
|
||||
// Verify setPacketizer + sendFrame: two peers connect, audio+video tracks
|
||||
// packetize real encoded frames (opus + AnnexB H264), RTP flows without crash.
|
||||
"use strict";
|
||||
const { PeerConnection } = require("./build/Release/datachannel_min.node");
|
||||
|
||||
function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }
|
||||
|
||||
async function main() {
|
||||
const pcA = new PeerConnection({ iceServers: [] });
|
||||
const pcB = new PeerConnection({ iceServers: [] });
|
||||
|
||||
const aAudio = pcA.addTrack("0", "audio");
|
||||
const aVideo = pcA.addTrack("1", "video");
|
||||
pcB.addTrack("0", "audio");
|
||||
pcB.addTrack("1", "video");
|
||||
|
||||
let states = { a: "", b: "" };
|
||||
pcA.onStateChange((s) => (states.a = s));
|
||||
pcB.onStateChange((s) => (states.b = s));
|
||||
|
||||
// A: offer (createDataChannel not needed — tracks trigger negotiation)
|
||||
const offer = await pcA.createOffer();
|
||||
pcB.setRemoteDescription(offer, "offer");
|
||||
const answer = await pcB.createAnswer(offer);
|
||||
pcA.setRemoteDescription(answer, "answer");
|
||||
|
||||
// Wait for connected
|
||||
for (let i = 0; i < 50; i++) {
|
||||
if (states.a === "connected" && states.b === "connected") break;
|
||||
await sleep(100);
|
||||
}
|
||||
console.log("[pkt] states:", states.a, states.b);
|
||||
if (states.a !== "connected" || states.b !== "connected") {
|
||||
console.log("PKT TEST FAILED: not connected");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Setup packetizers on A (sender)
|
||||
aAudio.setPacketizer("audio", 1234, 120, 48000, 5, 0, 1);
|
||||
aVideo.setPacketizer("h264", 5678, 101, 90000, 5, 0, 10);
|
||||
|
||||
// Fake opus frame (20ms @48kHz stereo — payload can be any bytes)
|
||||
const opusFrame = Buffer.alloc(160);
|
||||
for (let i = 0; i < 160; i++) opusFrame[i] = i & 0xff;
|
||||
|
||||
// Fake AnnexB H264 frame: SPS + PPS + IDR slice
|
||||
const sps = Buffer.from([0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xc0, 0x1e, 0xd9, 0x01, 0x40, 0x7e]);
|
||||
const pps = Buffer.from([0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x3c, 0x80]);
|
||||
const idr = Buffer.from([0x00, 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]);
|
||||
const h264Frame = Buffer.concat([sps, pps, idr]);
|
||||
|
||||
// Send 10 audio frames (20ms each) + 3 video frames (33ms each)
|
||||
for (let i = 0; i < 10; i++) {
|
||||
aAudio.sendFrame(opusFrame);
|
||||
aAudio.addTimestamp(960); // 20ms @ 48kHz
|
||||
}
|
||||
for (let i = 0; i < 3; i++) {
|
||||
aVideo.sendFrame(h264Frame);
|
||||
aVideo.addTimestamp(3000); // 33ms @ 90kHz
|
||||
}
|
||||
|
||||
await sleep(500);
|
||||
console.log("[pkt] after send: states:", states.a, states.b);
|
||||
console.log("[pkt] audio track open:", aAudio.isOpen(), "| video track open:", aVideo.isOpen());
|
||||
const ok = states.a === "connected" && aAudio.isOpen() && aVideo.isOpen();
|
||||
console.log(ok ? "PKT TEST PASSED" : "PKT TEST FAILED");
|
||||
pcA.close();
|
||||
pcB.close();
|
||||
process.exit(ok ? 0 : 1);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error("[pkt] FAILED:", e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
console.error("[pkt] TIMEOUT");
|
||||
process.exit(1);
|
||||
}, 25000);
|
||||
@@ -1,138 +0,0 @@
|
||||
// Two-peer RTP capture test: A sends REAL H264 frames through the binding's
|
||||
// packetizer chain to B over localhost. tcpdump (run externally on lo) captures
|
||||
// the RTP; a Python script reassembles AnnexB and ffmpeg decodes it.
|
||||
//
|
||||
// Usage:
|
||||
// node test-rtp-capture.js <mode> mode = "a" (sender) | "b" (receiver)
|
||||
// Sender writes the negotiated SDP pieces to /tmp/rtp-a.sdp /tmp/rtp-b.sdp
|
||||
// Receiver listens and keeps alive.
|
||||
"use strict";
|
||||
const { PeerConnection } = require("./build/Release/datachannel_min.node");
|
||||
const fs = require("fs");
|
||||
|
||||
const mode = process.argv[2] || "a";
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
async function main() {
|
||||
const pc = new PeerConnection({ iceServers: [] });
|
||||
const audio = pc.addTrack("0", "audio");
|
||||
const video = pc.addTrack("1", "video");
|
||||
|
||||
if (mode === "a") {
|
||||
// Sender: generate offer, hand to B via files, get B's answer
|
||||
const offer = await pc.createOffer();
|
||||
fs.writeFileSync("/tmp/rtp-offer.sdp", offer);
|
||||
console.log("[a] offer written", offer.length, "bytes");
|
||||
|
||||
// wait for B to write its answer
|
||||
for (let i = 0; i < 300; i++) {
|
||||
if (fs.existsSync("/tmp/rtp-answer.sdp")) break;
|
||||
await sleep(200);
|
||||
}
|
||||
const answer = fs.readFileSync("/tmp/rtp-answer.sdp", "utf8");
|
||||
pc.setRemoteDescription(answer, "answer");
|
||||
|
||||
// wait connected
|
||||
for (let i = 0; i < 50; i++) {
|
||||
if (pc.state() === "connected") break;
|
||||
await sleep(100);
|
||||
}
|
||||
console.log("[a] state:", pc.state());
|
||||
if (pc.state() !== "connected") {
|
||||
console.log("[a] FAILED not connected");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Setup packetizer like the gateway does
|
||||
video.setPacketizer("h264", 5678, 101, 90000, 5, 0, 10);
|
||||
|
||||
// Real H264 AnnexB (baseline) — read from file created by ffmpeg
|
||||
const data = fs.readFileSync("/tmp/rtp-input.h264");
|
||||
console.log("[a] input h264 bytes:", data.length);
|
||||
|
||||
// Split into NAL units by start codes, then group into access units
|
||||
// the same way Demuxer does (param sets + one slice per frame).
|
||||
const start3 = Buffer.from([0, 0, 1]);
|
||||
const start4 = Buffer.from([0, 0, 0, 1]);
|
||||
const nals = [];
|
||||
let i = 0;
|
||||
while (i < data.length) {
|
||||
let start = -1;
|
||||
let startLen = 0;
|
||||
for (let j = i; j < data.length - 3; j++) {
|
||||
if (data[j] === 0 && data[j + 1] === 0 && data[j + 2] === 1) {
|
||||
start = j;
|
||||
startLen = 3;
|
||||
if (j > 0 && data[j - 1] === 0) {
|
||||
start = j - 1;
|
||||
startLen = 4;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (start === -1) break;
|
||||
if (start > i) {
|
||||
nals.push(data.subarray(i, start));
|
||||
}
|
||||
i = start + startLen;
|
||||
}
|
||||
console.log("[a] NALs:", nals.length);
|
||||
|
||||
// Group: buffer param sets, flush on slice (like Demuxer.flushAccessUnit)
|
||||
let pending = [];
|
||||
let frameCount = 0;
|
||||
const flush = () => {
|
||||
if (pending.length === 0) return;
|
||||
const parts = pending.map((n) => Buffer.concat([start4, n]));
|
||||
const au = Buffer.concat(parts);
|
||||
pending = [];
|
||||
video.sendFrame(au);
|
||||
video.addTimestamp(3000); // 30fps @ 90kHz
|
||||
frameCount++;
|
||||
};
|
||||
for (const n of nals) {
|
||||
const t = n[0] & 0x1f;
|
||||
if (t === 1 || t === 5) {
|
||||
flush(); // previous AU closed by this slice
|
||||
pending.push(n);
|
||||
} else {
|
||||
pending.push(n); // param set / SEI
|
||||
}
|
||||
}
|
||||
flush();
|
||||
console.log("[a] sent frames:", frameCount);
|
||||
await sleep(3000); // let packets flow
|
||||
console.log("[a] done");
|
||||
pc.close();
|
||||
process.exit(0);
|
||||
} else {
|
||||
// Receiver: read offer, answer, keep alive
|
||||
for (let i = 0; i < 300; i++) {
|
||||
if (fs.existsSync("/tmp/rtp-offer.sdp")) break;
|
||||
await sleep(200);
|
||||
}
|
||||
const offer = fs.readFileSync("/tmp/rtp-offer.sdp", "utf8");
|
||||
pc.setRemoteDescription(offer, "offer");
|
||||
const answer = await pc.createAnswer(offer);
|
||||
fs.writeFileSync("/tmp/rtp-answer.sdp", answer);
|
||||
console.log("[b] answer written");
|
||||
for (let i = 0; i < 50; i++) {
|
||||
if (pc.state() === "connected") break;
|
||||
await sleep(100);
|
||||
}
|
||||
console.log("[b] state:", pc.state());
|
||||
await sleep(10000); // hold while sender streams
|
||||
console.log("[b] done");
|
||||
pc.close();
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error("FAILED:", e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
setTimeout(() => {
|
||||
console.error("TIMEOUT");
|
||||
process.exit(1);
|
||||
}, 30000);
|
||||
@@ -1,33 +0,0 @@
|
||||
// Verify addTrack produces SDP with audio+video media sections.
|
||||
"use strict";
|
||||
const { PeerConnection } = require("./build/Release/datachannel_min.node");
|
||||
|
||||
const pc = new PeerConnection({ iceServers: [] });
|
||||
const audioTrack = pc.addTrack("0", "audio");
|
||||
const videoTrack = pc.addTrack("1", "video");
|
||||
|
||||
pc.onStateChange((s) => console.log("[test-track] state:", s));
|
||||
|
||||
pc.createOffer().then((sdp) => {
|
||||
const hasAudio = /^m=audio\s/m.test(sdp);
|
||||
const hasVideo = /^m=video\s/m.test(sdp);
|
||||
const audioPts = sdp.match(/a=rtpmap:(\d+) opus/g) || [];
|
||||
const videoPts = sdp.match(/a=rtpmap:(\d+) H264/g) || [];
|
||||
console.log("[test-track] SDP bytes:", sdp.length);
|
||||
console.log("[test-track] m=audio:", hasAudio, "| m=video:", hasVideo);
|
||||
console.log("[test-track] opus pt:", audioPts, "| H264 pt:", videoPts);
|
||||
console.log("[test-track] audio track send ok:", typeof audioTrack.send === "function");
|
||||
console.log("[test-track] video track send ok:", typeof videoTrack.send === "function");
|
||||
const ok = hasAudio && hasVideo && audioPts.length > 0 && videoPts.length > 0;
|
||||
console.log(ok ? "TRACK TEST PASSED" : "TRACK TEST FAILED");
|
||||
pc.close();
|
||||
process.exit(ok ? 0 : 1);
|
||||
}).catch((e) => {
|
||||
console.error("[test-track] FAILED:", e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
console.error("[test-track] TIMEOUT");
|
||||
process.exit(1);
|
||||
}, 20000);
|
||||
Reference in New Issue
Block a user