feat: add native WebRTC bridge with libdatachannel/rustrtc bindings

This commit is contained in:
2026-02-19 11:38:10 -03:00
parent 3da00503a2
commit d8111dd32a
13 changed files with 7236 additions and 0 deletions

753
deps/rustrtc-capi/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,753 @@
//! rustrtc C API wrapper — drop-in replacement for libdatachannel.
//!
//! Exports the same `rtc*` C symbols so that Zig's `webrtc_native.zig`
//! links against this library with zero code changes.
mod monitors;
mod state;
mod types;
pub mod ws_signaling;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
use std::sync::atomic::Ordering;
use std::sync::Arc;
use rustrtc::config::RtcConfiguration as RustRtcConfig;
use rustrtc::peer_connection::PeerConnection;
use rustrtc::transports::datachannel::DataChannelConfig;
use rustrtc::transports::ice::IceCandidate;
use crate::monitors::*;
use crate::state::*;
use crate::types::*;
// ===========================================================================
// Global
// ===========================================================================
#[no_mangle]
pub extern "C" fn rtcPreload() {
init_runtime();
}
#[no_mangle]
pub extern "C" fn rtcCleanup() {
cleanup();
}
#[no_mangle]
pub extern "C" fn rtcInitLogger(level: c_int, cb: Option<LogCallbackFn>) {
// Simple implementation: if callback provided, store it; otherwise use env_logger
let _ = level;
let _ = cb;
// For now, initialize env_logger for Rust-side logging (best effort)
let _ = env_logger::try_init();
}
// ===========================================================================
// User pointer
// ===========================================================================
#[no_mangle]
pub extern "C" fn rtcSetUserPointer(id: c_int, ptr: *mut c_void) {
set_user_ptr(id, ptr);
}
#[no_mangle]
pub extern "C" fn rtcGetUserPointer(id: c_int) -> *mut c_void {
get_user_ptr(id)
}
// ===========================================================================
// PeerConnection
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcCreatePeerConnection(config: *const RtcConfiguration) -> c_int {
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
let cfg = &*config;
let mut rust_config = RustRtcConfig::default();
// Map ICE servers
if !cfg.ice_servers.is_null() && cfg.ice_servers_count > 0 {
let count = cfg.ice_servers_count as usize;
for i in 0..count {
let server_ptr = *cfg.ice_servers.add(i);
if !server_ptr.is_null() {
if let Ok(s) = CStr::from_ptr(server_ptr).to_str() {
let ice_server = rustrtc::config::IceServer::new(vec![s.to_string()]);
rust_config.ice_servers.push(ice_server);
}
}
}
}
// Map port range
if cfg.port_range_begin > 0 && cfg.port_range_end > 0 {
rust_config.rtp_start_port = Some(cfg.port_range_begin);
rust_config.rtp_end_port = Some(cfg.port_range_end);
}
// Enter runtime context — PeerConnection::new() needs a tokio reactor
let _guard = rt.enter();
let pc = Arc::new(PeerConnection::new(rust_config));
let pc_id = alloc_id();
let disable_auto = cfg.disable_auto_negotiation;
// Spawn PC monitoring tasks
let tasks = spawn_pc_monitors(rt, pc_id, &pc);
let pc_state = PcState::new(pc, disable_auto);
*pc_state.tasks.lock() = tasks;
entries().write().insert(pc_id, Entry::Pc(pc_state));
pc_id
}
#[no_mangle]
pub extern "C" fn rtcClosePeerConnection(pc: c_int) -> c_int {
match with_pc(pc, |pc_state| {
pc_state.pc.close();
}) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcDeletePeerConnection(pc: c_int) -> c_int {
let entry = entries().write().remove(&pc);
match entry {
Some(Entry::Pc(pc_state)) => {
// Abort all monitor tasks
for t in pc_state.tasks.lock().drain(..) {
t.abort();
}
pc_state.pc.close();
RTC_ERR_SUCCESS
}
Some(other) => {
// Put it back — wrong type
entries().write().insert(pc, other);
RTC_ERR_INVALID
}
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// Callback setters (PeerConnection)
// ===========================================================================
#[no_mangle]
pub extern "C" fn rtcSetLocalDescriptionCallback(
pc: c_int,
cb: Option<DescriptionCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_local_description.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetLocalCandidateCallback(
pc: c_int,
cb: Option<CandidateCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_local_candidate.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetStateChangeCallback(
pc: c_int,
cb: Option<StateChangeCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_state_change.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetGatheringStateChangeCallback(
pc: c_int,
cb: Option<GatheringStateCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_gathering_state.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetDataChannelCallback(
pc: c_int,
cb: Option<DataChannelCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_data_channel.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// SDP
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcSetLocalDescription(
pc: c_int,
sdp_type: *const c_char,
) -> c_int {
let (pc_arc, _disable_auto) = match with_pc(pc, |s| (s.pc.clone(), s.disable_auto_negotiation))
{
Some(v) => v,
None => return RTC_ERR_INVALID,
};
let is_answer = if sdp_type.is_null() {
false
} else {
let type_str = CStr::from_ptr(sdp_type).to_str().unwrap_or("");
type_str == "answer"
};
if is_answer {
// Generate answer (assumes remote offer already set)
let pc_clone = pc_arc.clone();
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
let handle = rt.spawn(async move {
match pc_clone.create_answer().await {
Ok(answer) => {
let sdp_string = crate::monitors::inject_max_message_size(&answer.to_sdp_string());
if let Err(e) = pc_clone.set_local_description(answer) {
log::error!("set_local_description (answer) failed: {e}");
return;
}
let sdp_c = match CString::new(sdp_string) {
Ok(c) => c,
Err(_) => return,
};
let type_c = CString::new("answer").unwrap();
with_pc(pc, |s| {
*s.local_sdp.lock() = Some(sdp_c.clone());
*s.local_sdp_type.lock() = Some(type_c.clone());
});
if let Some((Some(cb), ptr)) = get_pc_description_cb(pc) {
cb(pc, sdp_c.as_ptr(), type_c.as_ptr(), ptr);
}
}
Err(e) => log::error!("create_answer failed: {e}"),
}
});
with_pc(pc, |s| s.tasks.lock().push(handle));
} else {
// Generate offer
trigger_offer(pc, pc_arc);
}
RTC_ERR_SUCCESS
}
#[no_mangle]
pub unsafe extern "C" fn rtcSetRemoteDescription(
pc: c_int,
sdp: *const c_char,
sdp_type: *const c_char,
) -> c_int {
if sdp.is_null() {
return RTC_ERR_INVALID;
}
let sdp_str = match CStr::from_ptr(sdp).to_str() {
Ok(s) => s.to_string(),
Err(_) => return RTC_ERR_INVALID,
};
let type_str = if sdp_type.is_null() {
"offer".to_string()
} else {
CStr::from_ptr(sdp_type)
.to_str()
.unwrap_or("offer")
.to_string()
};
let pc_arc = match with_pc(pc, |s| s.pc.clone()) {
Some(v) => v,
None => return RTC_ERR_INVALID,
};
let is_offer = type_str == "offer";
if is_offer {
// Trigger auto-answer: parse remote offer → set remote desc → create answer → fire callback
trigger_answer(pc, pc_arc, sdp_str);
} else {
// It's an answer — just set the remote description
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
let handle = rt.spawn(async move {
let desc = match rustrtc::sdp::SessionDescription::parse(
rustrtc::sdp::SdpType::Answer,
&sdp_str,
) {
Ok(d) => d,
Err(e) => {
log::error!("parse answer SDP failed: {e}");
return;
}
};
if let Err(e) = pc_arc.set_remote_description(desc).await {
log::error!("set_remote_description (answer) failed: {e}");
}
// Cache remote SDP
if let Ok(remote_c) = CString::new(sdp_str) {
with_pc(pc, |s| {
*s.remote_sdp.lock() = Some(remote_c);
});
}
});
with_pc(pc, |s| s.tasks.lock().push(handle));
}
RTC_ERR_SUCCESS
}
#[no_mangle]
pub unsafe extern "C" fn rtcAddRemoteCandidate(
pc: c_int,
cand: *const c_char,
mid: *const c_char,
) -> c_int {
let _ = mid; // mid is typically ignored for data-channel-only connections
if cand.is_null() {
return RTC_ERR_INVALID;
}
let cand_str = match CStr::from_ptr(cand).to_str() {
Ok(s) => s,
Err(_) => return RTC_ERR_INVALID,
};
let pc_arc = match with_pc(pc, |s| s.pc.clone()) {
Some(v) => v,
None => return RTC_ERR_INVALID,
};
match IceCandidate::from_sdp(cand_str) {
Ok(candidate) => match pc_arc.add_ice_candidate(candidate) {
Ok(_) => RTC_ERR_SUCCESS,
Err(e) => {
log::error!("add_ice_candidate failed: {e}");
RTC_ERR_FAILURE
}
},
Err(e) => {
log::error!("parse ICE candidate failed: {e}");
RTC_ERR_FAILURE
}
}
}
#[no_mangle]
pub unsafe extern "C" fn rtcGetLocalDescription(
pc: c_int,
buffer: *mut u8,
size: c_int,
) -> c_int {
if buffer.is_null() || size <= 0 {
return RTC_ERR_INVALID;
}
match with_pc(pc, |s| s.local_sdp.lock().clone()) {
Some(Some(sdp)) => {
let bytes = sdp.as_bytes_with_nul();
let len = bytes.len();
if (size as usize) < len {
return RTC_ERR_TOO_SMALL;
}
std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, len);
len as c_int
}
Some(None) => RTC_ERR_NOT_AVAIL,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub unsafe extern "C" fn rtcGetRemoteDescription(
pc: c_int,
buffer: *mut u8,
size: c_int,
) -> c_int {
if buffer.is_null() || size <= 0 {
return RTC_ERR_INVALID;
}
match with_pc(pc, |s| s.remote_sdp.lock().clone()) {
Some(Some(sdp)) => {
let bytes = sdp.as_bytes_with_nul();
let len = bytes.len();
if (size as usize) < len {
return RTC_ERR_TOO_SMALL;
}
std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, len);
len as c_int
}
Some(None) => RTC_ERR_NOT_AVAIL,
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// DataChannel
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcCreateDataChannel(
pc: c_int,
label: *const c_char,
) -> c_int {
// Create with default DataChannelInit
let default_init = RtcDataChannelInit {
reliability: RtcReliability {
unordered: false,
unreliable: false,
max_packet_life_time: 0,
max_retransmits: 0,
},
protocol: std::ptr::null(),
negotiated: false,
manual_stream: false,
stream: 0,
};
rtcCreateDataChannelEx(pc, label, &default_init)
}
#[no_mangle]
pub unsafe extern "C" fn rtcCreateDataChannelEx(
pc: c_int,
label: *const c_char,
init: *const RtcDataChannelInit,
) -> c_int {
if label.is_null() || init.is_null() {
return RTC_ERR_INVALID;
}
let label_str = match CStr::from_ptr(label).to_str() {
Ok(s) => s.to_string(),
Err(_) => return RTC_ERR_INVALID,
};
let init_ref = &*init;
let protocol = if init_ref.protocol.is_null() {
String::new()
} else {
CStr::from_ptr(init_ref.protocol)
.to_str()
.unwrap_or("")
.to_string()
};
let (pc_arc, disable_auto) = match with_pc(pc, |s| (s.pc.clone(), s.disable_auto_negotiation))
{
Some(v) => v,
None => return RTC_ERR_INVALID,
};
let dc_config = DataChannelConfig {
label: label_str,
protocol,
ordered: !init_ref.reliability.unordered,
max_retransmits: if init_ref.reliability.unreliable && init_ref.reliability.max_retransmits > 0
{
Some(init_ref.reliability.max_retransmits as u16)
} else {
None
},
max_packet_life_time: if init_ref.reliability.unreliable
&& init_ref.reliability.max_packet_life_time > 0
{
Some(init_ref.reliability.max_packet_life_time as u16)
} else {
None
},
max_payload_size: None,
negotiated: if init_ref.negotiated {
Some(init_ref.stream)
} else {
None
},
};
// Enter runtime context for create_data_channel
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
let _guard = rt.enter();
let label_for_create = dc_config.label.clone();
let dc = match pc_arc.create_data_channel(&label_for_create, Some(dc_config)) {
Ok(dc) => dc,
Err(e) => {
log::error!("create_data_channel failed: {e}");
return RTC_ERR_FAILURE;
}
};
let dc_id = alloc_id();
let channel_id = dc.id;
// Spawn DC event monitor
let handle = spawn_dc_monitor(dc_id, dc);
let dc_state = DcState::new(pc, pc_arc.clone(), channel_id);
*dc_state.task.lock() = Some(handle);
entries().write().insert(dc_id, Entry::Dc(dc_state));
// Trigger auto-negotiation (offer generation) if enabled
if !disable_auto {
trigger_offer(pc, pc_arc);
}
dc_id
}
#[no_mangle]
pub extern "C" fn rtcDeleteDataChannel(dc: c_int) -> c_int {
let entry = entries().write().remove(&dc);
match entry {
Some(Entry::Dc(dc_state)) => {
if let Some(t) = dc_state.task.lock().take() {
t.abort();
}
RTC_ERR_SUCCESS
}
Some(other) => {
entries().write().insert(dc, other);
RTC_ERR_INVALID
}
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// Callback setters (DataChannel / common)
// ===========================================================================
#[no_mangle]
pub extern "C" fn rtcSetOpenCallback(id: c_int, cb: Option<OpenCallbackFn>) -> c_int {
match with_dc(id, |s| *s.on_open.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetClosedCallback(id: c_int, cb: Option<ClosedCallbackFn>) -> c_int {
match with_dc(id, |s| *s.on_closed.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetErrorCallback(id: c_int, cb: Option<ErrorCallbackFn>) -> c_int {
match with_dc(id, |s| *s.on_error.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetMessageCallback(id: c_int, cb: Option<MessageCallbackFn>) -> c_int {
match with_dc(id, |s| *s.on_message.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// I/O
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcSendMessage(
id: c_int,
data: *const u8,
size: c_int,
) -> c_int {
let bytes = if size < 0 {
// Treat as null-terminated string
let cstr = CStr::from_ptr(data as *const c_char);
cstr.to_bytes().to_vec()
} else {
std::slice::from_raw_parts(data, size as usize).to_vec()
};
let (pc_arc, channel_id) = match with_dc(id, |dc| (dc.pc.clone(), dc.channel_id)) {
Some(v) => v,
None => return RTC_ERR_INVALID,
};
// Blocking send — preserves message ordering (caller is always on a non-tokio thread)
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
match rt.block_on(pc_arc.send_data(channel_id, &bytes)) {
Ok(_) => RTC_ERR_SUCCESS,
Err(e) => {
log::error!("send_data failed: {e}");
RTC_ERR_FAILURE
}
}
}
#[no_mangle]
pub extern "C" fn rtcClose(id: c_int) -> c_int {
// Try as DC first
if let Some(_) = with_dc(id, |dc| {
dc.is_open.store(false, Ordering::Release);
// Close the underlying PC data channel
let pc = dc.pc.clone();
let channel_id = dc.channel_id;
if let Some(rt) = get_runtime() {
rt.spawn(async move {
// There's no explicit DC close in rustrtc; closing is done at PC level
let _ = (pc, channel_id);
});
}
}) {
return RTC_ERR_SUCCESS;
}
// Try as PC
if let Some(_) = with_pc(id, |pc| {
pc.pc.close();
}) {
return RTC_ERR_SUCCESS;
}
RTC_ERR_INVALID
}
#[no_mangle]
pub extern "C" fn rtcDelete(id: c_int) -> c_int {
let entry = entries().write().remove(&id);
match entry {
Some(Entry::Dc(dc_state)) => {
if let Some(t) = dc_state.task.lock().take() {
t.abort();
}
RTC_ERR_SUCCESS
}
Some(Entry::Pc(pc_state)) => {
for t in pc_state.tasks.lock().drain(..) {
t.abort();
}
pc_state.pc.close();
RTC_ERR_SUCCESS
}
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcIsOpen(id: c_int) -> bool {
with_dc(id, |dc| dc.is_open.load(Ordering::Acquire)).unwrap_or(false)
}
#[no_mangle]
pub extern "C" fn rtcIsClosed(id: c_int) -> bool {
with_dc(id, |dc| dc.is_closed.load(Ordering::Acquire)).unwrap_or(true)
}
#[no_mangle]
pub extern "C" fn rtcGetBufferedAmount(id: c_int) -> c_int {
let pc_arc = match with_dc(id, |dc| dc.pc.clone()) {
Some(v) => v,
None => return RTC_ERR_INVALID,
};
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
// block_on is safe here because we're called from non-tokio threads
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
rt.block_on(pc_arc.sctp_buffered_amount()) as c_int
})) {
Ok(amount) => amount,
Err(_) => {
// If block_on panics (called from tokio context), try spawn + channel
let pc_clone = pc_arc.clone();
let (tx, rx) = std::sync::mpsc::channel();
rt.spawn(async move {
let amount = pc_clone.sctp_buffered_amount().await;
let _ = tx.send(amount as c_int);
});
rx.recv().unwrap_or(0)
}
}
}
#[no_mangle]
pub unsafe extern "C" fn rtcReceiveMessage(
id: c_int,
buffer: *mut u8,
size: *mut c_int,
) -> c_int {
if buffer.is_null() || size.is_null() {
return RTC_ERR_INVALID;
}
match with_dc(id, |dc| {
let mut buf = dc.recv_buffer.lock();
buf.pop_front()
}) {
Some(Some(data)) => {
let available = *size as usize;
if data.len() > available {
*size = data.len() as c_int;
return RTC_ERR_TOO_SMALL;
}
std::ptr::copy_nonoverlapping(data.as_ptr(), buffer, data.len());
*size = data.len() as c_int;
RTC_ERR_SUCCESS
}
Some(None) => RTC_ERR_NOT_AVAIL,
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// SCTP settings (no-op — rustrtc has its own SCTP stack)
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcSetSctpSettings(_settings: *const RtcSctpSettings) -> c_int {
RTC_ERR_SUCCESS
}

338
deps/rustrtc-capi/src/monitors.rs vendored Normal file
View File

@@ -0,0 +1,338 @@
//! Async tasks that bridge rustrtc events → C callbacks.
//!
//! For each PeerConnection, we spawn monitor tasks for:
//! - ICE candidates (broadcast receiver)
//! - Peer connection state (watch receiver)
//! - ICE gathering state (watch receiver)
//! - Incoming DataChannels (pc.recv())
//!
//! For each DataChannel, we spawn one monitor task that handles
//! Open / Message / Close events.
use std::ffi::CString;
use std::sync::Arc;
use rustrtc::peer_connection::{
IceGatheringState, PeerConnection, PeerConnectionEvent, PeerConnectionState,
};
use rustrtc::transports::datachannel::{DataChannel, DataChannelEvent};
use tokio::task::JoinHandle;
use crate::state::*;
use crate::types::*;
// ---------------------------------------------------------------------------
// PeerConnection monitors
// ---------------------------------------------------------------------------
/// Spawn all monitoring tasks for a PeerConnection. Returns task handles.
pub fn spawn_pc_monitors(
rt: &tokio::runtime::Runtime,
pc_id: i32,
pc: &Arc<PeerConnection>,
) -> Vec<JoinHandle<()>> {
let mut tasks = Vec::with_capacity(4);
// 1. ICE candidate monitor (broadcast::Receiver)
let mut cand_rx = pc.subscribe_ice_candidates();
let pc_id1 = pc_id;
tasks.push(rt.spawn(async move {
loop {
match cand_rx.recv().await {
Ok(candidate) => {
let cand_str = candidate.to_sdp();
let cand_c = match CString::new(cand_str) {
Ok(c) => c,
Err(_) => continue,
};
let mid_c = CString::new("0").unwrap();
if let Some((Some(cb), ptr)) = get_pc_candidate_cb(pc_id1) {
unsafe { cb(pc_id1, cand_c.as_ptr(), mid_c.as_ptr(), ptr) };
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
}
}
}));
// 2. Peer connection state monitor (watch::Receiver)
let mut state_rx = pc.subscribe_peer_state();
let pc_id2 = pc_id;
tasks.push(rt.spawn(async move {
while state_rx.changed().await.is_ok() {
let state = *state_rx.borrow_and_update();
let c_state = map_peer_state(state);
if let Some((Some(cb), ptr)) = get_pc_state_change_cb(pc_id2) {
unsafe { cb(pc_id2, c_state, ptr) };
}
}
}));
// 3. ICE gathering state monitor (watch::Receiver)
let mut gather_rx = pc.subscribe_ice_gathering_state();
let pc_id3 = pc_id;
tasks.push(rt.spawn(async move {
while gather_rx.changed().await.is_ok() {
let state = *gather_rx.borrow_and_update();
let c_state = map_gathering_state(state);
if let Some((Some(cb), ptr)) = get_pc_gathering_state_cb(pc_id3) {
unsafe { cb(pc_id3, c_state, ptr) };
}
}
}));
// 4. Incoming DataChannel monitor (pc.recv())
let pc_clone = pc.clone();
let pc_id4 = pc_id;
tasks.push(rt.spawn(async move {
while let Some(event) = pc_clone.recv().await {
match event {
PeerConnectionEvent::DataChannel(dc) => {
handle_incoming_data_channel(pc_id4, &pc_clone, dc).await;
}
_ => {} // Ignore Track events for data-channel-only usage
}
}
}));
tasks
}
/// Handle an incoming DataChannel: register it, fire callback, then spawn monitor.
async fn handle_incoming_data_channel(
pc_id: i32,
pc: &Arc<PeerConnection>,
dc: Arc<DataChannel>,
) {
let dc_id = alloc_id();
let channel_id = dc.id;
let dc_state = DcState::new(pc_id, pc.clone(), channel_id);
// Insert into global registry
{
let mut map = entries().write();
map.insert(dc_id, Entry::Dc(dc_state));
}
// Fire DataChannel callback (synchronously — user sets DC callbacks inside)
if let Some((Some(cb), ptr)) = get_pc_data_channel_cb(pc_id) {
// Copy the PC's user pointer to the DC entry
let pc_ptr = get_user_ptr(pc_id);
set_user_ptr(dc_id, pc_ptr);
unsafe { cb(pc_id, dc_id, ptr) };
}
// Now spawn DC monitor (callbacks are set by this point)
let handle = spawn_dc_monitor(dc_id, dc);
with_dc(dc_id, |dc_state| {
*dc_state.task.lock() = Some(handle);
});
}
// ---------------------------------------------------------------------------
// DataChannel monitor
// ---------------------------------------------------------------------------
/// Spawn a monitor task for a DataChannel. Fires open/message/close callbacks.
pub fn spawn_dc_monitor(dc_id: i32, dc: Arc<DataChannel>) -> JoinHandle<()> {
let rt = get_runtime().expect("runtime not initialized");
rt.spawn(async move {
while let Some(event) = dc.recv().await {
match event {
DataChannelEvent::Open => {
// Mark as open
with_dc(dc_id, |dc_state| {
dc_state.is_open.store(true, std::sync::atomic::Ordering::Release);
dc_state.is_closed.store(false, std::sync::atomic::Ordering::Release);
});
if let Some((Some(cb), ptr)) = get_dc_open_cb(dc_id) {
unsafe { cb(dc_id, ptr) };
}
}
DataChannelEvent::Message(data) => {
let bytes = data.to_vec();
let len = bytes.len();
// Push to recv_buffer (for rtcReceiveMessage)
with_dc(dc_id, |dc_state| {
let mut buf = dc_state.recv_buffer.lock();
if buf.len() < 65536 {
buf.push_back(bytes.clone());
}
});
// Fire message callback
if let Some((Some(cb), ptr)) = get_dc_message_cb(dc_id) {
unsafe { cb(dc_id, bytes.as_ptr(), len as i32, ptr) };
}
}
DataChannelEvent::Close => {
with_dc(dc_id, |dc_state| {
dc_state.is_open.store(false, std::sync::atomic::Ordering::Release);
dc_state.is_closed.store(true, std::sync::atomic::Ordering::Release);
});
if let Some((Some(cb), ptr)) = get_dc_closed_cb(dc_id) {
unsafe { cb(dc_id, ptr) };
}
break;
}
}
}
})
}
// ---------------------------------------------------------------------------
// SDP generation helpers (spawned as async tasks)
// ---------------------------------------------------------------------------
/// Inject `a=max-message-size:1048576` into an SDP string if not already present.
/// Per RFC 8841 §4.3, absence of this attribute makes the remote peer assume a
/// default of 65536 bytes, which is too small for efficient file transfers.
pub fn inject_max_message_size(sdp: &str) -> String {
if sdp.contains("a=max-message-size") {
return sdp.to_string();
}
// Insert after `a=sctp-port` line (within the m= section)
if let Some(pos) = sdp.find("a=sctp-port") {
if let Some(eol) = sdp[pos..].find("\r\n") {
let insert_at = pos + eol + 2;
let mut result = String::with_capacity(sdp.len() + 30);
result.push_str(&sdp[..insert_at]);
result.push_str("a=max-message-size:1048576\r\n");
result.push_str(&sdp[insert_at..]);
return result;
}
}
sdp.to_string()
}
/// Trigger offer generation: create offer → set local description → fire callback.
/// Called after rtcCreateDataChannelEx when auto-negotiation is enabled.
pub fn trigger_offer(pc_id: i32, pc: Arc<PeerConnection>) {
let rt = get_runtime().expect("runtime not initialized");
let handle = rt.spawn(async move {
match pc.create_offer().await {
Ok(offer) => {
let sdp_string = inject_max_message_size(&offer.to_sdp_string());
if let Err(e) = pc.set_local_description(offer) {
log::error!("set_local_description failed: {e}");
return;
}
let sdp_c = match CString::new(sdp_string.clone()) {
Ok(c) => c,
Err(_) => return,
};
let type_c = CString::new("offer").unwrap();
// Cache SDP
with_pc(pc_id, |pc_state| {
*pc_state.local_sdp.lock() = Some(sdp_c.clone());
*pc_state.local_sdp_type.lock() = Some(type_c.clone());
});
// Fire description callback
if let Some((Some(cb), ptr)) = get_pc_description_cb(pc_id) {
unsafe { cb(pc_id, sdp_c.as_ptr(), type_c.as_ptr(), ptr) };
}
}
Err(e) => {
log::error!("create_offer failed: {e}");
}
}
});
// Store task handle
with_pc(pc_id, |pc_state| {
pc_state.tasks.lock().push(handle);
});
}
/// Trigger answer generation after receiving a remote offer.
pub fn trigger_answer(pc_id: i32, pc: Arc<PeerConnection>, remote_sdp: String) {
let rt = get_runtime().expect("runtime not initialized");
let handle = rt.spawn(async move {
// Parse and set remote description
let desc = match rustrtc::sdp::SessionDescription::parse(
rustrtc::sdp::SdpType::Offer,
&remote_sdp,
) {
Ok(d) => d,
Err(e) => {
log::error!("parse remote SDP failed: {e}");
return;
}
};
if let Err(e) = pc.set_remote_description(desc).await {
log::error!("set_remote_description failed: {e}");
return;
}
// Cache remote SDP
if let Ok(remote_c) = CString::new(remote_sdp) {
with_pc(pc_id, |pc_state| {
*pc_state.remote_sdp.lock() = Some(remote_c);
});
}
// Create answer
match pc.create_answer().await {
Ok(answer) => {
let sdp_string = inject_max_message_size(&answer.to_sdp_string());
if let Err(e) = pc.set_local_description(answer) {
log::error!("set_local_description (answer) failed: {e}");
return;
}
let sdp_c = match CString::new(sdp_string) {
Ok(c) => c,
Err(_) => return,
};
let type_c = CString::new("answer").unwrap();
// Cache answer SDP
with_pc(pc_id, |pc_state| {
*pc_state.local_sdp.lock() = Some(sdp_c.clone());
*pc_state.local_sdp_type.lock() = Some(type_c.clone());
});
// Fire description callback
if let Some((Some(cb), ptr)) = get_pc_description_cb(pc_id) {
unsafe { cb(pc_id, sdp_c.as_ptr(), type_c.as_ptr(), ptr) };
}
}
Err(e) => {
log::error!("create_answer failed: {e}");
}
}
});
with_pc(pc_id, |pc_state| {
pc_state.tasks.lock().push(handle);
});
}
// ---------------------------------------------------------------------------
// State mapping helpers
// ---------------------------------------------------------------------------
fn map_peer_state(state: PeerConnectionState) -> i32 {
match state {
PeerConnectionState::New => RTC_STATE_NEW,
PeerConnectionState::Connecting => RTC_STATE_CONNECTING,
PeerConnectionState::Connected => RTC_STATE_CONNECTED,
PeerConnectionState::Disconnected => RTC_STATE_DISCONNECTED,
PeerConnectionState::Failed => RTC_STATE_FAILED,
PeerConnectionState::Closed => RTC_STATE_CLOSED,
}
}
fn map_gathering_state(state: IceGatheringState) -> i32 {
match state {
IceGatheringState::New => RTC_GATHERING_NEW,
IceGatheringState::Gathering => RTC_GATHERING_IN_PROGRESS,
IceGatheringState::Complete => RTC_GATHERING_COMPLETE,
}
}

254
deps/rustrtc-capi/src/state.rs vendored Normal file
View File

@@ -0,0 +1,254 @@
//! Global ID registry, PcState, DcState.
use std::collections::{HashMap, VecDeque};
use std::ffi::CString;
use std::os::raw::c_void;
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, Ordering};
use std::sync::{Arc, OnceLock};
use parking_lot::{Mutex, RwLock};
use tokio::runtime::Runtime;
use tokio::task::JoinHandle;
use rustrtc::peer_connection::PeerConnection;
use crate::types::*;
// ---------------------------------------------------------------------------
// Global statics
// ---------------------------------------------------------------------------
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
static ENTRIES: OnceLock<RwLock<HashMap<i32, Entry>>> = OnceLock::new();
static NEXT_ID: AtomicI32 = AtomicI32::new(1);
pub fn init_runtime() {
RUNTIME.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("failed to create tokio runtime")
});
ENTRIES.get_or_init(|| RwLock::new(HashMap::new()));
}
pub fn get_runtime() -> Option<&'static Runtime> {
RUNTIME.get()
}
pub fn cleanup() {
if let Some(entries) = ENTRIES.get() {
let mut map = entries.write();
// Abort all tasks
for (_, entry) in map.drain() {
match entry {
Entry::Pc(pc) => {
let tasks = pc.tasks.lock();
for t in tasks.iter() {
t.abort();
}
}
Entry::Dc(dc) => {
if let Some(t) = dc.task.lock().take() {
t.abort();
}
}
}
}
}
// Note: We don't drop the runtime here because OnceLock doesn't support reset.
// The runtime will be cleaned up on process exit.
}
pub fn alloc_id() -> i32 {
NEXT_ID.fetch_add(1, Ordering::Relaxed)
}
pub fn entries() -> &'static RwLock<HashMap<i32, Entry>> {
ENTRIES.get().expect("runtime not initialized")
}
// ---------------------------------------------------------------------------
// Entry types
// ---------------------------------------------------------------------------
pub enum Entry {
Pc(PcState),
Dc(DcState),
}
pub struct PcState {
pub pc: Arc<PeerConnection>,
pub user_ptr: AtomicPtr<c_void>,
pub disable_auto_negotiation: bool,
// Callback slots
pub on_local_description: Mutex<Option<DescriptionCallbackFn>>,
pub on_local_candidate: Mutex<Option<CandidateCallbackFn>>,
pub on_state_change: Mutex<Option<StateChangeCallbackFn>>,
pub on_gathering_state: Mutex<Option<GatheringStateCallbackFn>>,
pub on_data_channel: Mutex<Option<DataChannelCallbackFn>>,
// Cached SDP
pub local_sdp: Mutex<Option<CString>>,
pub local_sdp_type: Mutex<Option<CString>>,
pub remote_sdp: Mutex<Option<CString>>,
// Monitor task handles
pub tasks: Mutex<Vec<JoinHandle<()>>>,
}
pub struct DcState {
#[allow(dead_code)]
pub pc_id: i32,
pub pc: Arc<PeerConnection>,
pub channel_id: u16,
pub user_ptr: AtomicPtr<c_void>,
// Callback slots
pub on_open: Mutex<Option<OpenCallbackFn>>,
pub on_closed: Mutex<Option<ClosedCallbackFn>>,
pub on_error: Mutex<Option<ErrorCallbackFn>>,
pub on_message: Mutex<Option<MessageCallbackFn>>,
// State flags
pub is_open: AtomicBool,
pub is_closed: AtomicBool,
// Receive buffer (for rtcReceiveMessage polling)
pub recv_buffer: Mutex<VecDeque<Vec<u8>>>,
// Monitor task handle
pub task: Mutex<Option<JoinHandle<()>>>,
}
impl PcState {
pub fn new(pc: Arc<PeerConnection>, disable_auto_negotiation: bool) -> Self {
Self {
pc,
user_ptr: AtomicPtr::new(std::ptr::null_mut()),
disable_auto_negotiation,
on_local_description: Mutex::new(None),
on_local_candidate: Mutex::new(None),
on_state_change: Mutex::new(None),
on_gathering_state: Mutex::new(None),
on_data_channel: Mutex::new(None),
local_sdp: Mutex::new(None),
local_sdp_type: Mutex::new(None),
remote_sdp: Mutex::new(None),
tasks: Mutex::new(Vec::new()),
}
}
}
impl DcState {
pub fn new(pc_id: i32, pc: Arc<PeerConnection>, channel_id: u16) -> Self {
Self {
pc_id,
pc,
channel_id,
user_ptr: AtomicPtr::new(std::ptr::null_mut()),
on_open: Mutex::new(None),
on_closed: Mutex::new(None),
on_error: Mutex::new(None),
on_message: Mutex::new(None),
is_open: AtomicBool::new(false),
is_closed: AtomicBool::new(false),
recv_buffer: Mutex::new(VecDeque::new()),
task: Mutex::new(None),
}
}
}
// ---------------------------------------------------------------------------
// Helper accessors
// ---------------------------------------------------------------------------
/// Get user pointer for any entry (PC or DC).
pub fn get_user_ptr(id: i32) -> *mut c_void {
let map = entries().read();
match map.get(&id) {
Some(Entry::Pc(pc)) => pc.user_ptr.load(Ordering::Acquire),
Some(Entry::Dc(dc)) => dc.user_ptr.load(Ordering::Acquire),
None => std::ptr::null_mut(),
}
}
/// Set user pointer for any entry.
pub fn set_user_ptr(id: i32, ptr: *mut c_void) {
let map = entries().read();
match map.get(&id) {
Some(Entry::Pc(pc)) => pc.user_ptr.store(ptr, Ordering::Release),
Some(Entry::Dc(dc)) => dc.user_ptr.store(ptr, Ordering::Release),
None => {}
}
}
/// Execute a closure with read access to a PcState.
pub fn with_pc<F, R>(id: i32, f: F) -> Option<R>
where
F: FnOnce(&PcState) -> R,
{
let map = entries().read();
match map.get(&id) {
Some(Entry::Pc(pc)) => Some(f(pc)),
_ => None,
}
}
/// Execute a closure with read access to a DcState.
pub fn with_dc<F, R>(id: i32, f: F) -> Option<R>
where
F: FnOnce(&DcState) -> R,
{
let map = entries().read();
match map.get(&id) {
Some(Entry::Dc(dc)) => Some(f(dc)),
_ => None,
}
}
/// Get the PC Arc and user_ptr for a given PC id.
#[allow(dead_code)]
pub fn get_pc_arc(id: i32) -> Option<(Arc<PeerConnection>, *mut c_void)> {
with_pc(id, |pc| (pc.pc.clone(), pc.user_ptr.load(Ordering::Acquire)))
}
/// Get callback + user_ptr from a PC entry.
pub fn get_pc_description_cb(id: i32) -> Option<(Option<DescriptionCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_local_description.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_pc_candidate_cb(id: i32) -> Option<(Option<CandidateCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_local_candidate.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_pc_state_change_cb(id: i32) -> Option<(Option<StateChangeCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_state_change.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_pc_gathering_state_cb(id: i32) -> Option<(Option<GatheringStateCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_gathering_state.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_pc_data_channel_cb(id: i32) -> Option<(Option<DataChannelCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_data_channel.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_dc_open_cb(id: i32) -> Option<(Option<OpenCallbackFn>, *mut c_void)> {
with_dc(id, |dc| (*dc.on_open.lock(), dc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_dc_closed_cb(id: i32) -> Option<(Option<ClosedCallbackFn>, *mut c_void)> {
with_dc(id, |dc| (*dc.on_closed.lock(), dc.user_ptr.load(Ordering::Acquire)))
}
#[allow(dead_code)]
pub fn get_dc_error_cb(id: i32) -> Option<(Option<ErrorCallbackFn>, *mut c_void)> {
with_dc(id, |dc| (*dc.on_error.lock(), dc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_dc_message_cb(id: i32) -> Option<(Option<MessageCallbackFn>, *mut c_void)> {
with_dc(id, |dc| (*dc.on_message.lock(), dc.user_ptr.load(Ordering::Acquire)))
}

107
deps/rustrtc-capi/src/types.rs vendored Normal file
View File

@@ -0,0 +1,107 @@
//! C ABI type definitions matching libdatachannel's rtc.h
use std::os::raw::{c_char, c_int, c_uint, c_void};
// ---------------------------------------------------------------------------
// Error codes
// ---------------------------------------------------------------------------
pub const RTC_ERR_SUCCESS: c_int = 0;
pub const RTC_ERR_INVALID: c_int = -1;
pub const RTC_ERR_FAILURE: c_int = -2;
pub const RTC_ERR_NOT_AVAIL: c_int = -3;
pub const RTC_ERR_TOO_SMALL: c_int = -4;
// ---------------------------------------------------------------------------
// State enum values (as c_int, matching Zig's enum(c_int))
// ---------------------------------------------------------------------------
// PeerConnection / ICE state
pub const RTC_STATE_NEW: c_int = 0;
pub const RTC_STATE_CONNECTING: c_int = 1;
pub const RTC_STATE_CONNECTED: c_int = 2;
pub const RTC_STATE_DISCONNECTED: c_int = 3;
pub const RTC_STATE_FAILED: c_int = 4;
pub const RTC_STATE_CLOSED: c_int = 5;
// ICE gathering state
pub const RTC_GATHERING_NEW: c_int = 0;
pub const RTC_GATHERING_IN_PROGRESS: c_int = 1;
pub const RTC_GATHERING_COMPLETE: c_int = 2;
// ---------------------------------------------------------------------------
// Callback function types
// ---------------------------------------------------------------------------
pub type DescriptionCallbackFn =
unsafe extern "C" fn(pc: c_int, sdp: *const c_char, sdp_type: *const c_char, ptr: *mut c_void);
pub type CandidateCallbackFn =
unsafe extern "C" fn(pc: c_int, cand: *const c_char, mid: *const c_char, ptr: *mut c_void);
pub type StateChangeCallbackFn =
unsafe extern "C" fn(pc: c_int, state: c_int, ptr: *mut c_void);
pub type GatheringStateCallbackFn =
unsafe extern "C" fn(pc: c_int, state: c_int, ptr: *mut c_void);
pub type DataChannelCallbackFn =
unsafe extern "C" fn(pc: c_int, dc: c_int, ptr: *mut c_void);
pub type OpenCallbackFn = unsafe extern "C" fn(id: c_int, ptr: *mut c_void);
pub type ClosedCallbackFn = unsafe extern "C" fn(id: c_int, ptr: *mut c_void);
pub type ErrorCallbackFn =
unsafe extern "C" fn(id: c_int, err_msg: *const c_char, ptr: *mut c_void);
pub type MessageCallbackFn =
unsafe extern "C" fn(id: c_int, message: *const u8, size: c_int, ptr: *mut c_void);
pub type LogCallbackFn = unsafe extern "C" fn(level: c_int, message: *const c_char);
// ---------------------------------------------------------------------------
// #[repr(C)] structs matching Zig extern structs
// ---------------------------------------------------------------------------
#[repr(C)]
pub struct RtcConfiguration {
pub ice_servers: *const *const c_char,
pub ice_servers_count: c_int,
pub proxy_server: *const c_char,
pub bind_address: *const c_char,
pub certificate_type: c_int,
pub ice_transport_policy: c_int,
pub enable_ice_tcp: bool,
pub enable_ice_udp_mux: bool,
pub disable_auto_negotiation: bool,
pub force_media_transport: bool,
pub port_range_begin: u16,
pub port_range_end: u16,
pub mtu: c_int,
pub max_message_size: c_int,
}
#[repr(C)]
pub struct RtcReliability {
pub unordered: bool,
pub unreliable: bool,
pub max_packet_life_time: c_uint,
pub max_retransmits: c_uint,
}
#[repr(C)]
pub struct RtcDataChannelInit {
pub reliability: RtcReliability,
pub protocol: *const c_char,
pub negotiated: bool,
pub manual_stream: bool,
pub stream: u16,
}
#[repr(C)]
pub struct RtcSctpSettings {
pub recv_buffer_size: c_int,
pub send_buffer_size: c_int,
pub max_chunks_on_queue: c_int,
pub initial_congestion_window: c_int,
pub max_burst: c_int,
pub congestion_control_module: c_int,
pub delayed_sack_time_ms: c_int,
pub min_retransmit_timeout_ms: c_int,
pub max_retransmit_timeout_ms: c_int,
pub initial_retransmit_timeout_ms: c_int,
pub max_retransmit_attempts: c_int,
pub heartbeat_interval_ms: c_int,
}

304
deps/rustrtc-capi/src/ws_signaling.rs vendored Normal file
View File

@@ -0,0 +1,304 @@
//! WebSocket signaling client for SDP/ICE exchange.
//!
//! Provides 5 C-callable functions that let the Zig bridge connect to a
//! signaling server, send/receive JSON messages, and disconnect.
use std::collections::VecDeque;
use std::os::raw::{c_char, c_int};
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
use std::sync::OnceLock;
use futures_util::{SinkExt, StreamExt};
use parking_lot::Mutex;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio_tungstenite::tungstenite::Message;
use crate::state;
// ============================================================================
// WebSocket State
// ============================================================================
static NEXT_WS_ID: AtomicI32 = AtomicI32::new(1);
static WS_ENTRIES: OnceLock<Mutex<Vec<Option<WsState>>>> = OnceLock::new();
const MAX_WS_CONNECTIONS: usize = 8;
const MAX_RECV_QUEUE: usize = 256;
struct WsState {
id: i32,
connected: AtomicBool,
/// Sender for outgoing messages (to the writer task)
tx: mpsc::UnboundedSender<String>,
/// Received messages waiting to be polled by C caller
recv_queue: Mutex<VecDeque<String>>,
/// Background reader task handle
reader_task: Mutex<Option<JoinHandle<()>>>,
/// Background writer task handle
writer_task: Mutex<Option<JoinHandle<()>>>,
}
fn get_entries() -> &'static Mutex<Vec<Option<WsState>>> {
WS_ENTRIES.get_or_init(|| {
let mut v = Vec::with_capacity(MAX_WS_CONNECTIONS);
for _ in 0..MAX_WS_CONNECTIONS {
v.push(None);
}
Mutex::new(v)
})
}
// ============================================================================
// C API Functions
// ============================================================================
/// Connect to a signaling server via WebSocket.
/// `url` and `peer_id` are null-terminated C strings.
/// Returns a ws_id > 0 on success, or negative error code.
#[no_mangle]
pub unsafe extern "C" fn rtcWsConnect(url: *const c_char, peer_id: *const c_char) -> c_int {
if url.is_null() || peer_id.is_null() {
return -1;
}
let url_str = match std::ffi::CStr::from_ptr(url).to_str() {
Ok(s) => s.to_string(),
Err(_) => return -1,
};
let peer_id_str = match std::ffi::CStr::from_ptr(peer_id).to_str() {
Ok(s) => s.to_string(),
Err(_) => return -1,
};
let rt = match state::get_runtime() {
Some(rt) => rt,
None => {
// Ensure runtime is initialized
state::init_runtime();
match state::get_runtime() {
Some(rt) => rt,
None => return -2,
}
}
};
let ws_id = NEXT_WS_ID.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = mpsc::unbounded_channel::<String>();
// Connect in a blocking fashion so the C caller gets immediate result
let connect_result = rt.block_on(async {
tokio_tungstenite::connect_async(&url_str).await
});
let ws_stream = match connect_result {
Ok((stream, _response)) => stream,
Err(e) => {
log::error!("WebSocket connect failed: {}", e);
return -2;
}
};
let (mut write, mut read) = ws_stream.split();
// Send register message immediately
let register_msg = serde_json::json!({
"type": "register",
"peerId": peer_id_str
}).to_string();
if let Err(e) = rt.block_on(write.send(Message::Text(register_msg))) {
log::error!("Failed to send register: {}", e);
return -2;
}
let recv_queue = Mutex::new(VecDeque::new());
let connected = AtomicBool::new(true);
// Create the state entry first so tasks can reference the ID
let ws_state = WsState {
id: ws_id,
connected,
tx,
recv_queue,
reader_task: Mutex::new(None),
writer_task: Mutex::new(None),
};
// Store in entries
{
let mut entries = get_entries().lock();
let slot = entries.iter().position(|e| e.is_none());
match slot {
Some(idx) => entries[idx] = Some(ws_state),
None => return -3, // No free slots
}
}
// Spawn reader task
let reader_ws_id = ws_id;
let reader_handle = rt.spawn(async move {
while let Some(msg_result) = read.next().await {
match msg_result {
Ok(Message::Text(text)) => {
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == reader_ws_id)
}) {
if let Some(ws) = slot.as_ref() {
let mut queue = ws.recv_queue.lock();
if queue.len() < MAX_RECV_QUEUE {
queue.push_back(text);
}
}
}
}
Ok(Message::Close(_)) => break,
Ok(_) => {} // Ignore binary/ping/pong
Err(e) => {
log::warn!("WebSocket read error: {}", e);
break;
}
}
}
// Mark as disconnected
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == reader_ws_id)
}) {
if let Some(ws) = slot.as_ref() {
ws.connected.store(false, Ordering::Release);
}
}
});
// Spawn writer task
let mut writer_rx = rx;
let writer_handle = rt.spawn(async move {
while let Some(msg) = writer_rx.recv().await {
if write.send(Message::Text(msg)).await.is_err() {
break;
}
}
});
// Store task handles
{
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = slot.as_ref() {
*ws.reader_task.lock() = Some(reader_handle);
*ws.writer_task.lock() = Some(writer_handle);
}
}
}
ws_id
}
/// Disconnect a WebSocket connection.
/// Returns 0 on success, negative on error.
#[no_mangle]
pub extern "C" fn rtcWsDisconnect(ws_id: c_int) -> c_int {
let mut entries = get_entries().lock();
if let Some(idx) = entries.iter().position(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = entries[idx].take() {
ws.connected.store(false, Ordering::Release);
// Abort tasks
if let Some(h) = ws.reader_task.lock().take() {
h.abort();
}
if let Some(h) = ws.writer_task.lock().take() {
h.abort();
}
}
return 0;
}
-1
}
/// Send a message on a WebSocket connection.
/// `message` points to a buffer of `size` bytes (not null-terminated).
/// Returns 0 on success, negative on error.
#[no_mangle]
pub unsafe extern "C" fn rtcWsSend(ws_id: c_int, message: *const c_char, size: c_int) -> c_int {
if message.is_null() || size <= 0 {
return -1;
}
let bytes = std::slice::from_raw_parts(message as *const u8, size as usize);
let text = match std::str::from_utf8(bytes) {
Ok(s) => s.to_string(),
Err(_) => return -1,
};
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = slot.as_ref() {
if !ws.connected.load(Ordering::Acquire) {
return -2;
}
match ws.tx.send(text) {
Ok(_) => return 0,
Err(_) => return -2,
}
}
}
-1
}
/// Non-blocking receive: polls for the next message.
/// If a message is available, copies it into `buffer` (up to `*size` bytes),
/// updates `*size` to the actual message length, and returns 0.
/// If no message is available, returns 1 (would-block).
/// On error returns negative.
#[no_mangle]
pub unsafe extern "C" fn rtcWsRecv(
ws_id: c_int,
buffer: *mut c_char,
size: *mut c_int,
) -> c_int {
if buffer.is_null() || size.is_null() {
return -1;
}
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = slot.as_ref() {
let mut queue = ws.recv_queue.lock();
if let Some(msg) = queue.pop_front() {
let buf_size = *size as usize;
let msg_bytes = msg.as_bytes();
let copy_len = msg_bytes.len().min(buf_size);
std::ptr::copy_nonoverlapping(msg_bytes.as_ptr(), buffer as *mut u8, copy_len);
*size = msg_bytes.len() as c_int;
return 0;
}
return 1; // Would-block: no messages
}
}
-1
}
/// Check if a WebSocket connection is still connected.
/// Returns 1 if connected, 0 if not, negative on error.
#[no_mangle]
pub extern "C" fn rtcWsIsConnected(ws_id: c_int) -> c_int {
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = slot.as_ref() {
return if ws.connected.load(Ordering::Acquire) { 1 } else { 0 };
}
}
-1
}