From a4bcc14283d5a00f6c6ea5247953cbeb832e0eae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20Trzci=C5=84ski?= Date: Wed, 2 Jul 2025 23:33:28 +0200 Subject: [PATCH] webrtc: introduce `timeout_s` by default set to `1h` Client can overwrite this value to set `timeout_s` as part of webrtc request. The `0` completely disables the timeout. --- output/webrtc/webrtc.cc | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/output/webrtc/webrtc.cc b/output/webrtc/webrtc.cc index 7fecc2e..4eedcea 100644 --- a/output/webrtc/webrtc.cc +++ b/output/webrtc/webrtc.cc @@ -17,10 +17,12 @@ extern "C" { #include "util/http/json.hh" #define DEFAULT_PING_INTERVAL_US (1 * 1000 * 1000) -#define DEFAULT_DISCONNECT_INTERVAL_US (30 * 1000 * 1000) +#define DEFAULT_PONG_INTERVAL_US (30 * 1000 * 1000) +#define DEFAULT_TIMEOUT_S (60 * 60) #ifdef USE_LIBDATACHANNEL +#include #include #include #include @@ -122,18 +124,23 @@ public: bool keepAlive() { + uint64_t now_us = get_monotonic_time_us(NULL, NULL); + + if (deadline_us > 0 && now_us > deadline_us) { + LOG_INFO(this, "The stream reached the deadline."); + return false; + } + if (!dc_keepAlive) return true; - uint64_t now_us = get_monotonic_time_us(NULL, NULL); - if (dc_keepAlive->isOpen() && now_us - last_ping_us >= DEFAULT_PING_INTERVAL_US) { LOG_DEBUG(this, "Checking if client still alive."); dc_keepAlive->send("ping"); last_ping_us = now_us; } - if (now_us - last_pong_us >= DEFAULT_DISCONNECT_INTERVAL_US) { + if (now_us - last_pong_us >= DEFAULT_PONG_INTERVAL_US) { LOG_INFO(this, "No heartbeat from client."); return false; } @@ -213,6 +220,7 @@ public: bool requested_key_frame = false; uint64_t last_ping_us = 0; uint64_t last_pong_us = 0; + uint64_t deadline_us = 0; }; std::shared_ptr webrtc_find_client(std::string id) @@ -324,6 +332,12 @@ static std::shared_ptr webrtc_peer_connection(rtc::Configuration config, LOG_INFO(client.get(), "Client does not support Keep-Alives. This might result in stale streams."); } + int64_t timeout_s = message.value("timeout_s", DEFAULT_TIMEOUT_S); + if (timeout_s > 0) { + LOG_INFO(client.get(), "The stream will auto-close in %" PRId64 "s.", timeout_s); + client->deadline_us = get_monotonic_time_us(NULL, NULL) + timeout_s * 1000 * 1000; + } + pc->onTrack([wclient](std::shared_ptr track) { if(auto client = wclient.lock()) { LOG_DEBUG(client.get(), "onTrack: %s", track->mid().c_str());