ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
webrtc/transport.c
Go to the documentation of this file.
31
37#include <ascii-chat/log/log.h>
39#include <ascii-chat/buffer.h>
40#include <libplatform/mutex.h>
41#include <libplatform/cond.h>
46#include <string.h>
47
55#define WEBRTC_RECV_QUEUE_SIZE 512
56// Start coalescing well before the 512-message ring fills so a congested peer
57// stays close to live.
58#define WEBRTC_RECV_QUEUE_HIGH_WATER 12
59
60// DataChannel sends are asynchronous. Bound replaceable video so reliable,
61// ordered delivery cannot turn a slow peer into an ever-growing history of
62// obsolete frames.
63#define WEBRTC_SEND_VIDEO_HIGH_WATER (256 * 1024)
64
65// Allow ICE connectivity checks to recover temporarily, then let the owning
66// session tear down and renegotiate a peer that has remained disconnected.
67#define WEBRTC_DISCONNECTED_GRACE_NS (30 * NS_PER_SEC_INT)
68
72typedef struct {
74 size_t len;
76
103
104static void webrtc_abort(webrtc_transport_data_t *wrtc) {
105 mutex_lock(&wrtc->state_mutex);
106 wrtc->is_connected = false;
107 wrtc->data_channel_closed = true;
108 mutex_unlock(&wrtc->state_mutex);
109 cond_broadcast(&wrtc->queue_cond);
110 // Closing is safe in a callback; the owner deletes the channel after callbacks finish.
112}
113
114// =============================================================================
115// DataChannel Callbacks
116// =============================================================================
117
118static bool queued_message_is_media(const webrtc_recv_msg_t *msg) {
119 if (msg->len < sizeof(packet_header_t))
120 return false;
121 packet_header_t header;
122 memcpy(&header, msg->data, sizeof(header));
123 packet_type_t type = NET_TO_HOST_U16(header.type);
125}
126
127static bool queued_message_is_video(const webrtc_recv_msg_t *msg) {
128 if (msg->len < sizeof(packet_header_t))
129 return false;
130 packet_header_t header;
131 memcpy(&header, msg->data, sizeof(header));
132 packet_type_t type = NET_TO_HOST_U16(header.type);
133 return type == PACKET_TYPE_IMAGE_FRAME || type == PACKET_TYPE_ASCII_FRAME;
134}
135
136static bool queued_message_is_audio(const webrtc_recv_msg_t *msg) {
137 if (msg->len < sizeof(packet_header_t))
138 return false;
139 packet_header_t header;
140 memcpy(&header, msg->data, sizeof(header));
141 packet_type_t type = NET_TO_HOST_U16(header.type);
143}
144
145static void discard_stale_media(webrtc_transport_data_t *wrtc) {
147 size_t count = 0, video_count = 0, audio_count = 0;
148 while (count < WEBRTC_RECV_QUEUE_SIZE && ringbuffer_read(wrtc->recv_queue, &queued[count])) {
149 if (queued_message_is_video(&queued[count]))
150 video_count++;
151 else if (queued_message_is_audio(&queued[count]))
152 audio_count++;
153 count++;
154 }
155 // Video frames are snapshots, so retain the newest one. Preserve a short
156 // recent audio history, but discard stale audio when it would otherwise fill
157 // the queue and prevent new video packets from reaching the receive worker.
158 // Derive the audio allowance from the existing queue high-water mark after
159 // reserving room for control messages and the newest video frame.
160 size_t control_count = count - video_count - audio_count;
161 size_t retained_video_count = video_count > 0 ? 1 : 0;
162 size_t non_audio_count = control_count + retained_video_count;
163 size_t keep_audio_count = non_audio_count < WEBRTC_RECV_QUEUE_HIGH_WATER ? WEBRTC_RECV_QUEUE_HIGH_WATER - non_audio_count : 0;
164 size_t video_to_discard = video_count - retained_video_count;
165 size_t audio_to_discard = audio_count > keep_audio_count ? audio_count - keep_audio_count : 0;
166 size_t dropped_video = 0;
167 size_t dropped_audio = 0;
168 for (size_t i = 0; i < count; i++) {
169 if (video_to_discard && queued_message_is_video(&queued[i])) {
170 buffer_release(queued[i].data);
171 video_to_discard--;
172 dropped_video++;
173 } else if (audio_to_discard && queued_message_is_audio(&queued[i])) {
174 buffer_release(queued[i].data);
175 audio_to_discard--;
176 dropped_audio++;
177 } else {
178 ringbuffer_write(wrtc->recv_queue, &queued[i]);
179 }
180 }
181 if (dropped_video || dropped_audio) {
182 log_warn_every(US_PER_SEC_INT, "WebRTC receive backlog: dropped %zu stale video packets and %zu oldest audio packets", dropped_video, dropped_audio);
183 }
184}
185
192static void webrtc_on_message(webrtc_data_channel_t *channel, const uint8_t *data, size_t len, void *user_data) {
193 (void)channel; // Unused
195
196 if (!wrtc || !data || len == 0) {
197 return;
198 }
199
200 // Ordered DataChannels may split a large ACIP packet across messages.
201 const size_t limit = 8 * 1024 * 1024;
202 mutex_lock(&wrtc->queue_mutex);
203 if (len > limit || wrtc->partial_len > limit - len) {
204 mutex_unlock(&wrtc->queue_mutex);
205 log_error("WebRTC receive buffer exceeded");
206 webrtc_abort(wrtc);
207 return;
208 }
209 if (!wrtc->partial_len)
210 wrtc->partial_since_ns = time_get_ns();
211 size_t required = wrtc->partial_len + len;
212 if (required > wrtc->partial_capacity) {
213 size_t capacity = wrtc->partial_capacity ? wrtc->partial_capacity : 16384;
214 while (capacity < required) {
215 capacity *= 2;
216 }
217 if (capacity > limit) {
218 capacity = limit;
219 }
220 uint8_t *next = buffer_alloc(NULL, capacity);
221 if (!next) {
222 mutex_unlock(&wrtc->queue_mutex);
223 webrtc_abort(wrtc);
224 return;
225 }
226 if (wrtc->partial_len)
227 memcpy(next, wrtc->partial, wrtc->partial_len);
228 buffer_release(wrtc->partial);
229 wrtc->partial = next;
230 wrtc->partial_capacity = capacity;
231 }
232 memcpy(wrtc->partial + wrtc->partial_len, data, len);
233 wrtc->partial_len += len;
234 size_t offset = 0;
235 bool notify_ready = false;
236 while (wrtc->partial_len - offset >= sizeof(packet_header_t)) {
237 packet_header_t header;
238 memcpy(&header, wrtc->partial + offset, sizeof(header));
239 size_t payload_len = NET_TO_HOST_U32(header.length);
240 if (NET_TO_HOST_U64(header.magic) != PACKET_MAGIC || payload_len > limit - sizeof(header)) {
241 mutex_unlock(&wrtc->queue_mutex);
242 log_error("Invalid ACIP packet on WebRTC DataChannel");
243 webrtc_abort(wrtc);
244 return;
245 }
246 size_t packet_len = sizeof(header) + payload_len;
247 if (wrtc->partial_len - offset < packet_len)
248 break;
249 webrtc_recv_msg_t msg = {.data = buffer_alloc(NULL, packet_len), .len = packet_len};
250 if (!msg.data)
251 break;
252 memcpy(msg.data, wrtc->partial + offset, packet_len);
253 if (packet_validate(msg.data, packet_len, 0, NULL) != ASCIICHAT_OK) {
254 buffer_release(msg.data);
255 mutex_unlock(&wrtc->queue_mutex);
256 log_error("WebRTC packet checksum failed");
257 webrtc_abort(wrtc);
258 return;
259 }
260 if (wrtc->security && !wrtc->security->ready) {
261 asciichat_error_t result = acip_security_receive(wrtc->security, wrtc->transport, NET_TO_HOST_U16(header.type), msg.data + sizeof(header), payload_len);
262 buffer_release(msg.data);
263 if (result != ASCIICHAT_OK) {
264 mutex_unlock(&wrtc->queue_mutex);
266 log_error("WebRTC peer handshake failed: %s", HAS_ERRNO(&error) ? error.context_message : asciichat_error_format(NULL, result));
267 webrtc_abort(wrtc);
268 return;
269 }
270 if (wrtc->security->ready && wrtc->on_ready) {
271 notify_ready = true;
272 }
273 offset += packet_len;
274 continue;
275 }
276 packet_envelope_t envelope = {.type = NET_TO_HOST_U16(header.type), .data = msg.data + sizeof(header), .len = payload_len, .allocated_buffer = msg.data, .allocated_size = msg.len};
277 crypto_context_t *crypto = wrtc->transport->crypto_ctx;
279 if (envelope.type == PACKET_TYPE_ENCRYPTED) {
280 if (!crypto || !crypto->encrypt_data || !crypto_is_ready(crypto))
281 result = SET_ERRNO(ERROR_CRYPTO, "Unexpected encrypted WebRTC packet");
282 else
283 result = packet_decrypt_envelope(&envelope, crypto);
284 } else if (crypto && crypto->encrypt_data && crypto_is_ready(crypto) && !packet_is_initial_handshake_type(envelope.type)) {
285 result = SET_ERRNO(ERROR_CRYPTO, "Plaintext application packet on encrypted WebRTC connection");
286 }
287 if (result != ASCIICHAT_OK) {
288 buffer_release(envelope.allocated_buffer);
289 mutex_unlock(&wrtc->queue_mutex);
290 log_error("WebRTC packet rejected: %s", asciichat_error_format(NULL, result));
291 webrtc_abort(wrtc);
292 return;
293 }
294 if (envelope.consumed) {
295 buffer_release(envelope.allocated_buffer);
296 offset += packet_len;
297 continue;
298 }
299 msg.data = envelope.allocated_buffer;
300 msg.len = sizeof(packet_header_t) + envelope.len;
301 if (ringbuffer_is_full(wrtc->recv_queue)) {
302 discard_stale_media(wrtc);
303 }
304 if (!ringbuffer_write(wrtc->recv_queue, &msg)) {
305 bool media = queued_message_is_media(&msg);
306 if (media) {
307 log_warn_every(US_PER_SEC_INT, "WebRTC receive queue saturated; dropping newest media packet");
308 }
309 buffer_release(msg.data);
310 if (media) {
311 offset += packet_len;
312 continue;
313 }
314 mutex_unlock(&wrtc->queue_mutex);
315 log_error("WebRTC receive queue exceeded");
316 webrtc_abort(wrtc);
317 return;
318 }
319 // Keep video presentation current and prevent stale audio from filling the
320 // bounded queue ahead of newer media and control packets.
322 discard_stale_media(wrtc);
323 }
324 offset += packet_len;
325 }
326 wrtc->partial_len -= offset;
327 if (offset)
328 wrtc->partial_since_ns = wrtc->partial_len ? time_get_ns() : 0;
329 if (offset && wrtc->partial_len)
330 memmove(wrtc->partial, wrtc->partial + offset, wrtc->partial_len);
331 cond_signal(&wrtc->queue_cond);
332 mutex_unlock(&wrtc->queue_mutex);
333 // Application callbacks may immediately receive from the transport.
334 if (notify_ready)
335 wrtc->on_ready(wrtc->transport, wrtc->ready_user_data);
336}
337
341static void webrtc_on_open(webrtc_data_channel_t *channel, void *user_data) {
342 (void)channel;
344
345 if (!wrtc) {
346 return;
347 }
348
349 mutex_lock(&wrtc->state_mutex);
350 wrtc->is_connected = true;
351 wrtc->data_channel_closed = false;
352 wrtc->disconnected_since_ns = 0;
353 mutex_unlock(&wrtc->state_mutex);
354
355 log_info("WebRTC DataChannel opened, transport ready");
356}
357
361static void webrtc_on_error(webrtc_data_channel_t *channel, const char *error_msg, void *user_data) {
362 (void)channel;
364
365 log_error("WebRTC DataChannel error: %s", error_msg ? error_msg : "unknown error");
366
367 if (!wrtc) {
368 return;
369 }
370
371 // A DataChannel error can be reported while ICE is recovering. The peer
372 // connection state determines whether the transport is terminal.
373 cond_broadcast(&wrtc->queue_cond);
374}
375
379static void webrtc_on_close(webrtc_data_channel_t *channel, void *user_data) {
380 (void)channel;
382
383 log_info("WebRTC DataChannel closed");
384
385 if (!wrtc) {
386 return;
387 }
388
389 mutex_lock(&wrtc->state_mutex);
390 wrtc->is_connected = false;
391 wrtc->data_channel_closed = true;
392 mutex_unlock(&wrtc->state_mutex);
393
394 // Wake any blocking recv() calls
395 cond_broadcast(&wrtc->queue_cond);
396}
397
398// =============================================================================
399// WebRTC Transport Methods
400// =============================================================================
401
402static bool webrtc_transport_is_connected_impl(webrtc_transport_data_t *wrtc) {
403 if (!wrtc) {
404 return false;
405 }
406
407 if (!wrtc->peer_conn || !wrtc->data_channel) {
408 return false;
409 }
410
411 mutex_lock(&wrtc->state_mutex);
412 bool close_requested = wrtc->close_requested;
413 bool data_channel_closed = wrtc->data_channel_closed;
414 bool connected = wrtc->is_connected;
415 mutex_unlock(&wrtc->state_mutex);
417 if (close_requested || data_channel_closed) {
418 return false;
419 }
420
421 // The DataChannel open callback can precede the peer connection's CONNECTED
422 // callback. An open channel is already usable during that event ordering.
423 if (state == WEBRTC_STATE_CONNECTED || state == WEBRTC_STATE_CONNECTING) {
424 if (!connected || !webrtc_datachannel_is_open(wrtc->data_channel)) {
425 return false;
426 }
427 mutex_lock(&wrtc->state_mutex);
428 wrtc->disconnected_since_ns = 0;
429 mutex_unlock(&wrtc->state_mutex);
430 return true;
431 }
432
433 if (state != WEBRTC_STATE_DISCONNECTED) {
434 return false;
435 }
436
437 // ICE can briefly enter DISCONNECTED while connectivity checks recover.
438 // Retain the DataChannel for a bounded window so a temporary network change
439 // does not restart the whole session; a stuck peer must still be cleaned up.
440 uint64_t now_ns = time_get_ns();
441 mutex_lock(&wrtc->state_mutex);
442 if (wrtc->disconnected_since_ns == 0) {
443 wrtc->disconnected_since_ns = now_ns;
444 }
445 bool within_grace = now_ns - wrtc->disconnected_since_ns <= WEBRTC_DISCONNECTED_GRACE_NS;
446 mutex_unlock(&wrtc->state_mutex);
447 return within_grace;
448}
449
450static asciichat_error_t webrtc_send(acip_transport_t *transport, const void *data, size_t len) {
452
453 if (!webrtc_transport_is_connected_impl(wrtc)) {
454 return SET_ERRNO(ERROR_NETWORK, "WebRTC transport not connected");
455 }
456
457 if (wrtc->security && !wrtc->security->ready) {
458 packet_header_t header;
459 if (len < sizeof(header))
460 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Incomplete WebRTC header");
461 memcpy(&header, data, sizeof(header));
462 if (NET_TO_HOST_U16(header.type) != PACKET_TYPE_PROTOCOL_VERSION && !packet_is_handshake_type(NET_TO_HOST_U16(header.type)))
463 return SET_ERRNO(ERROR_INVALID_STATE, "WebRTC peer security is not ready");
464 }
465 mutex_lock(&wrtc->send_mutex);
466 uint64_t send_start_ns = time_get_ns();
467 size_t buffered_before_send = 0;
468 asciichat_error_t buffered_result = webrtc_datachannel_get_buffered_amount(wrtc->data_channel, &buffered_before_send);
469 if (buffered_result != ASCIICHAT_OK) {
470 mutex_unlock(&wrtc->send_mutex);
471 return buffered_result;
472 }
473
474 size_t max_message_size = 16384;
476 asciichat_error_t max_size_result = webrtc_datachannel_get_max_message_size(wrtc->data_channel, &max_message_size);
477 if (max_size_result != ASCIICHAT_OK || max_message_size == 0) {
478 max_message_size = 16384;
479 } else {
480 ASSERT_NO_ERRNO_SINCE(size_scope);
481 }
483 log_debug_every(60 * US_PER_SEC_INT, "WebRTC DataChannel negotiated max message size: %zu bytes", max_message_size);
484
485 socket_buffer_t input = {.data = data, .len = len};
487 crypto_context_t *send_crypto = wrtc->security && !wrtc->security->ready ? NULL : transport->crypto_ctx;
488 asciichat_error_t result = acip_packet_plan(send_crypto, &input, 1, &plan);
489 uint8_t *encrypted = NULL;
490 if (result == ASCIICHAT_OK && plan.encrypt) {
491 encrypted = buffer_alloc(plan.domain, sizeof(packet_header_t) + plan.ciphertext_capacity);
492 if (!encrypted) {
493 result = SET_ERRNO(ERROR_MEMORY, "Cannot allocate WebRTC encrypted packet");
494 } else {
495 packet_header_t header;
496 size_t ciphertext_length = 0;
497 result = acip_packet_encrypt(transport->crypto_ctx, &plan, plan.domain, encrypted + sizeof(header), plan.ciphertext_capacity, &header, &ciphertext_length);
498 if (result == ASCIICHAT_OK) {
499 memcpy(encrypted, &header, sizeof(header));
500 data = encrypted;
501 len = sizeof(header) + ciphertext_length;
502 }
503 }
504 }
505 if (result != ASCIICHAT_OK) {
506 buffer_release(encrypted);
507 mutex_unlock(&wrtc->send_mutex);
508 return result;
509 }
510 for (size_t offset = 0; offset < len;) {
511 size_t chunk = len - offset;
512 if (chunk > max_message_size)
513 chunk = max_message_size;
514 result = webrtc_datachannel_send(wrtc->data_channel, (const uint8_t *)data + offset, chunk);
515 if (result != ASCIICHAT_OK)
516 break;
517 offset += chunk;
518 }
519 buffer_release(encrypted);
520 mutex_unlock(&wrtc->send_mutex);
521
522 uint64_t send_duration_ns = time_elapsed_ns(send_start_ns, time_get_ns());
523 if (send_duration_ns > 20 * NS_PER_MS_INT) {
524 log_warn_every(US_PER_SEC_INT, "WebRTC DataChannel send blocked %.1fms for %zu-byte packet (buffered=%zu)", (double)send_duration_ns / 1e6, len, buffered_before_send);
525 }
526
527 if (result != ASCIICHAT_OK) {
528 // A partial packet or consumed nonce cannot be retried on this stream.
529 mutex_lock(&wrtc->state_mutex);
530 wrtc->is_connected = false;
531 wrtc->data_channel_closed = true;
532 mutex_unlock(&wrtc->state_mutex);
533 return SET_ERRNO(ERROR_NETWORK, "Failed to send on WebRTC DataChannel");
534 }
535
536 return ASCIICHAT_OK;
537}
538
539static asciichat_error_t webrtc_recv(acip_transport_t *transport, void **buffer, size_t *out_len, void **out_allocated_buffer) {
541 uint64_t started = time_get_ns();
542 uint64_t timeout = transport->receive_timeout_ns ? transport->receive_timeout_ns : NS_PER_SEC_INT;
543
544 mutex_lock(&wrtc->queue_mutex);
545
546 // Block until message arrives or connection closes
547 while (ringbuffer_is_empty(wrtc->recv_queue)) {
548 uint64_t elapsed = time_get_ns() - started;
549 if (elapsed >= timeout) {
550 bool partial = wrtc->partial_len != 0;
551 mutex_unlock(&wrtc->queue_mutex);
552 return SET_ERRNO(partial ? ERROR_NETWORK_INCOMPLETE : ERROR_NETWORK_TIMEOUT, "WebRTC receive deadline expired");
553 }
554 if (!webrtc_transport_is_connected_impl(wrtc)) {
555 mutex_unlock(&wrtc->queue_mutex);
556 return SET_ERRNO(ERROR_NETWORK, "Connection closed while waiting for data");
557 }
558
559 // Wait for message arrival or connection close
560 // Peer-connection state changes do not necessarily produce a DataChannel
561 // callback. Periodically recheck the peer state so a lost connection can
562 // leave this blocking receive path and let its owner clean up.
563 cond_timedwait(&wrtc->queue_cond, &wrtc->queue_mutex, MIN(timeout - elapsed, 250 * NS_PER_MS_INT));
564 if (ringbuffer_is_empty(wrtc->recv_queue) && wrtc->partial_len) {
565 bool expired = time_elapsed_ns(wrtc->partial_since_ns, time_get_ns()) >= 5 * NS_PER_SEC_INT;
566 mutex_unlock(&wrtc->queue_mutex);
567 if (expired) {
568 mutex_lock(&wrtc->state_mutex);
569 wrtc->is_connected = false;
570 wrtc->data_channel_closed = true;
571 mutex_unlock(&wrtc->state_mutex);
572 return SET_ERRNO(ERROR_NETWORK, "Incomplete WebRTC packet exceeded receive deadline");
573 }
574 return SET_ERRNO(ERROR_NETWORK_INCOMPLETE, "Waiting for remaining WebRTC packet bytes");
575 }
576 }
577
578 // Read message from queue
580 bool success = ringbuffer_read(wrtc->recv_queue, &msg);
581 mutex_unlock(&wrtc->queue_mutex);
582
583 if (!success) {
584 return SET_ERRNO(ERROR_NETWORK, "Failed to read from receive queue");
585 }
586
587 // Return message to caller (caller owns the buffer)
588 *buffer = msg.data;
589 *out_len = msg.len;
590 *out_allocated_buffer = msg.data;
591
592 return ASCIICHAT_OK;
593}
594
595static asciichat_error_t webrtc_close(acip_transport_t *transport) {
597
598 mutex_lock(&wrtc->state_mutex);
599 if (wrtc->close_requested) {
600 mutex_unlock(&wrtc->state_mutex);
601 return ASCIICHAT_OK; // Already closed
602 }
603
604 wrtc->close_requested = true;
605 wrtc->is_connected = false;
606 mutex_unlock(&wrtc->state_mutex);
607
608 // Close the peer connection before deleting its DataChannel. libdatachannel
609 // tears down channel state as part of rtcClose(); deleting the channel first
610 // leaves rtcClose() trying to access an ID that no longer exists.
611 if (wrtc->peer_conn) {
613 }
614
615 // Delete the channel after the peer has stopped using it. Its owner will
616 // later destroy the wrapper; we only invalidate the native channel here so
617 // queued callbacks cannot retain this transport as user_data.
618 if (wrtc->data_channel) {
619 webrtc_datachannel_close(wrtc->data_channel);
620 }
621
622 // Wake any blocking recv() calls
623 cond_broadcast(&wrtc->queue_cond);
624
625 log_debug("WebRTC transport closed");
626 return ASCIICHAT_OK;
627}
628
629static acip_transport_type_t webrtc_get_type(acip_transport_t *transport) {
630 (void)transport;
632}
633
634static socket_t webrtc_get_socket(acip_transport_t *transport) {
635 (void)transport;
636 return INVALID_SOCKET_VALUE; // WebRTC has no underlying socket
637}
638
639static bool webrtc_is_connected(acip_transport_t *transport) {
641 return webrtc_transport_is_connected_impl(wrtc);
642}
643
644// =============================================================================
645// WebRTC Transport Destroy Implementation
646// =============================================================================
647
657static void webrtc_destroy_impl(acip_transport_t *transport) {
658 if (!transport || !transport->impl_data) {
659 return;
660 }
661
663
664 // acip_transport_destroy() only invokes close() for transports that still
665 // report connected. A WebRTC peer can enter DISCONNECTED before destruction,
666 // leaving this transport's callbacks registered on the DataChannel. Deleting
667 // the channel here is the libdatachannel synchronization point: it waits for
668 // scheduled callbacks and prevents new ones before this callback userdata,
669 // queue, and mutexes are released.
670 (void)webrtc_close(transport);
671
672 // Clear receive queue and free buffered messages
673 if (wrtc->recv_queue) {
674 mutex_lock(&wrtc->queue_mutex);
675
677 while (ringbuffer_read(wrtc->recv_queue, &msg)) {
678 if (msg.data) {
679 buffer_release(msg.data);
680 msg.data = NULL;
681 }
682 }
683
684 mutex_unlock(&wrtc->queue_mutex);
686 wrtc->recv_queue = NULL;
687 }
688
689 buffer_release(wrtc->partial);
690 wrtc->partial = NULL;
691 wrtc->partial_len = 0;
692 wrtc->partial_capacity = 0;
693
694 if (wrtc->security) {
696 SAFE_FREE(wrtc->security);
697 }
698
699 // Destroy synchronization primitives
700 mutex_destroy(&wrtc->state_mutex);
701 mutex_destroy(&wrtc->send_mutex);
702 cond_destroy(&wrtc->queue_cond);
703 mutex_destroy(&wrtc->queue_mutex);
704
705 log_debug("Destroyed WebRTC transport resources");
706}
707
708// =============================================================================
709// WebRTC Transport Method Table
710// =============================================================================
711
712static bool webrtc_has_pending_data(acip_transport_t *transport) {
713 if (!transport || !transport->impl_data)
714 return false;
716 mutex_lock(&wrtc->queue_mutex);
717 bool pending = !ringbuffer_is_empty(wrtc->recv_queue);
718 mutex_unlock(&wrtc->queue_mutex);
719 return pending;
720}
721
722static void webrtc_interrupt(acip_transport_t *transport) {
723 webrtc_transport_data_t *wrtc = transport->impl_data;
724 /* Publish terminal state before waking readers. The owner retains peer handles
725 * and callback contexts until all media workers have joined. */
726 mutex_lock(&wrtc->queue_mutex);
727 mutex_lock(&wrtc->state_mutex);
728 wrtc->is_connected = false;
729 wrtc->data_channel_closed = true;
730 mutex_unlock(&wrtc->state_mutex);
731 cond_broadcast(&wrtc->queue_cond);
732 mutex_unlock(&wrtc->queue_mutex);
733}
734
735static size_t webrtc_queued_bytes(acip_transport_t *transport) {
736 webrtc_transport_data_t *wrtc = transport->impl_data;
737 size_t bytes = 0;
741 // Let the sender report a closed channel and fail the outbound queue.
742 return result == ASCIICHAT_OK ? bytes : 0;
743}
744
745static const acip_transport_methods_t webrtc_methods = {
746 .send = webrtc_send,
747 .queued_bytes = webrtc_queued_bytes,
748 .reserved_bytes = ACIP_OUTBOUND_SCTP_RESERVE,
749 .recv = webrtc_recv,
750 .close = webrtc_close,
751 .interrupt = webrtc_interrupt,
752 .get_type = webrtc_get_type,
753 .get_socket = webrtc_get_socket,
754 .is_connected = webrtc_is_connected,
755 .has_pending_data = webrtc_has_pending_data,
756 .destroy_impl = webrtc_destroy_impl,
757};
758
760 if (!transport || transport->methods != &webrtc_methods || !transport->impl_data)
761 return NULL;
762 return ((webrtc_transport_data_t *)transport->impl_data)->security;
763}
764
765// =============================================================================
766// WebRTC Transport Creation
767// =============================================================================
768
769static acip_transport_t *webrtc_transport_create(webrtc_peer_connection_t *peer_conn, webrtc_data_channel_t *data_channel, crypto_context_t *crypto_ctx, acip_security_t *security,
770 void (*on_ready)(acip_transport_t *, void *), void *user_data) {
771 if (!peer_conn || !data_channel) {
772 SET_ERRNO(ERROR_INVALID_PARAM, "peer_conn and data_channel are required");
773 return NULL;
774 }
775
776 // Allocate transport structure
778 if (!transport) {
779 SET_ERRNO(ERROR_MEMORY, "Failed to allocate WebRTC transport");
780 return NULL;
781 }
782
783 // Allocate WebRTC-specific data
785 if (!wrtc_data) {
786 SAFE_FREE(transport);
787 SET_ERRNO(ERROR_MEMORY, "Failed to allocate WebRTC transport data");
788 return NULL;
789 }
790
791 // Create receive queue
793 if (!wrtc_data->recv_queue) {
794 SAFE_FREE(wrtc_data);
795 SAFE_FREE(transport);
796 SET_ERRNO(ERROR_MEMORY, "Failed to create receive queue");
797 return NULL;
798 }
799
800 // Initialize synchronization primitives
801 if (mutex_init(&wrtc_data->queue_mutex, "webrtc_queue") != 0) {
802 ringbuffer_destroy(wrtc_data->recv_queue);
803 SAFE_FREE(wrtc_data);
804 SAFE_FREE(transport);
805 SET_ERRNO(ERROR_INTERNAL, "Failed to initialize queue mutex");
806 return NULL;
807 }
808
809 if (cond_init(&wrtc_data->queue_cond, "queue") != 0) {
810 mutex_destroy(&wrtc_data->queue_mutex);
811 ringbuffer_destroy(wrtc_data->recv_queue);
812 SAFE_FREE(wrtc_data);
813 SAFE_FREE(transport);
814 SET_ERRNO(ERROR_INTERNAL, "Failed to initialize queue condition variable");
815 return NULL;
816 }
817
818 if (mutex_init(&wrtc_data->state_mutex, "webrtc_state") != 0) {
819 cond_destroy(&wrtc_data->queue_cond);
820 mutex_destroy(&wrtc_data->queue_mutex);
821 ringbuffer_destroy(wrtc_data->recv_queue);
822 SAFE_FREE(wrtc_data);
823 SAFE_FREE(transport);
824 SET_ERRNO(ERROR_INTERNAL, "Failed to initialize state mutex");
825 return NULL;
826 }
827
828 if (mutex_init(&wrtc_data->send_mutex, "webrtc_send") != 0) {
829 mutex_destroy(&wrtc_data->state_mutex);
830 cond_destroy(&wrtc_data->queue_cond);
831 mutex_destroy(&wrtc_data->queue_mutex);
832 ringbuffer_destroy(wrtc_data->recv_queue);
833 SAFE_FREE(wrtc_data);
834 SAFE_FREE(transport);
835 SET_ERRNO(ERROR_INTERNAL, "Failed to initialize send mutex");
836 return NULL;
837 }
838
839 // Initialize WebRTC data
840 wrtc_data->peer_conn = peer_conn;
841 wrtc_data->data_channel = data_channel;
842 // Installing the receive callback may synchronously drain queued messages.
843 // The channel is already open: initialize send readiness before that can
844 // advance the handshake and send its protocol response.
845 wrtc_data->is_connected = true;
846 webrtc_datachannel_set_open_state(data_channel, true);
847
848 transport->methods = &webrtc_methods;
849 transport->crypto_ctx = crypto_ctx;
850 transport->impl_data = wrtc_data;
851 wrtc_data->transport = transport;
852 wrtc_data->security = security;
853 wrtc_data->on_ready = on_ready;
854 wrtc_data->ready_user_data = user_data;
855
856 // Register DataChannel callbacks
858 .on_open = webrtc_on_open,
859 .on_close = webrtc_on_close,
860 .on_error = webrtc_on_error,
861 .on_message = webrtc_on_message,
862 .user_data = wrtc_data,
863 };
864
865 asciichat_error_t result = webrtc_datachannel_set_callbacks(data_channel, &callbacks);
866 if (result != ASCIICHAT_OK) {
867 mutex_destroy(&wrtc_data->send_mutex);
868 mutex_destroy(&wrtc_data->state_mutex);
869 cond_destroy(&wrtc_data->queue_cond);
870 mutex_destroy(&wrtc_data->queue_mutex);
871 ringbuffer_destroy(wrtc_data->recv_queue);
872 SAFE_FREE(wrtc_data);
873 SAFE_FREE(transport);
874 SET_ERRNO(ERROR_INTERNAL, "Failed to set DataChannel callbacks");
875 return NULL;
876 }
877
878 // Initialize transport
879 transport->methods = &webrtc_methods;
880 transport->stats_peer = stats_runtime_peer_open("WebRTC");
881 transport->crypto_ctx = crypto_ctx;
882 transport->impl_data = wrtc_data;
883
884 log_info("Created WebRTC transport (crypto: %s)", crypto_ctx ? "enabled" : "disabled");
885
886 // Register WebRTC transport implementation data with transport as parent
887 NAMED_REGISTER(wrtc_data, "impl", "webrtc_impl", "0x%tx", (uintptr_t)(const void *)(transport));
888
889 if (acip_outbound_create(transport) != ASCIICHAT_OK) {
890 acip_transport_destroy(transport);
891 return NULL;
892 }
893 return transport;
894}
895
897 return webrtc_transport_create(peer_conn, data_channel, crypto_ctx, NULL, NULL, NULL);
898}
899
901 void *user_data) {
902 if (!security) {
903 SET_ERRNO(ERROR_INVALID_PARAM, "Missing WebRTC security state");
904 return NULL;
905 }
906 return webrtc_transport_create(peer_conn, data_channel, &security->handshake.crypto_ctx, security, on_ready, user_data);
907}
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_errno_scope_t errno_scope_begin(void)
const char * asciichat_error_format(const char *message, asciichat_error_t code)
#define SET_ERRNO(code,...)
#define HAS_ERRNO(context)
#define ASSERT_NO_ERRNO_SINCE(scope)
@ ASCIICHAT_ERRNO_DISMISSED
asciichat_error_t acip_outbound_create(acip_transport_t *transport)
#define ACIP_OUTBOUND_SCTP_RESERVE
void acip_transport_destroy(acip_transport_t *transport)
Destroy transport and free all resources.
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:272
#define buffer_release(data)
Definition buffer.h:99
Hardware-Accelerated CRC32 Checksum Computation.
Named object registry for debugging — log identifiable resource names.
🔄 Network byte order conversion helpers
#define NET_TO_HOST_U64(val)
Definition endian.h:232
#define NET_TO_HOST_U16(val)
Definition endian.h:115
#define NET_TO_HOST_U32(val)
Definition endian.h:85
#define SAFE_FREE(ptr)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
unsigned char uint8_t
bool crypto_is_ready(const crypto_context_t *ctx)
Check if key exchange is complete and ready for encryption.
#define NAMED_REGISTER(ptr, name, type, fmt, parent_ptr)
Register any pointer with base name, type, format spec, and location (auto-suffix).
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_NETWORK_INCOMPLETE
Definition error_codes.h:94
@ ERROR_NETWORK
Definition error_codes.h:76
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:80
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
@ ERROR_INTERNAL
Definition error_codes.h:91
@ ERROR_NETWORK_TIMEOUT
Definition error_codes.h:79
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:117
#define US_PER_SEC_INT
Definition time.h:177
asciichat_error_t packet_validate(const void *packet, size_t length, size_t limit, packet_header_t *output)
Definition packet.c:81
asciichat_error_t packet_decrypt_envelope(packet_envelope_t *envelope, void *crypto_ctx)
Send a clear console packet.
Definition packet.c:639
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
#define PACKET_MAGIC
Packet magic number (alias for MAGIC_PACKET_VALID).
Definition packet.h:284
@ PACKET_TYPE_AUDIO_OPUS_BATCH
Batched Opus-encoded audio frames.
Definition packet.h:412
@ PACKET_TYPE_IMAGE_FRAME
Complete RGB image with dimensions.
Definition packet.h:399
@ PACKET_TYPE_ENCRYPTED
Encrypted packet (after handshake completion).
Definition packet.h:369
@ PACKET_TYPE_PROTOCOL_VERSION
Protocol version and capabilities negotiation.
Definition packet.h:317
@ PACKET_TYPE_ASCII_FRAME
Complete ASCII frame with all metadata.
Definition packet.h:397
@ PACKET_TYPE_AUDIO_BATCH
Batched audio packets for efficiency.
Definition packet.h:410
ringbuffer_t * ringbuffer_create(size_t element_size, size_t capacity)
Create a new ring buffer.
Definition ringbuffer.c:34
size_t ringbuffer_size(const ringbuffer_t *rb)
Get current number of elements in the buffer.
Definition ringbuffer.c:131
bool ringbuffer_is_full(const ringbuffer_t *rb)
Check if buffer is full.
Definition ringbuffer.c:139
void ringbuffer_destroy(ringbuffer_t *rb)
Destroy a ring buffer and free its memory.
Definition ringbuffer.c:60
bool ringbuffer_is_empty(const ringbuffer_t *rb)
Check if buffer is empty.
Definition ringbuffer.c:135
bool ringbuffer_read(ringbuffer_t *rb, void *data)
Try to read an element from the ring buffer (non-blocking).
Definition ringbuffer.c:92
bool ringbuffer_write(ringbuffer_t *rb, const void *data)
Try to write an element to the ring buffer (non-blocking).
Definition ringbuffer.c:70
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
asciichat_error_t webrtc_datachannel_set_callbacks(webrtc_data_channel_t *dc, const webrtc_datachannel_callbacks_t *callbacks)
Set DataChannel callbacks.
struct webrtc_data_channel webrtc_data_channel_t
struct webrtc_peer_connection webrtc_peer_connection_t
webrtc_state_t webrtc_get_state(webrtc_peer_connection_t *pc)
Get current connection state.
asciichat_error_t webrtc_datachannel_get_max_message_size(webrtc_data_channel_t *dc, size_t *size)
asciichat_error_t webrtc_datachannel_get_buffered_amount(webrtc_data_channel_t *dc, size_t *amount)
void webrtc_peer_connection_close(webrtc_peer_connection_t *pc)
Close a peer connection.
webrtc_state_t
ICE, signaling, DataChannel, and callback settings for a WebRTC peer.
bool webrtc_datachannel_is_open(webrtc_data_channel_t *dc)
Check if DataChannel is open and ready.
asciichat_error_t webrtc_datachannel_send(webrtc_data_channel_t *dc, const uint8_t *data, size_t size)
Send data over DataChannel.
void webrtc_datachannel_set_open_state(webrtc_data_channel_t *dc, bool is_open)
Set DataChannel open state (internal use).
@ WEBRTC_STATE_DISCONNECTED
Connection lost.
@ WEBRTC_STATE_CONNECTING
ICE gathering/connection in progress.
@ WEBRTC_STATE_CONNECTED
DataChannel established and ready.
int socket_t
Transport abstraction layer for ACIP protocol.
acip_transport_type_t
Transport method table (virtual function table).
@ ACIP_TRANSPORT_WEBRTC
WebRTC DataChannel (P2P).
📝 Logging API with multiple log levels and terminal output control
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:743
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:749
void acip_security_cleanup(acip_security_t *security)
asciichat_error_t acip_security_receive(acip_security_t *security, acip_transport_t *transport, packet_type_t type, const void *payload, size_t length)
#define MIN(a, b)
Definition param.h:6
asciichat_error_t acip_packet_plan(crypto_context_t *crypto, const socket_buffer_t *buffers, size_t count, acip_packet_plan_t *plan)
Definition prepare.c:9
asciichat_error_t acip_packet_encrypt(crypto_context_t *crypto, const acip_packet_plan_t *plan, buffer_domain_t *domain, void *ciphertext, size_t capacity, packet_header_t *header, size_t *length)
The useful part of acip packet plan is in buffers, count, plaintext_size, ciphertext_capacity: togeth...
Definition prepare.c:53
Lock-Free Ring Buffer and Frame Buffer Management.
stats_peer_t * stats_runtime_peer_open(const char *transport)
Definition runtime.c:149
struct acip_security acip_security_t
acip security is intentionally a small, concrete record. Fields such as handshake,...
🔤 String Manipulation and Shell Escaping Utilities
size_t ciphertext_capacity
Definition prepare.h:24
buffer_domain_t * domain
Borrowed control reserve for handshake/error traffic; NULL otherwise.
Definition prepare.h:29
crypto_handshake_context_t handshake
Definition security.h:19
Transport method table (virtual function table).
void * impl_data
Transport-specific state.
stats_peer_t * stats_peer
Owned statistics handle, destroyed with transport.
const acip_transport_methods_t * methods
Method table (virtual functions).
crypto_context_t * crypto_ctx
Optional encryption context.
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
Endpoint cryptographic state for handshake, packet protection, authentication, and rekeying.
Packet envelope containing received packet data.
Definition packet.h:1204
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641
Audio ring buffer for real-time audio streaming.
Definition ringbuffer.h:94
Event hooks and caller context for one WebRTC DataChannel.
Receive queue element (variable-length message).
size_t len
Message length in bytes.
uint8_t * data
Message data (allocated, caller must free).
WebRTC transport implementation data.
bool close_requested
Whether this transport has closed its borrowed peer handles.
uint8_t * partial
Incomplete ACIP packet bytes.
webrtc_peer_connection_t * peer_conn
Borrowed peer connection.
uint64_t disconnected_since_ns
Start of the current transient ICE disconnect.
bool is_connected
Connection state.
acip_transport_t * transport
Borrowed enclosing transport.
mutex_t queue_mutex
Protect queue operations.
webrtc_data_channel_t * data_channel
Borrowed data channel.
mutex_t send_mutex
Keep chunks from concurrent packets together.
bool data_channel_closed
DataChannel close is terminal for this transport.
void(* on_ready)(acip_transport_t *, void *)
mutex_t state_mutex
Protect state changes.
cond_t queue_cond
Signal when messages arrive.
acip_security_t * security
Owned per-peer security state.
ringbuffer_t * recv_queue
Receive message queue.
⏱️ High-precision timing utilities using sokol_time.h and uthash
acip_transport_t * acip_webrtc_transport_create_secure(webrtc_peer_connection_t *peer_conn, webrtc_data_channel_t *data_channel, acip_security_t *security, void(*on_ready)(acip_transport_t *, void *), void *user_data)
#define WEBRTC_RECV_QUEUE_HIGH_WATER
acip_security_t * acip_webrtc_transport_security(acip_transport_t *transport)
#define WEBRTC_RECV_QUEUE_SIZE
Receive queue element (variable-length message).
acip_transport_t * acip_webrtc_transport_create(webrtc_peer_connection_t *peer_conn, webrtc_data_channel_t *data_channel, crypto_context_t *crypto_ctx)
#define WEBRTC_DISCONNECTED_GRACE_NS