ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
WebRTC P2P Connections

Event hooks and caller context for one WebRTC DataChannel. More...

Files

file  ice_selected_pair.cpp
 C++ implementation for retrieving selected ICE candidate pair.
file  ice.h
 ICE (Interactive Connectivity Establishment) for WebRTC.
file  sdp.h
 SDP (Session Description Protocol) for WebRTC audio/video negotiation.

Data Structures

struct  webrtc_peer_manager_config_t
 Peer manager configuration. More...
struct  webrtc_signaling_callbacks_t
 Hooks that deliver local SDP offers/answers and ICE candidates to ACDS. More...
struct  webrtc_config_t
 ICE, signaling, DataChannel, and callback settings for a WebRTC peer. More...
struct  webrtc_datachannel_callbacks_t
 Event hooks and caller context for one WebRTC DataChannel. More...

Typedefs

typedef struct webrtc_peer_manager webrtc_peer_manager_t
 For pending ice candidate, this is the live record that ties candidate, mid, next together. The owning code creates it, updates it while work is active, and releases its handles and pointed-to storage before freeing the record.
typedef void(* webrtc_transport_ready_callback_t) (acip_transport_t *transport, const uint8_t participant_id[16], void *user_data)
 Callback when DataChannel is ready and wrapped in ACIP transport.
typedef void(* webrtc_gathering_timeout_callback_t) (const uint8_t participant_id[16], uint32_t timeout_ms, uint64_t elapsed_ms, void *user_data)
 Callback when ICE candidate gathering is unusually slow.
typedef asciichat_error_t(* webrtc_send_sdp_callback_t) (const uint8_t session_id[16], const uint8_t recipient_id[16], const char *sdp_type, const char *sdp, void *user_data)
 Callback to send SDP via ACDS signaling.
typedef asciichat_error_t(* webrtc_send_ice_callback_t) (const uint8_t session_id[16], const uint8_t recipient_id[16], const char *candidate, const char *mid, void *user_data)
 Callback to send ICE candidate via ACDS signaling.
typedef struct webrtc_peer_connection webrtc_peer_connection_t
typedef struct webrtc_data_channel webrtc_data_channel_t
typedef void(* webrtc_state_callback_t) (webrtc_peer_connection_t *pc, webrtc_state_t state, void *user_data)
 Callback for state changes.
typedef void(* webrtc_local_description_callback_t) (webrtc_peer_connection_t *pc, const char *sdp, const char *type, void *user_data)
 Callback for local SDP offer/answer generation.
typedef void(* webrtc_local_candidate_callback_t) (webrtc_peer_connection_t *pc, const char *candidate, const char *mid, void *user_data)
 Callback for local ICE candidate discovery.
typedef void(* webrtc_gathering_state_callback_t) (webrtc_peer_connection_t *pc, webrtc_gathering_state_t state, void *user_data)
 Callback for ICE gathering state changes.
typedef void(* webrtc_datachannel_open_callback_t) (webrtc_data_channel_t *dc, void *user_data)
 Callback for DataChannel open event.
typedef void(* webrtc_datachannel_message_callback_t) (webrtc_data_channel_t *dc, const uint8_t *data, size_t size, void *user_data)
 Callback for DataChannel message received.
typedef void(* webrtc_datachannel_error_callback_t) (webrtc_data_channel_t *dc, const char *error, void *user_data)
 Callback for DataChannel error.

Enumerations

enum  webrtc_peer_role_t { WEBRTC_ROLE_CREATOR = 0 , WEBRTC_ROLE_JOINER = 1 }
 Peer connection role (server or client). More...
enum  webrtc_state_t {
  WEBRTC_STATE_NEW = 0 , WEBRTC_STATE_CONNECTING , WEBRTC_STATE_CONNECTED , WEBRTC_STATE_DISCONNECTED ,
  WEBRTC_STATE_FAILED , WEBRTC_STATE_CLOSED
}
 ICE, signaling, DataChannel, and callback settings for a WebRTC peer. More...
enum  webrtc_gathering_state_t { WEBRTC_GATHERING_NEW = 0 , WEBRTC_GATHERING_GATHERING , WEBRTC_GATHERING_COMPLETE }
 ICE gathering state. More...

Functions

asciichat_error_t webrtc_peer_manager_create (const webrtc_peer_manager_config_t *config, const webrtc_signaling_callbacks_t *signaling_callbacks, webrtc_peer_manager_t **manager_out)
 Create a WebRTC peer manager.
void webrtc_peer_manager_destroy (webrtc_peer_manager_t *manager)
 Destroy peer manager and close all connections.
asciichat_error_t webrtc_peer_manager_handle_sdp (webrtc_peer_manager_t *manager, const acip_webrtc_sdp_t *sdp)
 Handle incoming SDP message from ACDS.
asciichat_error_t webrtc_peer_manager_handle_ice (webrtc_peer_manager_t *manager, const acip_webrtc_ice_t *ice)
 Handle incoming ICE candidate from ACDS.
asciichat_error_t webrtc_peer_manager_connect (webrtc_peer_manager_t *manager, const uint8_t session_id[16], const uint8_t participant_id[16])
 Initiate connection to remote peer (joiner role only).
bool webrtc_peer_manager_get_state (webrtc_peer_manager_t *manager, const uint8_t participant_id[16], webrtc_state_t *state_out)
asciichat_error_t webrtc_peer_manager_remove_peer (webrtc_peer_manager_t *manager, const uint8_t participant_id[16])
int webrtc_peer_manager_check_gathering_timeouts (webrtc_peer_manager_t *manager, uint32_t timeout_ms)
 Report slow ICE gathering and remove failed connections.
asciichat_error_t webrtc_peer_manager_dispatch_ready (webrtc_peer_manager_t *manager)
asciichat_error_t webrtc_init (void)
 Initialize WebRTC library (libdatachannel).
void webrtc_destroy (void)
 Cleanup WebRTC library resources.
asciichat_error_t webrtc_create_peer_connection (const webrtc_config_t *config, webrtc_peer_connection_t **pc_out)
 Create a new WebRTC peer connection.
void webrtc_close_peer_connection (webrtc_peer_connection_t *pc)
 Close and destroy a peer connection.
webrtc_state_t webrtc_get_state (webrtc_peer_connection_t *pc)
 Get current connection state.
webrtc_gathering_state_t webrtc_get_gathering_state (webrtc_peer_connection_t *pc)
 Get current ICE gathering state.
bool webrtc_is_gathering_timed_out (webrtc_peer_connection_t *pc, uint32_t timeout_ms)
 Check if ICE gathering has timed out.
void * webrtc_get_user_data (webrtc_peer_connection_t *pc)
 Get user data pointer from connection.
asciichat_error_t webrtc_create_offer (webrtc_peer_connection_t *pc)
 Create and set local SDP offer (for connection initiator).
asciichat_error_t webrtc_set_remote_description (webrtc_peer_connection_t *pc, const char *sdp, const char *type)
 Set remote SDP offer/answer.
asciichat_error_t webrtc_add_remote_candidate (webrtc_peer_connection_t *pc, const char *candidate, const char *mid)
 Add remote ICE candidate.
asciichat_error_t webrtc_create_datachannel (webrtc_peer_connection_t *pc, const char *label, webrtc_data_channel_t **dc_out)
 Create a DataChannel (for connection initiator).
asciichat_error_t webrtc_datachannel_send (webrtc_data_channel_t *dc, const uint8_t *data, size_t size)
 Send data over DataChannel.
asciichat_error_t webrtc_datachannel_get_buffered_amount (webrtc_data_channel_t *dc, size_t *amount)
asciichat_error_t webrtc_datachannel_get_max_message_size (webrtc_data_channel_t *dc, size_t *size)
bool webrtc_datachannel_is_open (webrtc_data_channel_t *dc)
 Check if DataChannel is open and ready.
void webrtc_datachannel_set_open_state (webrtc_data_channel_t *dc, bool is_open)
 Set DataChannel open state (internal use).
const char * webrtc_datachannel_get_label (webrtc_data_channel_t *dc)
 Get DataChannel label.
asciichat_error_t webrtc_datachannel_set_callbacks (webrtc_data_channel_t *dc, const webrtc_datachannel_callbacks_t *callbacks)
 Set DataChannel callbacks.
void webrtc_close_datachannel (webrtc_data_channel_t *dc)
 Close a DataChannel.
void webrtc_datachannel_destroy (webrtc_data_channel_t *dc)
 Destroy a DataChannel and free resources.
void webrtc_peer_connection_close (webrtc_peer_connection_t *pc)
 Close a peer connection.
void webrtc_peer_connection_destroy (webrtc_peer_connection_t *pc)
 Destroy a peer connection and free resources.
int webrtc_get_rtc_id (webrtc_peer_connection_t *pc)
 Get the internal libdatachannel peer connection ID.

Detailed Description

Event hooks and caller context for one WebRTC DataChannel.

For webrtc peer manager config, this is the live record that ties role, bind_address, stun_servers, stun_count together. The owning code creates it, updates it while work is active, and releases its handles and pointed-to storage before freeing the record.

WebRTC DataChannel transport for ACIP packets

Hooks that deliver local SDP offers/answers and ICE candidates to ACDS

Manage WebRTC peer connections for session participants

Typedef Documentation

◆ webrtc_data_channel_t

◆ webrtc_datachannel_error_callback_t

typedef void(* webrtc_datachannel_error_callback_t) (webrtc_data_channel_t *dc, const char *error, void *user_data)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Callback for DataChannel error.

Parameters
dcData channel
errorError message (null-terminated)
user_dataUser-provided context pointer

Definition at line 122 of file include/ascii-chat/network/webrtc/webrtc.h.

◆ webrtc_datachannel_message_callback_t

typedef void(* webrtc_datachannel_message_callback_t) (webrtc_data_channel_t *dc, const uint8_t *data, size_t size, void *user_data)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Callback for DataChannel message received.

Parameters
dcData channel
dataMessage data (binary)
sizeMessage size in bytes
user_dataUser-provided context pointer

Definition at line 114 of file include/ascii-chat/network/webrtc/webrtc.h.

◆ webrtc_datachannel_open_callback_t

typedef void(* webrtc_datachannel_open_callback_t) (webrtc_data_channel_t *dc, void *user_data)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Callback for DataChannel open event.

Parameters
dcData channel that opened
user_dataUser-provided context pointer

Definition at line 105 of file include/ascii-chat/network/webrtc/webrtc.h.

◆ webrtc_gathering_state_callback_t

typedef void(* webrtc_gathering_state_callback_t) (webrtc_peer_connection_t *pc, webrtc_gathering_state_t state, void *user_data)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Callback for ICE gathering state changes.

Parameters
pcPeer connection
stateNew gathering state
user_dataUser-provided context pointer

Definition at line 98 of file include/ascii-chat/network/webrtc/webrtc.h.

◆ webrtc_gathering_timeout_callback_t

typedef void(* webrtc_gathering_timeout_callback_t) (const uint8_t participant_id[16], uint32_t timeout_ms, uint64_t elapsed_ms, void *user_data)

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Callback when ICE candidate gathering is unusually slow.

Parameters
participant_idRemote participant UUID (16 bytes)
timeout_msConfigured timeout in milliseconds
elapsed_msActual elapsed time in milliseconds
user_dataUser context pointer

Called once when a peer connection's ICE gathering exceeds the configured timeout. Trickle ICE may still connect the peer, so this callback does not imply that the peer connection will be closed.

Definition at line 90 of file peer_manager.h.

◆ webrtc_local_candidate_callback_t

typedef void(* webrtc_local_candidate_callback_t) (webrtc_peer_connection_t *pc, const char *candidate, const char *mid, void *user_data)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Callback for local ICE candidate discovery.

Parameters
pcPeer connection
candidateICE candidate string (null-terminated)
midMedia stream ID (null-terminated)
user_dataUser-provided context pointer

Application should send this candidate to the remote peer via signaling channel (ACDS).

Definition at line 90 of file include/ascii-chat/network/webrtc/webrtc.h.

◆ webrtc_local_description_callback_t

typedef void(* webrtc_local_description_callback_t) (webrtc_peer_connection_t *pc, const char *sdp, const char *type, void *user_data)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Callback for local SDP offer/answer generation.

Parameters
pcPeer connection
sdpSDP string (null-terminated)
typeSDP type ("offer" or "answer")
user_dataUser-provided context pointer

Application should send this SDP to the remote peer via signaling channel (ACDS).

Definition at line 79 of file include/ascii-chat/network/webrtc/webrtc.h.

◆ webrtc_peer_connection_t

◆ webrtc_peer_manager_t

#include <lib/network/webrtc/peer_manager.c>

For pending ice candidate, this is the live record that ties candidate, mid, next together. The owning code creates it, updates it while work is active, and releases its handles and pointed-to storage before freeing the record.

WebRTC peer manager structure

◆ webrtc_send_ice_callback_t

typedef asciichat_error_t(* webrtc_send_ice_callback_t) (const uint8_t session_id[16], const uint8_t recipient_id[16], const char *candidate, const char *mid, void *user_data)

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Callback to send ICE candidate via ACDS signaling.

Parameters
session_idSession UUID (16 bytes)
recipient_idRecipient participant UUID (16 bytes, all zeros for broadcast)
candidateICE candidate string (null-terminated)
midMedia stream ID (null-terminated)
user_dataUser context pointer
Returns
ASCIICHAT_OK on success, error code on failure

Implementation should send PACKET_TYPE_ACIP_WEBRTC_ICE via ACDS.

Definition at line 134 of file peer_manager.h.

◆ webrtc_send_sdp_callback_t

typedef asciichat_error_t(* webrtc_send_sdp_callback_t) (const uint8_t session_id[16], const uint8_t recipient_id[16], const char *sdp_type, const char *sdp, void *user_data)

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Callback to send SDP via ACDS signaling.

Parameters
session_idSession UUID (16 bytes)
recipient_idRecipient participant UUID (16 bytes, all zeros for broadcast)
sdp_typeSDP type ("offer" or "answer")
sdpSDP string (null-terminated)
user_dataUser context pointer
Returns
ASCIICHAT_OK on success, error code on failure

Implementation should send PACKET_TYPE_ACIP_WEBRTC_SDP via ACDS.

Definition at line 121 of file peer_manager.h.

◆ webrtc_state_callback_t

typedef void(* webrtc_state_callback_t) (webrtc_peer_connection_t *pc, webrtc_state_t state, void *user_data)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Callback for state changes.

Parameters
pcPeer connection
stateNew connection state
user_dataUser-provided context pointer

Definition at line 68 of file include/ascii-chat/network/webrtc/webrtc.h.

◆ webrtc_transport_ready_callback_t

typedef void(* webrtc_transport_ready_callback_t) (acip_transport_t *transport, const uint8_t participant_id[16], void *user_data)

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Callback when DataChannel is ready and wrapped in ACIP transport.

Parameters
transportACIP transport wrapping the WebRTC DataChannel
participant_idRemote participant UUID (16 bytes)
user_dataUser context pointer

Delivered only by dispatch_ready on the thread that created the manager. The callback must not destroy the manager. The callback receives ownership of the transport and must either:

Definition at line 77 of file peer_manager.h.

Enumeration Type Documentation

◆ webrtc_gathering_state_t

#include <include/ascii-chat/network/webrtc/webrtc.h>

ICE gathering state.

Enumerator
WEBRTC_GATHERING_NEW 

Not started.

WEBRTC_GATHERING_GATHERING 

Gathering candidates.

WEBRTC_GATHERING_COMPLETE 

All candidates gathered.

Definition at line 56 of file include/ascii-chat/network/webrtc/webrtc.h.

56 {
webrtc_gathering_state_t
ICE gathering state.
@ WEBRTC_GATHERING_COMPLETE
All candidates gathered.
@ WEBRTC_GATHERING_GATHERING
Gathering candidates.
@ WEBRTC_GATHERING_NEW
Not started.

◆ webrtc_peer_role_t

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Peer connection role (server or client).

Enumerator
WEBRTC_ROLE_CREATOR 

Session creator - accepts offers, generates answers.

WEBRTC_ROLE_JOINER 

Session joiner - generates offers, receives answers.

Definition at line 60 of file peer_manager.h.

60 {
webrtc_peer_role_t
Peer connection role (server or client).
@ WEBRTC_ROLE_JOINER
Session joiner - generates offers, receives answers.
@ WEBRTC_ROLE_CREATOR
Session creator - accepts offers, generates answers.

◆ webrtc_state_t

#include <include/ascii-chat/network/webrtc/webrtc.h>

ICE, signaling, DataChannel, and callback settings for a WebRTC peer.

WebRTC connection state

Enumerator
WEBRTC_STATE_NEW 

Connection created but not started.

WEBRTC_STATE_CONNECTING 

ICE gathering/connection in progress.

WEBRTC_STATE_CONNECTED 

DataChannel established and ready.

WEBRTC_STATE_DISCONNECTED 

Connection lost.

WEBRTC_STATE_FAILED 

Connection failed (fatal).

WEBRTC_STATE_CLOSED 

Connection closed cleanly.

Definition at line 44 of file include/ascii-chat/network/webrtc/webrtc.h.

44 {
webrtc_state_t
ICE, signaling, DataChannel, and callback settings for a WebRTC peer.
@ WEBRTC_STATE_NEW
Connection created but not started.
@ WEBRTC_STATE_DISCONNECTED
Connection lost.
@ WEBRTC_STATE_FAILED
Connection failed (fatal).
@ WEBRTC_STATE_CLOSED
Connection closed cleanly.
@ WEBRTC_STATE_CONNECTING
ICE gathering/connection in progress.
@ WEBRTC_STATE_CONNECTED
DataChannel established and ready.

Function Documentation

◆ webrtc_add_remote_candidate()

asciichat_error_t webrtc_add_remote_candidate ( webrtc_peer_connection_t * pc,
const char * candidate,
const char * mid )

#include <include/ascii-chat/network/webrtc/webrtc.h>

Add remote ICE candidate.

Parameters
pcPeer connection
candidateICE candidate string (null-terminated)
midMedia stream ID (null-terminated, can be empty)
Returns
ASCIICHAT_OK on success, error code on failure

Adds a remote ICE candidate received via signaling channel.

Definition at line 790 of file lib/network/webrtc/webrtc.c.

790 {
791 if (!pc || !candidate) {
792 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
793 }
794
795 log_debug(" [4] Before libdatachannel - candidate: '%s' (len=%zu)", candidate, strlen(candidate));
796 log_debug(" [4] Before libdatachannel - mid: '%s' (len=%zu)", mid ? mid : "(null)", mid ? strlen(mid) : 0);
797
798 int result = rtcAddRemoteCandidate(pc->rtc_id, candidate, mid);
799 if (result != RTC_ERR_SUCCESS) {
800 return SET_ERRNO(ERROR_NETWORK, "Failed to add remote ICE candidate (rtc error %d)", result);
801 }
802
803 log_debug("Added remote ICE candidate (pc_id=%d)", pc->rtc_id);
804 return ASCIICHAT_OK;
805}
#define SET_ERRNO(code,...)
@ ERROR_NETWORK
Definition error_codes.h:77
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
int rtc_id
libdatachannel peer connection ID

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, log_debug, webrtc_peer_connection::rtc_id, and SET_ERRNO.

Referenced by ice_add_remote_candidate(), and webrtc_peer_manager_handle_ice().

◆ webrtc_close_datachannel()

void webrtc_close_datachannel ( webrtc_data_channel_t * dc)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Close a DataChannel.

Parameters
dcData channel to close

Closes the channel gracefully. Safe to call with NULL pointer.

Definition at line 938 of file lib/network/webrtc/webrtc.c.

938 {
939 if (!dc) {
940 SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel is NULL");
941 return;
942 }
943 if (dc->rtc_id < 0) {
944 atomic_store_bool(&dc->is_open, false);
945 return;
946 }
947
948 // Save the ID before deleting the native channel.
949 int dc_id = dc->rtc_id;
950
951 rtcDeleteDataChannel(dc_id);
952 log_debug("Closed DataChannel (dc_id=%d)", dc_id);
953 dc->rtc_id = -1;
954 atomic_store_bool(&dc->is_open, false);
955}
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
atomic_t is_open
Channel open state.
int rtc_id
libdatachannel data channel ID

References atomic_store_bool(), ERROR_INVALID_PARAM, webrtc_data_channel::is_open, log_debug, webrtc_data_channel::rtc_id, and SET_ERRNO.

Referenced by webrtc_close_peer_connection(), and webrtc_datachannel_destroy().

◆ webrtc_close_peer_connection()

void webrtc_close_peer_connection ( webrtc_peer_connection_t * pc)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Close and destroy a peer connection.

Parameters
pcPeer connection to close

Closes the connection gracefully and frees all resources. Safe to call with NULL pointer.

Definition at line 665 of file lib/network/webrtc/webrtc.c.

665 {
666 if (!pc) {
667 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid peer connection");
668 return;
669 }
670
671 // Close data channel if exists
672 if (pc->dc) {
674 pc->dc = NULL;
675 }
676
677 // Close peer connection
678 rtcDeletePeerConnection(pc->rtc_id);
679 webrtc_mapping_close(pc);
680 log_debug("Closed WebRTC peer connection (id=%d)", pc->rtc_id);
681
682 SAFE_FREE(pc);
683}
#define SAFE_FREE(ptr)
void webrtc_close_datachannel(webrtc_data_channel_t *dc)
Close a DataChannel.
webrtc_data_channel_t * dc
Primary data channel (if created/received).

References webrtc_peer_connection::dc, ERROR_INVALID_PARAM, log_debug, webrtc_peer_connection::rtc_id, SAFE_FREE, SET_ERRNO, and webrtc_close_datachannel().

◆ webrtc_create_datachannel()

asciichat_error_t webrtc_create_datachannel ( webrtc_peer_connection_t * pc,
const char * label,
webrtc_data_channel_t ** dc_out )

#include <include/ascii-chat/network/webrtc/webrtc.h>

Create a DataChannel (for connection initiator).

Parameters
pcPeer connection
labelChannel label (e.g., "acip")
dc_outOutput parameter for data channel handle
Returns
ASCIICHAT_OK on success, error code on failure

Creates a new DataChannel. The initiator should create the channel, while the responder receives it via the datachannel callback.

Definition at line 811 of file lib/network/webrtc/webrtc.c.

811 {
812 if (!pc || !label || !dc_out) {
813 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
814 }
815
816 // Native peers use DCEP. Browser offers advertise the separately negotiated
817 // ACIP channel and are handled in webrtc_set_remote_description().
818 webrtc_release_port(pc);
819 int dc_id = rtcCreateDataChannel(pc->rtc_id, label);
820 if (dc_id < 0) {
821 return SET_ERRNO(ERROR_NETWORK, "Failed to create data channel (rtc error %d)", dc_id);
822 }
823
824 // Allocate wrapper
826 if (!dc) {
827 rtcDeleteDataChannel(dc_id);
828 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate data channel wrapper");
829 }
830
831 dc->rtc_id = dc_id;
832 dc->pc = pc;
833 atomic_store_bool(&dc->is_open, false);
834
835 // Set up callbacks
836 rtcSetUserPointer(dc_id, dc);
837 rtcSetOpenCallback(dc_id, on_datachannel_open_adapter);
838 // Keep libdatachannel's receive queue intact until a consumer is installed.
839 // An adapter with no user callback would silently discard early peer hellos.
841 rtcSetMessageCallback(dc_id, on_datachannel_message_adapter);
842 rtcSetErrorCallback(dc_id, on_datachannel_error_adapter);
843
844 pc->dc = dc;
845 *dc_out = dc;
846
847 // Register data channel with debug naming system
848 NAMED_REGISTER_DATACHANNEL(dc, label, NULL);
849
850 log_debug("Created DataChannel '%s' (dc_id=%d, pc_id=%d)", label, dc_id, pc->rtc_id);
851 return ASCIICHAT_OK;
852}
#define SAFE_CALLOC(count, size, cast)
#define NAMED_REGISTER_DATACHANNEL(datachannel, name, parent_ptr)
Register a data channel with automatic format specifier.
@ ERROR_MEMORY
Definition error_codes.h:55
struct webrtc_data_channel webrtc_data_channel_t
webrtc_datachannel_message_callback_t on_datachannel_message
webrtc_peer_connection_t * pc
Parent peer connection.
webrtc_config_t config
Configuration with callbacks.

References ASCIICHAT_OK, atomic_store_bool(), webrtc_peer_connection::config, webrtc_peer_connection::dc, ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_NETWORK, webrtc_data_channel::is_open, log_debug, NAMED_REGISTER_DATACHANNEL, webrtc_config_t::on_datachannel_message, webrtc_data_channel::pc, webrtc_data_channel::rtc_id, webrtc_peer_connection::rtc_id, SAFE_CALLOC, and SET_ERRNO.

◆ webrtc_create_offer()

asciichat_error_t webrtc_create_offer ( webrtc_peer_connection_t * pc)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Create and set local SDP offer (for connection initiator).

Parameters
pcPeer connection
Returns
ASCIICHAT_OK on success, error code on failure

Triggers ICE gathering and local description callback with the SDP offer. Use this when initiating a connection to a remote peer.

Definition at line 740 of file lib/network/webrtc/webrtc.c.

740 {
741 if (!pc) {
742 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid peer connection");
743 }
744
745 // Set local description with NULL type to trigger offer generation
746 webrtc_release_port(pc);
747 int result = rtcSetLocalDescription(pc->rtc_id, NULL);
748 if (result != RTC_ERR_SUCCESS) {
749 return SET_ERRNO(ERROR_NETWORK, "Failed to create SDP offer (rtc error %d)", result);
750 }
751
752 log_debug("Creating SDP offer (pc_id=%d)", pc->rtc_id);
753 return ASCIICHAT_OK;
754}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, log_debug, webrtc_peer_connection::rtc_id, and SET_ERRNO.

◆ webrtc_create_peer_connection()

asciichat_error_t webrtc_create_peer_connection ( const webrtc_config_t * config,
webrtc_peer_connection_t ** pc_out )

#include <include/ascii-chat/network/webrtc/webrtc.h>

Create a new WebRTC peer connection.

Parameters
configConfiguration including ICE servers and callbacks
pc_outOutput parameter for peer connection handle
Returns
ASCIICHAT_OK on success, error code on failure

Creates a new peer connection with the specified configuration. The connection starts in WEBRTC_STATE_NEW state.

Definition at line 532 of file lib/network/webrtc/webrtc.c.

532 {
533 if (!config || !pc_out) {
534 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid config or output parameter");
535 }
536 *pc_out = NULL;
537 if ((config->stun_count && !config->stun_servers) || (config->turn_count && !config->turn_servers)) {
538 return SET_ERRNO(ERROR_INVALID_PARAM, "ICE server counts require server arrays");
539 }
540 if ((config->turn_username != NULL) != (config->turn_credential != NULL)) {
541 return SET_ERRNO(ERROR_INVALID_PARAM, "TURN overrides require both username and credential");
542 }
543
544 if (!lifecycle_is_initialized(&g_webrtc_lc)) {
545 return SET_ERRNO(ERROR_INIT, "WebRTC library not initialized");
546 }
547 if (config->relay_only && config->turn_count == 0) {
548 return SET_ERRNO(ERROR_INVALID_PARAM, "Relay only requires a TURN server with credentials");
549 }
550 for (size_t i = 0; i < config->turn_count; i++) {
551 const turn_server_t *server = &config->turn_servers[i];
552 const char *username = config->turn_username ? config->turn_username : server->username;
553 const char *credential = config->turn_credential ? config->turn_credential : server->credential;
554 if (!username[0] || !credential[0] || strlen(username) > 127 || strlen(credential) > 127) {
555 return SET_ERRNO(ERROR_INVALID_PARAM, "TURN server requires both username and credential");
556 }
557 if (strncmp(server->url, "turn:", 5) != 0 && strncmp(server->url, "turns:", 6) != 0) {
558 return SET_ERRNO(ERROR_INVALID_PARAM, "TURN server URL must start with turn: or turns:");
559 }
560 }
561
562 // Allocate peer connection wrapper
564 if (!pc) {
565 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate peer connection");
566 }
567
568 pc->port_reservation = INVALID_SOCKET_VALUE;
569 pc->config = *config; // Copy config
571 pc->dc = NULL;
572
573 // Build ICE server list for libdatachannel
574 const char **ice_servers = NULL;
575 defer(SAFE_FREE(ice_servers));
576 size_t ice_count = 0;
577 char *turn_urls = NULL;
578 defer(SAFE_FREE(turn_urls));
579
580 if (config->stun_count > 0 || config->turn_count > 0) {
581 ice_count = config->stun_count + config->turn_count;
582 ice_servers = SAFE_MALLOC(ice_count * sizeof(char *), const char **);
583 if (!ice_servers) {
584 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate ICE server list");
585 }
586
587 // Add STUN servers
588 for (size_t i = 0; i < config->stun_count; i++) {
589 ice_servers[i] = config->stun_servers[i].host;
590 }
591
592 // Add TURN servers
593 if (config->turn_count > 0) {
594 turn_urls = SAFE_CALLOC(config->turn_count, WEBRTC_TURN_URL_BUFFER_SIZE, char *);
595 if (!turn_urls) {
596 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate authenticated TURN URLs");
597 }
598 }
599 for (size_t i = 0; i < config->turn_count; i++) {
600 const turn_server_t *server = &config->turn_servers[i];
601 char username[WEBRTC_ESCAPED_AUTH_BUFFER_SIZE];
602 char credential[WEBRTC_ESCAPED_AUTH_BUFFER_SIZE];
603 encode_turn_userinfo(config->turn_username ? config->turn_username : server->username, username, sizeof(username));
604 encode_turn_userinfo(config->turn_credential ? config->turn_credential : server->credential, credential, sizeof(credential));
605 const char *address = strchr(server->url, ':') + 1;
606 while (*address == '/')
607 address++;
608 SAFE_SNPRINTF(turn_urls + i * WEBRTC_TURN_URL_BUFFER_SIZE, WEBRTC_TURN_URL_BUFFER_SIZE, "%.*s%s:%s@%s", (int)(strchr(server->url, ':') - server->url + 1), server->url, username, credential,
609 address);
610 ice_servers[config->stun_count + i] = turn_urls + i * WEBRTC_TURN_URL_BUFFER_SIZE;
611 }
612 }
613
614 // Create libdatachannel configuration
615 rtcConfiguration rtc_config;
616 memset(&rtc_config, 0, sizeof(rtc_config));
617 // libdatachannel raises SO_SNDBUF to at least the local maximum message size.
618 // Keep both limits equal so the fixed SCTP reservation covers retained bytes.
619 rtc_config.maxMessageSize = ACIP_OUTBOUND_SCTP_RESERVE;
620 rtc_config.bindAddress = config->bind_address;
621 rtc_config.iceServers = ice_servers;
622 rtc_config.iceServersCount = (int)ice_count;
623 rtc_config.iceTransportPolicy = config->relay_only ? RTC_TRANSPORT_POLICY_RELAY : RTC_TRANSPORT_POLICY_ALL;
624 if (rtc_config.bindAddress && rtc_config.bindAddress[0]) {
625 log_info("Binding WebRTC ICE sockets to %s", rtc_config.bindAddress);
626 }
627
628 webrtc_mapping_prepare(pc, &rtc_config);
629
630 // Create peer connection
631 int pc_id = rtcCreatePeerConnection(&rtc_config);
632 SAFE_FREE(turn_urls);
633 SAFE_FREE(ice_servers);
634
635 if (pc_id < 0) {
636 webrtc_mapping_close(pc);
637 return SET_ERRNO(ERROR_NETWORK, "Failed to create peer connection (rtc error %d)", pc_id);
638 }
639
640 pc->rtc_id = pc_id;
641
642 // Initialize gathering state
643 atomic_store_u64(&pc->gathering_state, WEBRTC_GATHERING_NEW);
644 atomic_store_u64(&pc->gathering_start_time_ms, 0);
645
646 // Set up callbacks
647 rtcSetUserPointer(pc_id, pc);
648 rtcSetStateChangeCallback(pc_id, on_state_change_adapter);
649 rtcSetGatheringStateChangeCallback(pc_id, on_gathering_state_change_adapter);
650 rtcSetLocalDescriptionCallback(pc_id, on_local_description_adapter);
651 rtcSetLocalCandidateCallback(pc_id, on_local_candidate_adapter);
652 rtcSetDataChannelCallback(pc_id, on_datachannel_adapter);
653
654 /* Register peer connection with named registry */
656 snprintf(pc_name, sizeof(pc_name), "webrtc_peer_connection:%d", pc_id);
657 NAMED_REGISTER(pc, pc_name, "webrtc_peer_connection_t", "0x%tx", NULL);
658
659 *pc_out = pc;
660 pc = NULL;
661 log_debug("Created WebRTC peer connection (id=%d)", pc_id);
662 return ASCIICHAT_OK;
663}
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
#define ACIP_OUTBOUND_SCTP_RESERVE
#define SAFE_MALLOC(size, cast)
#define SAFE_SNPRINTF(buffer, buffer_size,...)
#define SAFE_CALLOC_DEFER_FREE(name, count, size, cast)
#define NAMED_REGISTER(ptr, name, type, fmt, parent_ptr)
Register any pointer with base name, type, format spec, and location (auto-suffix).
@ ERROR_INIT
Definition error_codes.h:60
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
turn_server_t
Definition turn.h:106
struct webrtc_peer_connection webrtc_peer_connection_t
#define NETWORK_WEBRTC_PC_NAME_BUFFER_SIZE
#define WEBRTC_ESCAPED_AUTH_BUFFER_SIZE
#define WEBRTC_TURN_URL_BUFFER_SIZE
const char * turn_username
Optional credential override, including full ACDS usernames.
size_t stun_count
Number of STUN servers.
bool relay_only
Restrict ICE to TURN relay candidates.
turn_server_t * turn_servers
Array of TURN servers.
stun_server_t * stun_servers
Array of STUN servers.
size_t turn_count
Number of TURN servers.
const char * bind_address
Optional local interface address for ICE sockets.
const char * turn_credential
Optional credential override.

References ACIP_OUTBOUND_SCTP_RESERVE, ASCIICHAT_OK, atomic_store_u64(), webrtc_config_t::bind_address, webrtc_peer_connection::config, webrtc_peer_connection::dc, ERROR_INIT, ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_NETWORK, webrtc_peer_connection::gathering_start_time_ms, webrtc_peer_connection::gathering_state, log_debug, log_info, NAMED_REGISTER, NETWORK_WEBRTC_PC_NAME_BUFFER_SIZE, webrtc_peer_connection::port_reservation, webrtc_config_t::relay_only, webrtc_peer_connection::rtc_id, SAFE_CALLOC, SAFE_CALLOC_DEFER_FREE, SAFE_FREE, SAFE_MALLOC, SAFE_SNPRINTF, SET_ERRNO, webrtc_peer_connection::state, webrtc_config_t::stun_count, webrtc_config_t::stun_servers, webrtc_config_t::turn_count, webrtc_config_t::turn_credential, turn_server_t, webrtc_config_t::turn_servers, webrtc_config_t::turn_username, WEBRTC_ESCAPED_AUTH_BUFFER_SIZE, WEBRTC_GATHERING_NEW, WEBRTC_STATE_NEW, and WEBRTC_TURN_URL_BUFFER_SIZE.

◆ webrtc_datachannel_destroy()

void webrtc_datachannel_destroy ( webrtc_data_channel_t * dc)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Destroy a DataChannel and free resources.

Parameters
dcData channel to destroy

Frees all resources associated with the DataChannel. Automatically closes the channel if still open. Safe to call with NULL pointer.

Definition at line 1002 of file lib/network/webrtc/webrtc.c.

1002 {
1003 if (!dc) {
1004 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid null data channel");
1005 return;
1006 }
1007
1008 // Close if still open, then free the wrapper.
1010 SAFE_FREE(dc);
1011}

References ERROR_INVALID_PARAM, SAFE_FREE, SET_ERRNO, and webrtc_close_datachannel().

◆ webrtc_datachannel_get_buffered_amount()

asciichat_error_t webrtc_datachannel_get_buffered_amount ( webrtc_data_channel_t * dc,
size_t * amount )

#include <include/ascii-chat/network/webrtc/webrtc.h>

Definition at line 854 of file lib/network/webrtc/webrtc.c.

854 {
855 if (!dc || dc->rtc_id < 0 || !amount)
856 return SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel and amount are required");
857 int result = rtcGetBufferedAmount(dc->rtc_id);
858 if (result < 0)
859 return SET_ERRNO(ERROR_NETWORK, "Failed to query DataChannel buffered amount");
860 *amount = (size_t)result;
861 return ASCIICHAT_OK;
862}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, webrtc_data_channel::rtc_id, and SET_ERRNO.

◆ webrtc_datachannel_get_label()

const char * webrtc_datachannel_get_label ( webrtc_data_channel_t * dc)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Get DataChannel label.

Parameters
dcData channel
Returns
Label string (null-terminated), or NULL on error

Definition at line 923 of file lib/network/webrtc/webrtc.c.

923 {
924 if (!dc || dc->rtc_id < 0) {
925 SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel is NULL");
926 return NULL;
927 }
928
929 static char label[NETWORK_WEBRTC_LABEL_BUFFER_SIZE];
930 int result = rtcGetDataChannelLabel(dc->rtc_id, label, sizeof(label));
931 if (result < 0) {
932 return NULL;
933 }
934
935 return label;
936}
#define NETWORK_WEBRTC_LABEL_BUFFER_SIZE

References ERROR_INVALID_PARAM, NETWORK_WEBRTC_LABEL_BUFFER_SIZE, webrtc_data_channel::rtc_id, and SET_ERRNO.

◆ webrtc_datachannel_get_max_message_size()

asciichat_error_t webrtc_datachannel_get_max_message_size ( webrtc_data_channel_t * dc,
size_t * size )

#include <include/ascii-chat/network/webrtc/webrtc.h>

Definition at line 864 of file lib/network/webrtc/webrtc.c.

864 {
865 if (!dc || dc->rtc_id < 0 || !size)
866 return SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel and max message size are required");
867 int result = rtcMaxMessageSize(dc->rtc_id);
868 if (result <= 0)
869 return SET_ERRNO(ERROR_NETWORK, "Failed to query DataChannel max message size");
870 *size = (size_t)result;
871 return ASCIICHAT_OK;
872}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, webrtc_data_channel::rtc_id, and SET_ERRNO.

◆ webrtc_datachannel_is_open()

bool webrtc_datachannel_is_open ( webrtc_data_channel_t * dc)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Check if DataChannel is open and ready.

Parameters
dcData channel
Returns
true if open, false otherwise

Definition at line 907 of file lib/network/webrtc/webrtc.c.

907 {
908 if (!dc) {
909 SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel is NULL");
910 return false;
911 }
912 return dc->rtc_id >= 0 && atomic_load_bool(&dc->is_open);
913}
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.

References atomic_load_bool(), ERROR_INVALID_PARAM, webrtc_data_channel::is_open, webrtc_data_channel::rtc_id, and SET_ERRNO.

◆ webrtc_datachannel_send()

asciichat_error_t webrtc_datachannel_send ( webrtc_data_channel_t * dc,
const uint8_t * data,
size_t size )

#include <include/ascii-chat/network/webrtc/webrtc.h>

Send data over DataChannel.

Parameters
dcData channel
dataData buffer (binary)
sizeData size in bytes
Returns
ASCIICHAT_OK on success, error code on failure

Sends binary data over the DataChannel. Returns error if channel is not open.

Definition at line 874 of file lib/network/webrtc/webrtc.c.

874 {
875 if (!dc || dc->rtc_id < 0 || !data) {
876 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
877 }
878
879 if (!atomic_load_bool(&dc->is_open)) {
880 log_error("★ WEBRTC_DATACHANNEL_SEND: Channel not open! size=%zu, dc->rtc_id=%d", size, dc ? dc->rtc_id : -1);
881 return SET_ERRNO(ERROR_NETWORK, "DataChannel not open");
882 }
883
884 // Log packet details at network layer (debug level for normal operation)
885 if (size >= 20) {
886 const uint8_t *pkt = (const uint8_t *)data;
887 log_dev("★ RTCSENDMESSAGE_BEFORE: dc_id=%d, size=%zu, first_20_bytes: %02x%02x%02x%02x %02x%02x%02x%02x "
888 "%02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x",
889 dc->rtc_id, size, pkt[0], pkt[1], pkt[2], pkt[3], pkt[4], pkt[5], pkt[6], pkt[7], pkt[8], pkt[9], pkt[10], pkt[11], pkt[12], pkt[13], pkt[14], pkt[15], pkt[16], pkt[17], pkt[18], pkt[19]);
890 } else {
891 log_dev("★ RTCSENDMESSAGE_BEFORE: dc_id=%d, size=%zu (too small to log content)", dc->rtc_id, size);
892 }
893
894 int result = rtcSendMessage(dc->rtc_id, (const char *)data, (int)size);
895
896 log_dev("★ RTCSENDMESSAGE_AFTER: dc_id=%d, rtcSendMessage returned %d for size=%zu", dc->rtc_id, result, size);
897
898 if (result < 0) {
899 log_error("★ WEBRTC_DATACHANNEL_SEND: FAILED with error code %d", result);
900 return SET_ERRNO(ERROR_NETWORK, "Failed to send data (rtc error %d)", result);
901 }
902
903 log_dev("★ WEBRTC_DATACHANNEL_SEND: SUCCESS - sent %zu bytes", size);
904 return ASCIICHAT_OK;
905}
unsigned char uint8_t
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604

References ASCIICHAT_OK, atomic_load_bool(), ERROR_INVALID_PARAM, ERROR_NETWORK, webrtc_data_channel::is_open, log_dev, log_error, webrtc_data_channel::rtc_id, and SET_ERRNO.

◆ webrtc_datachannel_set_callbacks()

asciichat_error_t webrtc_datachannel_set_callbacks ( webrtc_data_channel_t * dc,
const webrtc_datachannel_callbacks_t * callbacks )

#include <include/ascii-chat/network/webrtc/webrtc.h>

Set DataChannel callbacks.

Parameters
dcData channel
callbacksCallback structure
Returns
ASCIICHAT_OK on success, error code on failure

Registers callbacks for DataChannel events. Any NULL callback pointer is ignored.

Definition at line 961 of file lib/network/webrtc/webrtc.c.

961 {
962 if (!dc) {
963 return SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel is NULL");
964 }
965
966 if (!callbacks) {
967 return SET_ERRNO(ERROR_INVALID_PARAM, "Callbacks struct is NULL");
968 }
969
970 // Store user callbacks in the data channel struct
971 dc->user_on_open = callbacks->on_open;
972 dc->user_on_close = callbacks->on_close;
973 dc->user_on_error = callbacks->on_error;
974 dc->user_on_message = callbacks->on_message;
975 dc->user_data = callbacks->user_data;
976
977 // Register adapter functions with libdatachannel (adapters use correct signature)
978 // The adapters will look up our stored callbacks and invoke them with proper types
979 if (callbacks->on_open) {
980 rtcSetOpenCallback(dc->rtc_id, on_datachannel_open_adapter);
981 }
982
983 if (callbacks->on_close) {
984 rtcSetClosedCallback(dc->rtc_id, on_datachannel_closed_adapter);
985 }
986
987 if (callbacks->on_error) {
988 rtcSetErrorCallback(dc->rtc_id, on_datachannel_error_adapter);
989 }
990
991 if (callbacks->on_message) {
992 rtcSetMessageCallback(dc->rtc_id, on_datachannel_message_adapter);
993 }
994
995 // Set user pointer to the data channel so adapters can retrieve it
996 rtcSetUserPointer(dc->rtc_id, dc);
997
998 log_debug("Set DataChannel callbacks (dc_id=%d)", dc->rtc_id);
999 return ASCIICHAT_OK;
1000}
void(* user_on_message)(webrtc_data_channel_t *dc, const uint8_t *data, size_t len, void *user_data)
Message callback.
void(* user_on_close)(webrtc_data_channel_t *dc, void *user_data)
Close callback.
void(* user_on_open)(webrtc_data_channel_t *dc, void *user_data)
Open callback.
void * user_data
User data for per-channel callbacks.
void(* user_on_error)(webrtc_data_channel_t *dc, const char *error, void *user_data)
Error callback.
void(* on_close)(webrtc_data_channel_t *dc, void *user_data)
Channel closed.
void(* on_error)(webrtc_data_channel_t *dc, const char *error, void *user_data)
Error occurred.
void(* on_open)(webrtc_data_channel_t *dc, void *user_data)
Channel opened.
void(* on_message)(webrtc_data_channel_t *dc, const uint8_t *data, size_t len, void *user_data)
Message received.

References ASCIICHAT_OK, ERROR_INVALID_PARAM, log_debug, webrtc_datachannel_callbacks_t::on_close, webrtc_datachannel_callbacks_t::on_error, webrtc_datachannel_callbacks_t::on_message, webrtc_datachannel_callbacks_t::on_open, webrtc_data_channel::rtc_id, SET_ERRNO, webrtc_data_channel::user_data, webrtc_datachannel_callbacks_t::user_data, webrtc_data_channel::user_on_close, webrtc_data_channel::user_on_error, webrtc_data_channel::user_on_message, and webrtc_data_channel::user_on_open.

◆ webrtc_datachannel_set_open_state()

void webrtc_datachannel_set_open_state ( webrtc_data_channel_t * dc,
bool is_open )

#include <include/ascii-chat/network/webrtc/webrtc.h>

Set DataChannel open state (internal use).

Parameters
dcData channel
is_openOpen state to set

Internal function for transport layer to manually set open state when callbacks are replaced after the DataChannel is already open.

Definition at line 915 of file lib/network/webrtc/webrtc.c.

915 {
916 if (!dc) {
917 SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel is NULL");
918 return;
919 }
920 atomic_store_bool(&dc->is_open, is_open);
921}

References atomic_store_bool(), ERROR_INVALID_PARAM, webrtc_data_channel::is_open, and SET_ERRNO.

◆ webrtc_destroy()

void webrtc_destroy ( void )

#include <include/ascii-chat/network/webrtc/webrtc.h>

Cleanup WebRTC library resources.

Should be called at program exit after all connections are closed. Thread-safe and idempotent.

Definition at line 511 of file lib/network/webrtc/webrtc.c.

511 {
512 webrtc_release();
513}

◆ webrtc_get_gathering_state()

webrtc_gathering_state_t webrtc_get_gathering_state ( webrtc_peer_connection_t * pc)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Get current ICE gathering state.

Parameters
pcPeer connection
Returns
Current gathering state

Definition at line 693 of file lib/network/webrtc/webrtc.c.

693 {
694 if (!pc) {
695 log_warn("Peer connection is NULL");
697 }
699}
uint64_t atomic_load_u64(const atomic_t *a)
Atomically load a uint64_t value.
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
atomic_t gathering_state
Current ICE gathering state.

References atomic_load_u64(), webrtc_peer_connection::gathering_state, log_warn, and WEBRTC_GATHERING_NEW.

Referenced by webrtc_peer_manager_check_gathering_timeouts().

◆ webrtc_get_rtc_id()

int webrtc_get_rtc_id ( webrtc_peer_connection_t * pc)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Get the internal libdatachannel peer connection ID.

Helper function for C++ code that needs access to internal rtc_id without exposing the full structure definition.

Parameters
pcPeer connection
Returns
libdatachannel peer connection ID, or -1 if pc is NULL

Definition at line 1051 of file lib/network/webrtc/webrtc.c.

1051 {
1052 if (!pc) {
1053 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid null peer connectiont");
1054 return -1;
1055 }
1056 return pc->rtc_id;
1057}

References ERROR_INVALID_PARAM, webrtc_peer_connection::rtc_id, and SET_ERRNO.

Referenced by ice_get_selected_pair_impl().

◆ webrtc_get_state()

webrtc_state_t webrtc_get_state ( webrtc_peer_connection_t * pc)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Get current connection state.

Parameters
pcPeer connection
Returns
Current state

Definition at line 685 of file lib/network/webrtc/webrtc.c.

685 {
686 if (!pc) {
687 log_warn("Peer connection is NULL");
688 return WEBRTC_STATE_CLOSED;
689 }
691}
atomic_t state
Current connection state.

References atomic_load_u64(), log_warn, webrtc_peer_connection::state, and WEBRTC_STATE_CLOSED.

Referenced by ice_is_connected(), webrtc_peer_manager_check_gathering_timeouts(), webrtc_peer_manager_get_state(), and webrtc_peer_manager_handle_sdp().

◆ webrtc_get_user_data()

void * webrtc_get_user_data ( webrtc_peer_connection_t * pc)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Get user data pointer from connection.

Parameters
pcPeer connection
Returns
User data pointer (from webrtc_config_t)

Definition at line 728 of file lib/network/webrtc/webrtc.c.

728 {
729 if (!pc) {
730 log_warn("Peer connection is NULL");
731 return NULL;
732 }
733 return pc->config.user_data;
734}
void * user_data
Passed to all callbacks.

References webrtc_peer_connection::config, log_warn, and webrtc_config_t::user_data.

◆ webrtc_init()

asciichat_error_t webrtc_init ( void )

#include <include/ascii-chat/network/webrtc/webrtc.h>

Initialize WebRTC library (libdatachannel).

Returns
ASCIICHAT_OK on success, error code on failure

Must be called once before creating any peer connections. Thread-safe and idempotent (safe to call multiple times).

Definition at line 507 of file lib/network/webrtc/webrtc.c.

507 {
508 return webrtc_ensure_initialized();
509}

◆ webrtc_is_gathering_timed_out()

bool webrtc_is_gathering_timed_out ( webrtc_peer_connection_t * pc,
uint32_t timeout_ms )

#include <include/ascii-chat/network/webrtc/webrtc.h>

Check if ICE gathering has timed out.

Parameters
pcPeer connection
timeout_msTimeout in milliseconds
Returns
true if gathering is in progress and has exceeded timeout, false otherwise

Definition at line 701 of file lib/network/webrtc/webrtc.c.

701 {
702 if (!pc) {
703 return false;
704 }
705
706 // Only check timeout if we're actively gathering
708 return false;
709 }
710
711 // If gathering hasn't started yet (start_time == 0), no timeout
712 uint64_t gathering_start_time_ms = atomic_load_u64(&pc->gathering_start_time_ms);
713 if (gathering_start_time_ms == 0) {
714 return false;
715 }
716
717 // Check if elapsed time exceeds timeout
718 uint64_t current_time_ms = platform_get_monotonic_time_us() / 1000;
719 uint64_t elapsed_ms = current_time_ms - gathering_start_time_ms;
720
721 if (elapsed_ms > timeout_ms) {
722 return true;
723 }
724
725 return false;
726}
unsigned long long uint64_t
atomic_t gathering_start_time_ms
When gathering started (platform_get_time_ms).

References atomic_load_u64(), webrtc_peer_connection::gathering_start_time_ms, webrtc_peer_connection::gathering_state, and WEBRTC_GATHERING_GATHERING.

Referenced by webrtc_peer_manager_check_gathering_timeouts().

◆ webrtc_peer_connection_close()

void webrtc_peer_connection_close ( webrtc_peer_connection_t * pc)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Close a peer connection.

Parameters
pcPeer connection to close

Closes the peer connection gracefully. Safe to call with NULL pointer.

Definition at line 1017 of file lib/network/webrtc/webrtc.c.

1017 {
1018 if (!pc) {
1019 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid null peer connectiont");
1020 return;
1021 }
1022
1023 rtcClose(pc->rtc_id);
1024 webrtc_mapping_close(pc);
1025 log_debug("Closed peer connection (pc_id=%d)", pc->rtc_id);
1026}

References ERROR_INVALID_PARAM, log_debug, webrtc_peer_connection::rtc_id, and SET_ERRNO.

◆ webrtc_peer_connection_destroy()

void webrtc_peer_connection_destroy ( webrtc_peer_connection_t * pc)

#include <include/ascii-chat/network/webrtc/webrtc.h>

Destroy a peer connection and free resources.

Parameters
pcPeer connection to destroy

Frees all resources associated with the peer connection. Automatically closes the connection if still open. Safe to call with NULL pointer.

Definition at line 1028 of file lib/network/webrtc/webrtc.c.

1028 {
1029 if (!pc) {
1030 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid null peer connectiont");
1031 return;
1032 }
1033
1034 // Close and delete peer connection
1035 rtcDeletePeerConnection(pc->rtc_id);
1036 webrtc_mapping_close(pc);
1037 log_debug("Destroyed peer connection (pc_id=%d)", pc->rtc_id);
1038
1039 SAFE_FREE(pc);
1040}

References ERROR_INVALID_PARAM, log_debug, webrtc_peer_connection::rtc_id, SAFE_FREE, and SET_ERRNO.

◆ webrtc_peer_manager_check_gathering_timeouts()

int webrtc_peer_manager_check_gathering_timeouts ( webrtc_peer_manager_t * manager,
uint32_t timeout_ms )

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Report slow ICE gathering and remove failed connections.

Parameters
managerPeer manager
timeout_msTimeout threshold in milliseconds
Returns
Number of failed or closed peer connections removed

Iterates through all active peer connections and checks if ICE gathering has exceeded the specified timeout or the connection has failed or closed. Slow gathering is reported once but left active because trickle ICE may still establish the connection. Failed or closed connections are removed.

This should be called periodically (e.g., every 100ms) during connection establishment to detect and handle gathering failures.

Note
Thread-safe - uses internal locking

Definition at line 839 of file peer_manager.c.

839 {
840 if (!manager) {
841 return 0;
842 }
843
844 int timeout_count = 0;
845 peer_entry_t *peer = NULL, *tmp = NULL;
846
847 mutex_lock(&manager->signaling_mutex);
848 mutex_lock(&manager->peers_mutex);
849
850 // Iterate through all peers and check for gathering timeout
851 HASH_ITER(hh, manager->peers, peer, tmp) {
852 if (!peer || !peer->pc) {
853 continue;
854 }
855
856 // Trickle ICE can connect before gathering completes. Report a slow gather,
857 // but keep the peer alive until libdatachannel reports a failed connection.
858 webrtc_state_t connection_state = webrtc_get_state(peer->pc);
859 bool gathering_timed_out = webrtc_is_gathering_timed_out(peer->pc, timeout_ms);
860 if (gathering_timed_out && !peer->gathering_timeout_reported) {
861 peer->gathering_timeout_reported = true;
862 if (manager->config.on_gathering_timeout) {
863 manager->config.on_gathering_timeout(peer->participant_id, timeout_ms, timeout_ms, manager->config.user_data);
864 }
865 log_warn("ICE gathering exceeded %ums; keeping peer alive while trickle ICE continues", timeout_ms);
866 }
867
868 uint64_t handshake_started = atomic_load_u64(&peer->handshake_started_ns);
869 bool handshake_expired = handshake_started && !atomic_load_bool(&peer->security_ready) && time_elapsed_ns(handshake_started, time_get_ns()) > 30 * NS_PER_SEC_INT;
870 if (handshake_expired || connection_state == WEBRTC_STATE_FAILED || connection_state == WEBRTC_STATE_CLOSED) {
872
873 log_error("WebRTC negotiation failed for peer (participant_id=%02x%02x%02x%02x..., timeout=%ums, "
874 "gathering=%d, connection=%d)",
875 peer->participant_id[0], peer->participant_id[1], peer->participant_id[2], peer->participant_id[3], timeout_ms, state, connection_state);
876
877 // Remove and close peers whose ICE connection has actually failed.
878 remove_peer_locked(manager, peer);
879 timeout_count++;
880
881 log_info("Closed and removed timed-out peer connection (count: %d)", timeout_count);
882 }
883 }
884
885 mutex_unlock(&manager->peers_mutex);
886 mutex_unlock(&manager->signaling_mutex);
887
888 return timeout_count;
889}
#define NS_PER_SEC_INT
Definition time.h:173
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:126
webrtc_state_t webrtc_get_state(webrtc_peer_connection_t *pc)
Get current connection state.
webrtc_gathering_state_t webrtc_get_gathering_state(webrtc_peer_connection_t *pc)
Get current ICE gathering state.
bool webrtc_is_gathering_timed_out(webrtc_peer_connection_t *pc, uint32_t timeout_ms)
Check if ICE gathering has timed out.
webrtc peer manager is intentionally a small, concrete record. Fields such as role,...
webrtc_peer_connection_t * pc
WebRTC peer connection.
atomic_t handshake_started_ns
uint8_t participant_id[16]
Remote participant UUID (hash key).
bool gathering_timeout_reported
ICE gathering timed out while trickle candidates may still connect.
atomic_t security_ready
void * user_data
Passed to callbacks.
webrtc_gathering_timeout_callback_t on_gathering_timeout
Called when ICE gathering times out.
mutex_t peers_mutex
Protect peers hash table.
peer_entry_t * peers
Hash table of peer connections.
webrtc_peer_manager_config_t config
Manager configuration.
mutex_t signaling_mutex
Serialize SDP and ICE updates for each peer.

References atomic_load_bool(), atomic_load_u64(), webrtc_peer_manager::config, peer_entry_t::gathering_timeout_reported, peer_entry_t::handshake_started_ns, log_error, log_info, log_warn, NS_PER_SEC_INT, webrtc_peer_manager_config_t::on_gathering_timeout, peer_entry_t::participant_id, peer_entry_t::pc, webrtc_peer_manager::peers, webrtc_peer_manager::peers_mutex, peer_entry_t::security_ready, webrtc_peer_manager::signaling_mutex, time_elapsed_ns(), webrtc_peer_manager_config_t::user_data, webrtc_get_gathering_state(), webrtc_get_state(), webrtc_is_gathering_timed_out(), WEBRTC_STATE_CLOSED, and WEBRTC_STATE_FAILED.

◆ webrtc_peer_manager_connect()

asciichat_error_t webrtc_peer_manager_connect ( webrtc_peer_manager_t * manager,
const uint8_t session_id[16],
const uint8_t participant_id[16] )

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Initiate connection to remote peer (joiner role only).

Parameters
managerPeer manager
session_idSession UUID (16 bytes)
participant_idRemote participant UUID to connect to (16 bytes)
Returns
ASCIICHAT_OK on success, error code on failure

Creates peer connection, generates SDP offer, and sends via signaling. Only valid for WEBRTC_ROLE_JOINER (session joiners initiate connections).

Creator role uses webrtc_peer_manager_handle_sdp() to accept offers instead.

Definition at line 773 of file peer_manager.c.

773 {
774 if (!manager || !session_id || !participant_id) {
775 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
776 }
777
778 if (manager->role != WEBRTC_ROLE_JOINER) {
779 return SET_ERRNO(ERROR_INVALID_PARAM, "Only joiners can initiate connections");
780 }
781
782 log_debug("session_id=%02x%02x%02x%02x..., participant_id=%02x%02x%02x%02x...", session_id[0], session_id[1], session_id[2], session_id[3], participant_id[0], participant_id[1], participant_id[2],
783 participant_id[3]);
784
785 mutex_lock(&manager->peers_mutex);
786
787 // Create peer connection
788 peer_entry_t *peer;
789 asciichat_error_t result = create_peer_connection_locked(manager, session_id, participant_id, &peer);
790 if (result != ASCIICHAT_OK) {
791 mutex_unlock(&manager->peers_mutex);
792 return SET_ERRNO(result, "Failed to create peer connection");
793 }
794
795 mutex_unlock(&manager->peers_mutex);
796
797 // Note: SDP offer is automatically created by libdatachannel when rtcCreateDataChannel() is called
798 // The on_local_description callback will be triggered automatically with the offer
799 // No need to manually call webrtc_create_offer() - doing so causes "Unexpected local description" error
800
801 log_info("Initiated WebRTC connection to participant (offer auto-created by DataChannel)");
802
803 return ASCIICHAT_OK;
804}
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
uint8_t session_id[SESSION_ID_SIZE]
uint8_t participant_id[SESSION_ID_SIZE]
webrtc_peer_role_t role
Session role.

References ASCIICHAT_OK, ERROR_INVALID_PARAM, log_debug, log_info, participant_id, webrtc_peer_manager::peers_mutex, webrtc_peer_manager::role, session_id, SESSION_ID_SIZE, SET_ERRNO, and WEBRTC_ROLE_JOINER.

◆ webrtc_peer_manager_create()

asciichat_error_t webrtc_peer_manager_create ( const webrtc_peer_manager_config_t * config,
const webrtc_signaling_callbacks_t * signaling_callbacks,
webrtc_peer_manager_t ** manager_out )

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Create a WebRTC peer manager.

Parameters
configManager configuration
signaling_callbacksCallbacks for sending SDP/ICE
manager_outOutput parameter for manager handle
Returns
ASCIICHAT_OK on success, error code on failure

Creates a manager for WebRTC peer connections. The manager handles:

  • Peer connection creation and lifecycle
  • SDP offer/answer generation and processing
  • ICE candidate exchange
  • ACIP transport wrapping when DataChannel opens

Definition at line 522 of file peer_manager.c.

522 {
523 if (!config || !signaling_callbacks || !manager_out) {
524 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
525 }
526 *manager_out = NULL;
527
528 if (!signaling_callbacks->send_sdp || !signaling_callbacks->send_ice) {
529 return SET_ERRNO(ERROR_INVALID_PARAM, "Signaling callbacks required");
530 }
531 if (config->relay_only && config->turn_count == 0) {
532 return SET_ERRNO(ERROR_INVALID_PARAM, "Relay only requires a TURN server with credentials");
533 }
534
535 // Allocate manager
537 if (!manager) {
538 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate peer manager");
539 }
540
541 memcpy(&manager->config, config, sizeof(*config));
542 memcpy(&manager->signaling, signaling_callbacks, sizeof(*signaling_callbacks));
543 manager->role = config->role;
544 manager->owner_thread = thread_self();
545 manager->peers = NULL;
546 manager->pending_ice = NULL;
547 manager->pending_ice_count = 0;
548
549 if (mutex_init(&manager->peers_mutex, "peers") != 0) {
550 SAFE_FREE(manager);
551 return SET_ERRNO(ERROR_INTERNAL, "Failed to initialize peers mutex");
552 }
553 if (mutex_init(&manager->signaling_mutex, "webrtc_signaling") != 0) {
554 mutex_destroy(&manager->peers_mutex);
555 SAFE_FREE(manager);
556 return SET_ERRNO(ERROR_INTERNAL, "Failed to initialize WebRTC signaling mutex");
557 }
558
559 log_info("Created WebRTC peer manager (role: %s)", manager->role == WEBRTC_ROLE_CREATOR ? "creator" : "joiner");
560
561 *manager_out = manager;
562 return ASCIICHAT_OK;
563}
@ ERROR_INTERNAL
Definition error_codes.h:94
struct webrtc_peer_manager webrtc_peer_manager_t
For pending ice candidate, this is the live record that ties candidate, mid, next together....
webrtc_peer_role_t role
Session role (creator or joiner).
size_t turn_count
Number of TURN servers.
bool relay_only
Restrict ICE to TURN relay candidates.
pending_ice_candidate_t * pending_ice
ICE delivered before the peer's remote SDP.
webrtc_signaling_callbacks_t signaling
Signaling callbacks.
thread_id_t owner_thread
Thread responsible for delivering ready transports.
webrtc_send_sdp_callback_t send_sdp
Send SDP via ACDS.
webrtc_send_ice_callback_t send_ice
Send ICE via ACDS.

References ASCIICHAT_OK, webrtc_peer_manager::config, ERROR_INTERNAL, ERROR_INVALID_PARAM, ERROR_MEMORY, log_info, webrtc_peer_manager::owner_thread, webrtc_peer_manager::peers, webrtc_peer_manager::peers_mutex, webrtc_peer_manager::pending_ice, webrtc_peer_manager::pending_ice_count, webrtc_peer_manager_config_t::relay_only, webrtc_peer_manager::role, webrtc_peer_manager_config_t::role, SAFE_FREE, SAFE_MALLOC, webrtc_signaling_callbacks_t::send_ice, webrtc_signaling_callbacks_t::send_sdp, SET_ERRNO, webrtc_peer_manager::signaling, webrtc_peer_manager::signaling_mutex, webrtc_peer_manager_config_t::turn_count, and WEBRTC_ROLE_CREATOR.

◆ webrtc_peer_manager_destroy()

void webrtc_peer_manager_destroy ( webrtc_peer_manager_t * manager)

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Destroy peer manager and close all connections.

Parameters
managerPeer manager to destroy

Closes all active peer connections gracefully and frees resources. Safe to call with NULL pointer.

Definition at line 565 of file peer_manager.c.

565 {
566 if (!manager) {
567 return;
568 }
569
570 mutex_lock(&manager->signaling_mutex);
571 mutex_lock(&manager->peers_mutex);
572
573 // Close all peer connections
574 peer_entry_t *peer = NULL, *tmp = NULL;
575 HASH_ITER(hh, manager->peers, peer, tmp) {
576 remove_peer_locked(manager, peer);
577 }
578
579 mutex_unlock(&manager->peers_mutex);
580 pending_ice_candidate_t *pending = manager->pending_ice;
581 while (pending) {
582 pending_ice_candidate_t *next = pending->next;
583 free_pending_ice_candidate(pending);
584 pending = next;
585 }
586 mutex_unlock(&manager->signaling_mutex);
587 mutex_destroy(&manager->signaling_mutex);
588 mutex_destroy(&manager->peers_mutex);
589
590 SAFE_FREE(manager);
591
592 log_debug("Destroyed WebRTC peer manager");
593}
struct pending_ice_candidate pending_ice_candidate_t
Hash-table record for one negotiated WebRTC participant.
struct pending_ice_candidate * next

References log_debug, pending_ice_candidate::next, webrtc_peer_manager::peers, webrtc_peer_manager::peers_mutex, webrtc_peer_manager::pending_ice, SAFE_FREE, and webrtc_peer_manager::signaling_mutex.

Referenced by discovery_session_apply_handoff(), and discovery_session_destroy().

◆ webrtc_peer_manager_dispatch_ready()

asciichat_error_t webrtc_peer_manager_dispatch_ready ( webrtc_peer_manager_t * manager)

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Deliver ready transports on the thread that created the manager. Serialize this call with peer removal and manager destruction. NULL is a no-op. Foreign-thread calls leave pending transports untouched.

Definition at line 239 of file peer_manager.c.

239 {
240 if (!manager)
241 return ASCIICHAT_OK;
242 if (!thread_equal(manager->owner_thread, thread_self()))
243 return SET_ERRNO(ERROR_INVALID_STATE, "Ready transport dispatch requires the manager owner thread");
244 if (!manager->config.on_transport_ready)
245 return ASCIICHAT_OK;
246 for (;;) {
247 acip_transport_t *transport = NULL;
249 mutex_lock(&manager->peers_mutex);
250 peer_entry_t *peer, *tmp;
251 HASH_ITER(hh, manager->peers, peer, tmp) {
252 if (!atomic_load_bool(&peer->security_ready))
253 continue;
254 transport = atomic_ptr_exchange(&peer->pending_transport, NULL);
255 if (transport) {
256 memcpy(participant_id, peer->participant_id, sizeof(participant_id));
257 peer->is_connected = true;
258 break;
259 }
260 }
261 mutex_unlock(&manager->peers_mutex);
262 if (!transport)
263 return ASCIICHAT_OK;
264 manager->config.on_transport_ready(transport, participant_id, manager->config.user_data);
265 }
266}
void * atomic_ptr_exchange(atomic_ptr_t *a, void *new_value)
Atomically exchange a pointer and return the old value.
@ ERROR_INVALID_STATE
#define SESSION_ID_SIZE
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
bool is_connected
DataChannel opened.
atomic_ptr_t pending_transport
Owned until authenticated and handed to the application.
webrtc_transport_ready_callback_t on_transport_ready
Called when DataChannel ready.

References ASCIICHAT_OK, atomic_load_bool(), atomic_ptr_exchange(), webrtc_peer_manager::config, ERROR_INVALID_STATE, peer_entry_t::is_connected, webrtc_peer_manager_config_t::on_transport_ready, webrtc_peer_manager::owner_thread, participant_id, peer_entry_t::participant_id, webrtc_peer_manager::peers, webrtc_peer_manager::peers_mutex, peer_entry_t::pending_transport, peer_entry_t::security_ready, SESSION_ID_SIZE, SET_ERRNO, and webrtc_peer_manager_config_t::user_data.

Referenced by discovery_session_process().

◆ webrtc_peer_manager_get_state()

bool webrtc_peer_manager_get_state ( webrtc_peer_manager_t * manager,
const uint8_t participant_id[16],
webrtc_state_t * state_out )

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Return the current state for a participant's peer connection.

Definition at line 806 of file peer_manager.c.

806 {
807 if (!manager || !participant_id || !state_out) {
808 return false;
809 }
810
811 mutex_lock(&manager->peers_mutex);
812 peer_entry_t *peer = find_peer_locked(manager, participant_id);
813 bool found = peer && peer->pc;
814 if (found) {
815 *state_out = webrtc_get_state(peer->pc);
816 }
817 mutex_unlock(&manager->peers_mutex);
818 return found;
819}

References participant_id, peer_entry_t::pc, webrtc_peer_manager::peers_mutex, SESSION_ID_SIZE, and webrtc_get_state().

◆ webrtc_peer_manager_handle_ice()

asciichat_error_t webrtc_peer_manager_handle_ice ( webrtc_peer_manager_t * manager,
const acip_webrtc_ice_t * ice )

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Handle incoming ICE candidate from ACDS.

Parameters
managerPeer manager
iceICE candidate message received from ACDS
Returns
ASCIICHAT_OK on success, error code on failure

Adds remote ICE candidate to the appropriate peer connection. If peer connection doesn't exist yet, queues candidate for later.

Definition at line 715 of file peer_manager.c.

715 {
716 if (!manager || !ice) {
717 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
718 }
719
720 // Extract ICE candidate and mid (both are null-terminated in the packet)
721 const char *candidate = (const char *)(ice + 1); // After header
722 size_t candidate_str_len = strlen(candidate);
723 const char *mid = candidate + candidate_str_len + 1; // After candidate + null terminator
724
725 log_debug("Handling incoming ICE candidate from remote peer (mid=%s)", mid);
726 log_debug(" [3] After ACDS recv - candidate: '%s' (len=%zu)", candidate, strlen(candidate));
727 log_debug(" [3] After ACDS recv - mid: '%s' (len=%zu)", mid, strlen(mid));
728 log_debug(" [3] After ACDS recv - header.candidate_len=%u", NET_TO_HOST_U16(ice->candidate_len));
729
730 // Hex dump first 100 bytes of payload for debugging
731 const uint8_t *payload = (const uint8_t *)(ice + 1);
732 log_debug(" [3] Hex dump of payload (first 100 bytes):");
733 for (int i = 0; i < 100 && i < (int)candidate_str_len + 20; i += 16) {
736 for (int j = 0; j < 16 && (i + j) < 100; j++) {
737 snprintf(hex + j * 3, sizeof(hex) - j * 3, "%02x ", payload[i + j]);
738 ascii[j] = (payload[i + j] >= 32 && payload[i + j] < 127) ? payload[i + j] : '.';
739 }
740 log_debug(" [%04x] %-48s %s", i, hex, ascii);
741 }
742
743 // Do not pass a candidate to libdatachannel until a preceding SDP packet has
744 // finished installing the remote ICE transport.
745 mutex_lock(&manager->signaling_mutex);
746 mutex_lock(&manager->peers_mutex);
747
748 // Find peer connection
749 peer_entry_t *peer = find_peer_locked(manager, ice->sender_id);
750 if (!peer || !peer->remote_description_set) {
751 mutex_unlock(&manager->peers_mutex);
752 asciichat_error_t result = queue_pending_ice_candidate(manager, ice->sender_id, candidate, mid);
753 mutex_unlock(&manager->signaling_mutex);
754 if (result == ASCIICHAT_OK) {
755 log_debug("Queued ICE candidate received before remote SDP was installed");
756 }
757 return result;
758 }
759
760 mutex_unlock(&manager->peers_mutex);
761
762 // Add remote ICE candidate
763 asciichat_error_t result = webrtc_add_remote_candidate(peer->pc, candidate, mid);
764 if (result != ASCIICHAT_OK) {
765 mutex_unlock(&manager->signaling_mutex);
766 return SET_ERRNO(result, "Failed to add remote ICE candidate");
767 }
768
769 mutex_unlock(&manager->signaling_mutex);
770 return ASCIICHAT_OK;
771}
#define NET_TO_HOST_U16(val)
Definition endian.h:115
asciichat_error_t webrtc_add_remote_candidate(webrtc_peer_connection_t *pc, const char *candidate, const char *mid)
Add remote ICE candidate.
#define NETWORK_WEBRTC_PEER_MANAGER_HEX_BUFFER_SIZE
#define NETWORK_WEBRTC_PEER_MANAGER_ASCII_BUFFER_SIZE
bool remote_description_set
libdatachannel has installed the remote SDP and ICE transport

References acip_webrtc_ice_t, ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NOT_SUPPORTED, log_debug, NET_TO_HOST_U16, NETWORK_WEBRTC_PEER_MANAGER_ASCII_BUFFER_SIZE, NETWORK_WEBRTC_PEER_MANAGER_HEX_BUFFER_SIZE, peer_entry_t::pc, webrtc_peer_manager::peers_mutex, peer_entry_t::remote_description_set, SET_ERRNO, webrtc_peer_manager::signaling_mutex, and webrtc_add_remote_candidate().

◆ webrtc_peer_manager_handle_sdp()

asciichat_error_t webrtc_peer_manager_handle_sdp ( webrtc_peer_manager_t * manager,
const acip_webrtc_sdp_t * sdp )

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Handle incoming SDP message from ACDS.

Parameters
managerPeer manager
sdpSDP message received from ACDS
Returns
ASCIICHAT_OK on success, error code on failure

Processes SDP offer or answer from remote peer:

  • Creator role + offer: Create peer connection, set remote SDP, generate answer
  • Joiner role + answer: Set remote SDP on existing peer connection

Sends response SDP via signaling callbacks.

Definition at line 595 of file peer_manager.c.

595 {
596 if (!manager || !sdp) {
597 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
598 }
599
600 // Extract SDP string and type
601 const uint8_t *sdp_data = (const uint8_t *)(sdp + 1); // After header
602 const char *sdp_type = (sdp->sdp_type == 0) ? "offer" : "answer";
603 uint16_t sdp_len = NET_TO_HOST_U16(sdp->sdp_len);
604
605 // ACDS can deliver ICE immediately after SDP. Keep both operations ordered
606 // until libdatachannel has installed the remote description and ICE transport.
607 mutex_lock(&manager->signaling_mutex);
608
609 // Allocate null-terminated buffer for SDP string (libdatachannel requires C string)
610 char *sdp_str = SAFE_MALLOC(sdp_len + 1, char *);
611 if (!sdp_str) {
612 mutex_unlock(&manager->signaling_mutex);
613 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate remote SDP buffer");
614 }
615 memcpy(sdp_str, sdp_data, sdp_len);
616 sdp_str[sdp_len] = '\0'; // Null-terminate
617
619 bool has_incoming_ice_ufrag = extract_ice_ufrag(sdp_str, incoming_ice_ufrag, sizeof(incoming_ice_ufrag));
620
621 log_debug("Handling incoming SDP %s from remote peer (len=%u)", sdp_type, sdp_len);
622
623 mutex_lock(&manager->peers_mutex);
624
625 // Find or create peer connection
626 peer_entry_t *peer;
627
628 // Special case: If receiving an answer and we're a joiner, we may have created
629 // a peer with broadcast ID (00000000...) and need to update it to the real sender_id
630 if (sdp->sdp_type == 1 && manager->role == WEBRTC_ROLE_JOINER) {
631 static const uint8_t broadcast_id[SESSION_ID_SIZE] = {0};
632 peer = find_peer_locked(manager, broadcast_id);
633 if (peer) {
634 log_debug("Updating broadcast peer with real participant_id from answer");
635 // Remove from hash with old ID
636 HASH_DEL(manager->peers, peer);
637 // Update to real participant_id
638 memcpy(peer->participant_id, sdp->sender_id, SESSION_ID_SIZE);
639 // Re-add with new ID
640 HASH_ADD(hh, manager->peers, participant_id, 16, peer);
641 }
642 }
643
644 // libdatachannel cannot apply an ICE restart to an existing peer connection.
645 // Repeated signaling can also redeliver the same offer, which must not be
646 // mistaken for a new ICE generation or applied twice.
647 if (sdp->sdp_type == 0 && manager->role == WEBRTC_ROLE_CREATOR) {
648 peer_entry_t *existing = find_peer_locked(manager, sdp->sender_id);
649 if (existing && existing->remote_sdp_attempted && existing->pc) {
650 webrtc_state_t state = webrtc_get_state(existing->pc);
651 bool comparable_ice_generation = has_incoming_ice_ufrag && existing->remote_ice_ufrag[0] != '\0';
652 bool new_ice_generation = comparable_ice_generation && strcmp(incoming_ice_ufrag, existing->remote_ice_ufrag) != 0;
653 bool terminal_state = state == WEBRTC_STATE_FAILED || state == WEBRTC_STATE_CLOSED;
654 if (!terminal_state && comparable_ice_generation && !new_ice_generation && existing->remote_description_set) {
655 log_debug("Ignoring duplicate WebRTC offer for existing ICE generation");
656 mutex_unlock(&manager->peers_mutex);
657 SAFE_FREE(sdp_str);
658 mutex_unlock(&manager->signaling_mutex);
659 return ASCIICHAT_OK;
660 }
661 if (terminal_state || new_ice_generation) {
662 log_info("Replacing WebRTC peer for %s", new_ice_generation ? "new ICE generation" : "terminal connection state");
663 remove_peer_locked(manager, existing);
664 }
665 }
666 }
667
668 asciichat_error_t result = create_peer_connection_locked(manager, sdp->session_id, sdp->sender_id, &peer);
669 if (result != ASCIICHAT_OK) {
670 mutex_unlock(&manager->peers_mutex);
671 SAFE_FREE(sdp_str);
672 mutex_unlock(&manager->signaling_mutex);
673 return SET_ERRNO(result, "Failed to create peer connection for SDP");
674 }
675
676 if (sdp->sdp_type == 0 && manager->role == WEBRTC_ROLE_CREATOR) {
677 peer->remote_sdp_attempted = true;
678 }
679
680 mutex_unlock(&manager->peers_mutex);
681
682 // Set remote SDP
683 result = webrtc_set_remote_description(peer->pc, sdp_str, sdp_type);
684 SAFE_FREE(sdp_str); // Free after use
685
686 if (result != ASCIICHAT_OK) {
687 mutex_unlock(&manager->signaling_mutex);
688 return SET_ERRNO(result, "Failed to set remote SDP");
689 }
690
691 // A peer entry can be created before its offer arrives (for example when
692 // ACDS reports a participant join). Do not treat that entry as ready for
693 // trickle ICE until libdatachannel has accepted its remote description.
694 peer->remote_description_set = true;
695 if (sdp->sdp_type == 0 && has_incoming_ice_ufrag) {
696 memcpy(peer->remote_ice_ufrag, incoming_ice_ufrag, strlen(incoming_ice_ufrag) + 1);
697 }
698
699 result = apply_pending_ice_candidates(manager, peer);
700 if (result != ASCIICHAT_OK) {
701 mutex_unlock(&manager->signaling_mutex);
702 return SET_ERRNO(result, "Failed to apply ICE candidates queued before remote SDP");
703 }
704
705 // If this is an offer and we're the creator, generate answer automatically
706 // (libdatachannel triggers on_local_description callback with answer)
707 if (sdp->sdp_type == 0 && manager->role == WEBRTC_ROLE_CREATOR) {
708 log_debug("Offer received, answer will be generated automatically");
709 }
710
711 mutex_unlock(&manager->signaling_mutex);
712 return ASCIICHAT_OK;
713}
unsigned short uint16_t
asciichat_error_t webrtc_set_remote_description(webrtc_peer_connection_t *pc, const char *sdp, const char *type)
Set remote SDP offer/answer.
#define NETWORK_WEBRTC_PEER_MANAGER_INCOMING_ICE_UFRAG_BUFFER_SIZE
char remote_ice_ufrag[257]
installed on this peer
bool remote_sdp_attempted
A remote description was applied or attempted.

References acip_webrtc_sdp_t, ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_NOT_SUPPORTED, log_debug, log_info, NET_TO_HOST_U16, NETWORK_WEBRTC_PEER_MANAGER_INCOMING_ICE_UFRAG_BUFFER_SIZE, participant_id, peer_entry_t::participant_id, peer_entry_t::pc, webrtc_peer_manager::peers, webrtc_peer_manager::peers_mutex, peer_entry_t::remote_description_set, peer_entry_t::remote_ice_ufrag, peer_entry_t::remote_sdp_attempted, webrtc_peer_manager::role, SAFE_FREE, SAFE_MALLOC, SESSION_ID_SIZE, SET_ERRNO, webrtc_peer_manager::signaling_mutex, webrtc_get_state(), WEBRTC_ROLE_CREATOR, WEBRTC_ROLE_JOINER, webrtc_set_remote_description(), WEBRTC_STATE_CLOSED, and WEBRTC_STATE_FAILED.

◆ webrtc_peer_manager_remove_peer()

asciichat_error_t webrtc_peer_manager_remove_peer ( webrtc_peer_manager_t * manager,
const uint8_t participant_id[16] )

#include <include/ascii-chat/network/webrtc/peer_manager.h>

Definition at line 821 of file peer_manager.c.

821 {
822 if (!manager || !participant_id) {
823 return SET_ERRNO(ERROR_INVALID_PARAM, "Peer manager and participant ID are required");
824 }
825
826 // SDP and ICE handlers retain peer pointers after releasing peers_mutex.
827 // Serialize removal with those handlers before freeing the peer wrappers.
828 mutex_lock(&manager->signaling_mutex);
829 mutex_lock(&manager->peers_mutex);
830 peer_entry_t *peer = find_peer_locked(manager, participant_id);
831 if (peer) {
832 remove_peer_locked(manager, peer);
833 }
834 mutex_unlock(&manager->peers_mutex);
835 mutex_unlock(&manager->signaling_mutex);
836 return ASCIICHAT_OK;
837}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, participant_id, webrtc_peer_manager::peers_mutex, SESSION_ID_SIZE, SET_ERRNO, and webrtc_peer_manager::signaling_mutex.

◆ webrtc_set_remote_description()

asciichat_error_t webrtc_set_remote_description ( webrtc_peer_connection_t * pc,
const char * sdp,
const char * type )

#include <include/ascii-chat/network/webrtc/webrtc.h>

Set remote SDP offer/answer.

Parameters
pcPeer connection
sdpRemote SDP string (null-terminated)
typeSDP type ("offer" or "answer")
Returns
ASCIICHAT_OK on success, error code on failure

Sets the remote peer's SDP. If this is an offer, triggers automatic answer generation via the local description callback.

Definition at line 756 of file lib/network/webrtc/webrtc.c.

756 {
757 if (!pc || !sdp || !type) {
758 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
759 }
760
761 webrtc_release_port(pc);
762 int result = rtcSetRemoteDescription(pc->rtc_id, sdp, type);
763 if (result != RTC_ERR_SUCCESS) {
764 return SET_ERRNO(ERROR_NETWORK, "Failed to set remote SDP (rtc error %d)", result);
765 }
766
767 const char *dcmap = strstr(sdp, "a=dcmap:");
768 if (strcmp(type, "offer") == 0) {
769 log_debug("Remote WebRTC offer DataChannel map: %s", dcmap ? dcmap : "(none)");
770 }
771 if (strcmp(type, "offer") == 0 && strstr(sdp, "\na=dcmap:0 label=\"acip\"") && !pc->dc) {
772 rtcDataChannelInit init = {0};
773 init.negotiated = true;
774 init.manualStream = true;
775 init.stream = 0;
776 int dc_id = rtcCreateDataChannelEx(pc->rtc_id, "acip", &init);
777 if (dc_id < 0)
778 return SET_ERRNO(ERROR_NETWORK, "Failed to create negotiated ACIP channel");
779 on_datachannel_adapter(pc->rtc_id, dc_id, pc);
780 }
781
782 log_debug("Set remote SDP description (pc_id=%d, type=%s)", pc->rtc_id, type);
783 return ASCIICHAT_OK;
784}

References ASCIICHAT_OK, webrtc_peer_connection::dc, ERROR_INVALID_PARAM, ERROR_NETWORK, log_debug, webrtc_peer_connection::rtc_id, and SET_ERRNO.

Referenced by webrtc_peer_manager_handle_sdp().