From 0859c6d61d37dec66ef7fa46329b19cc30c3555a Mon Sep 17 00:00:00 2001 From: Juan Sepulveda Date: Tue, 1 Dec 2026 17:55:23 -0800 Subject: [PATCH 1/4] Add stock LiveKit native transport provider and isolated network setup Signed-off-by: Juan Sepulveda --- src/CMakeLists.txt | 8 + src/plugins/transport_livekit/CMakeLists.txt | 4 + src/plugins/transport_livekit/README.md | 31 ++ .../transport_livekit/cpp/CMakeLists.txt | 5 + src/plugins/transport_livekit/cpp/plugin.cpp | 407 ++++++++++++++++++ .../transport_livekit/tools/setup_network.py | 240 +++++++++++ .../plugins/transport_livekit/pyproject.toml | 7 + .../plugins/transport_livekit/test_setup.py | 102 +++++ 8 files changed, 804 insertions(+) create mode 100644 src/plugins/transport_livekit/CMakeLists.txt create mode 100644 src/plugins/transport_livekit/README.md create mode 100644 src/plugins/transport_livekit/cpp/CMakeLists.txt create mode 100644 src/plugins/transport_livekit/cpp/plugin.cpp create mode 100644 src/plugins/transport_livekit/tools/setup_network.py create mode 100644 tests/python/plugins/transport_livekit/pyproject.toml create mode 100644 tests/python/plugins/transport_livekit/test_setup.py diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index cdef8fe380..e9cfb40734 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -28,3 +28,11 @@ endif() if(BUILD_PLUGINS) add_subdirectory(plugins) endif() + +option(BUILD_TRANSPORT_LIVEKIT_NATIVE "Build the loadable native LiveKit transport" OFF) +if(BUILD_TRANSPORT_LIVEKIT_NATIVE) + if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "Native transport plugins currently require Linux") + endif() + add_subdirectory(plugins/transport_livekit) +endif() diff --git a/src/plugins/transport_livekit/CMakeLists.txt b/src/plugins/transport_livekit/CMakeLists.txt new file mode 100644 index 0000000000..3b0b989ade --- /dev/null +++ b/src/plugins/transport_livekit/CMakeLists.txt @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +find_package(LiveKit 1.13.1 EXACT CONFIG REQUIRED) +add_subdirectory(cpp) diff --git a/src/plugins/transport_livekit/README.md b/src/plugins/transport_livekit/README.md new file mode 100644 index 0000000000..9eec37b471 --- /dev/null +++ b/src/plugins/transport_livekit/README.md @@ -0,0 +1,31 @@ + + +# Native LiveKit transport + +An opt-in, dynamically loaded implementation of the [native transport contract](../../core/media_transport/NATIVE.md). +Applications link the transport interface, not LiveKit. Build the provider with +`BUILD_TRANSPORT_LIVEKIT_NATIVE=ON` and the official LiveKit C++ SDK **1.13.1**; +set `LiveKit_DIR` to its `lib/cmake/LiveKit` directory. With the option off, no +LiveKit SDK is needed. Build applications and providers with the same toolchain. + +The provider supports pre-encoded H.264 publishing, newest-frame CPU RGBA reception, +and bounded, peer/topic-filtered opaque messages. It uses only public SDK APIs. +The SDK owns network retransmission and decode scheduling; the plugin does not +provide CUDA output, immediate playout control, or clock-qualified timing. Its +receive counters are local slot/inbox statistics, not network packet-loss metrics. + +`tools/setup_network.py` creates private host/client credentials and a Docker +Compose test server with verified TLS for an IPv4 LAN/VPN. Run it with `uv run` +to resolve its isolated setup-only dependencies (LiveKit token API and PyYAML). +It does not install a Python media runtime, start services, or configure firewalls. +It requires OpenSSL and refuses existing output directories; transfer only the +client subdirectory. Tokens expire after 24 hours by default, certificates after +seven days. Regeneration requires transferring the new client bundle and restarting +both sites against the matching server. The room is created when a participant +first joins with its generated token. + +This is a single-host test deployment. It does not provision public DNS, TURN, +production certificate renewal or an Internet-facing SFU cluster. diff --git a/src/plugins/transport_livekit/cpp/CMakeLists.txt b/src/plugins/transport_livekit/cpp/CMakeLists.txt new file mode 100644 index 0000000000..0cf1fa1d9b --- /dev/null +++ b/src/plugins/transport_livekit/cpp/CMakeLists.txt @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +find_package(Threads REQUIRED) +add_library(isaac_transport_livekit_native MODULE plugin.cpp) +target_link_libraries(isaac_transport_livekit_native PRIVATE media_transport::native LiveKit::livekit Threads::Threads log_bridge::log_bridge_core) diff --git a/src/plugins/transport_livekit/cpp/plugin.cpp b/src/plugins/transport_livekit/cpp/plugin.cpp new file mode 100644 index 0000000000..d2ac7f732d --- /dev/null +++ b/src/plugins/transport_livekit/cpp/plugin.cpp @@ -0,0 +1,407 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +namespace +{ +namespace mt = isaaccapture::media_transport; +std::mutex sdk_mutex; +unsigned sdk_users = 0; +struct SdkLease +{ + SdkLease() + { + std::lock_guard lock(sdk_mutex); + if (!sdk_users) + livekit::initialize(livekit::LogLevel::Warn); + ++sdk_users; + } + ~SdkLease() + { + std::lock_guard lock(sdk_mutex); + if (!--sdk_users) + livekit::shutdown(); + } +}; +void validate(const mt::Connection& c) +{ + if (c.url.rfind("wss://", 0) != 0 || c.token.empty()) + throw std::invalid_argument("LiveKit requires a verified wss:// URL and token"); +} +class Selection : public livekit::RoomDelegate +{ +public: + std::string publisher, name; + void onTrackSubscribed(livekit::Room&, const livekit::TrackSubscribedEvent& event) override + { + if (!event.participant || !event.track || event.participant->identity() != publisher || + event.track->name() != name) + return; + std::lock_guard guard(mutex); + if (!track) + track = event.track; + } + void onTrackUnsubscribed(livekit::Room&, const livekit::TrackUnsubscribedEvent& event) override + { + std::lock_guard guard(mutex); + if (track && event.track && track->sid() == event.track->sid()) + ended = true; + } + std::shared_ptr selected() + { + std::lock_guard guard(mutex); + return track; + } + bool finished() + { + std::lock_guard guard(mutex); + return ended; + } + +private: + std::mutex mutex; + std::shared_ptr track; + bool ended = false; +}; +class Reader +{ +public: + explicit Reader(const std::shared_ptr& track) + { + livekit::VideoStream::Options options; + options.capacity = 1; + options.format = livekit::VideoBufferType::RGBA; + stream = livekit::VideoStream::fromTrack(track, options); + worker = std::thread( + [this] + { + try + { + livekit::VideoFrameEvent event; + while (stream->read(event)) + { + std::lock_guard guard(mutex); + ++received; + if (latest) + ++overwritten; + latest = std::move(event); + } + } + catch (const std::exception& e) + { + std::lock_guard guard(mutex); + error = e.what(); + } + std::lock_guard guard(mutex); + ended = true; + }); + } + ~Reader() + { + stream->close(); + if (worker.joinable()) + worker.join(); + } + std::optional take() + { + std::lock_guard guard(mutex); + if (!error.empty()) + throw std::runtime_error(error); + auto result = std::move(latest); + latest.reset(); + return result; + } + bool finished() + { + std::lock_guard guard(mutex); + return ended; + } + std::pair counts() + { + std::lock_guard guard(mutex); + return { received, overwritten }; + } + +private: + std::shared_ptr stream; + std::thread worker; + std::mutex mutex; + std::optional latest; + std::string error; + bool ended = false; + std::uint64_t received = 0, overwritten = 0; +}; + +class Publisher final : public mt::Publisher +{ +public: + Publisher(const mt::Connection& c, const mt::VideoConfig& v) : config(v) + { + validate(c); + if (v.track.empty() || !v.width || !v.height || v.width > 8192 || v.height > 8192 || !v.fps || v.fps > 120 || + !v.bitrate) + throw std::invalid_argument("Invalid H.264 video configuration"); + livekit::RoomOptions options; + options.auto_subscribe = false; + options.dynacast = false; + if (!room.connect(c.url, c.token, options)) + throw std::runtime_error("LiveKit publisher connection failed"); + source = std::make_shared(livekit::VideoCodec::H264, v.width, v.height); + track = livekit::LocalVideoTrack::createLocalVideoTrack(v.track, source); + livekit::TrackPublishOptions publish; + publish.source = livekit::TrackSource::SOURCE_CAMERA; + publish.video_codec = livekit::VideoCodec::H264; + publish.video_encoder = livekit::VideoEncoderBackend::PreEncoded; + publish.simulcast = false; + publish.video_encoding = livekit::VideoEncodingOptions{ v.bitrate, static_cast(v.fps) }; + publish.frame_metadata_features = livekit::FrameMetadataFeatures{ true, true, true }; + auto participant = room.localParticipant().lock(); + if (!participant) + throw std::runtime_error("No local participant"); + participant->publishTrack(track, publish); + } + ~Publisher() override + { + try + { + if (auto p = room.localParticipant().lock()) + p->unpublishTrack(track->sid()); + track.reset(); + source.reset(); + room.disconnect(); + } + catch (const std::exception& e) + { + isaaccapture::Logger::get("isaaccapture.transport.livekit")->warn("Publisher shutdown: {}", e.what()); + } + } + mt::Feedback feedback() override + { + auto f = source->takeFeedback(); + mt::Feedback result; + result.keyframe_requested = f.keyframe_requested; + if (f.rate_control) + result.target_bitrate_bps = f.rate_control->target_bitrate_bps; + return result; + } + bool publish(mt::EncodedFrame frame) override + { + if (frame.data.empty() || !frame.timestamp_us) + throw std::invalid_argument("Empty access unit or invalid sender timestamp"); + livekit::EncodedVideoSource::Frame out; + out.width = config.width; + out.height = config.height; + out.is_keyframe = frame.keyframe; + out.timestamp_us = frame.timestamp_us; + out.data = std::move(frame.data); + livekit::VideoFrameMetadata metadata; + metadata.frame_id = frame.frame_id; + metadata.user_timestamp_us = frame.timestamp_us; + out.metadata = metadata; + return source->captureFrame(out); + } + +private: + mt::VideoConfig config; + livekit::Room room; + std::shared_ptr source; + std::shared_ptr track; +}; +class Subscriber final : public mt::Subscriber +{ +public: + Subscriber(const mt::Connection& c, const std::string& publisher, const std::string& track) + { + validate(c); + if (publisher.empty() || track.empty()) + throw std::invalid_argument("Select a publisher and track"); + selection.publisher = publisher; + selection.name = track; + room.setDelegate(&selection); + livekit::RoomOptions options; + options.auto_subscribe = true; + if (!room.connect(c.url, c.token, options)) + throw std::runtime_error("LiveKit subscriber connection failed"); + } + ~Subscriber() override + { + reader.reset(); + try + { + room.disconnect(); + } + catch (const std::exception& e) + { + isaaccapture::Logger::get("isaaccapture.transport.livekit")->warn("Subscriber shutdown: {}", e.what()); + } + room.setDelegate(nullptr); + } + std::optional take() override + { + if (!reader) + if (auto track = selection.selected()) + reader = std::make_unique(track); + if (!reader) + return {}; + auto event = reader->take(); + if (!event) + return {}; + if (event->frame.type() != livekit::VideoBufferType::RGBA) + throw std::runtime_error("Unexpected LiveKit pixel format"); + auto pixels = std::make_shared(std::move(event->frame)); + mt::DecodedFrame out; + out.width = pixels->width(); + out.height = pixels->height(); + out.byte_size = pixels->dataSize(); + out.pixels = std::shared_ptr(pixels, pixels->data()); + if (event->metadata) + { + out.frame_id = event->metadata->frame_id; + out.sender_timestamp_us = event->metadata->user_timestamp_us; + } + return out; + } + bool finished() override + { + return selection.finished() || (reader && reader->finished()); + } + mt::ReceiveStats stats() override + { + mt::ReceiveStats result; + if (reader) + { + auto counts = reader->counts(); + result.received = counts.first; + result.overwritten = counts.second; + if (!stats_requested) + { + pending = selection.selected()->getStats(); + stats_requested = true; + } + } + if (pending && pending->wait_for(std::chrono::seconds(0)) == std::future_status::ready) + { + for (const auto& entry : pending->get()) + if (const auto* inbound = std::get_if(&entry.stats)) + decoder = inbound->inbound.decoder_implementation; + pending.reset(); + } + result.decoder = decoder; + return result; + } + +private: + Selection selection; + livekit::Room room; + std::unique_ptr reader; + bool stats_requested = false; + std::string decoder; + std::optional>> pending; +}; +class Messages final : public mt::MessageSession, private livekit::RoomDelegate +{ +public: + Messages(const mt::Connection& c, const mt::MessageConfig& config) : inbox(config), config(config) + { + validate(c); + room.setDelegate(this); + livekit::RoomOptions options; + options.auto_subscribe = false; + if (!room.connect(c.url, c.token, options)) + throw std::runtime_error("LiveKit message connection failed"); + } + ~Messages() override + { + try + { + room.disconnect(); + } + catch (const std::exception& e) + { + isaaccapture::Logger::get("isaaccapture.transport.livekit")->warn("Message shutdown: {}", e.what()); + } + room.setDelegate(nullptr); + } + void send(const std::vector& payload, mt::Delivery delivery) override + { + mt::validate_payload(payload, delivery); + if (room.connectionState() != livekit::ConnectionState::Connected) + throw std::runtime_error("LiveKit message room is not connected"); + auto participant = room.localParticipant().lock(); + if (!participant) + throw std::runtime_error("No local message participant"); + participant->publishData(payload, delivery == mt::Delivery::Reliable, { config.peer }, config.topic); + } + std::optional take() override + { + return inbox.take(); + } + mt::MessageStats stats() override + { + return inbox.stats(); + } + bool finished() override + { + return ended.load(); + } + +private: + void onUserPacketReceived(livekit::Room&, const livekit::UserDataPacketEvent& event) override + { + // The callback only copies bounded packets; application code never runs on the SDK thread. + if (!event.participant) + return; + inbox.push(event.participant->identity(), event.topic, event.data, + event.kind == livekit::DataPacketKind::Reliable ? mt::Delivery::Reliable : mt::Delivery::Lossy); + } + void onDisconnected(livekit::Room&, const livekit::DisconnectedEvent&) override + { + ended = true; + } + void onRoomEos(livekit::Room&, const livekit::RoomEosEvent&) override + { + ended = true; + } + mt::MessageInbox inbox; + mt::MessageConfig config; + std::atomic ended{ false }; + livekit::Room room; +}; +class Transport final : public mt::Transport +{ +public: + std::unique_ptr messages(const mt::Connection& c, const mt::MessageConfig& config) override + { + return std::make_unique(c, config); + } + std::unique_ptr publisher(const mt::Connection& c, const mt::VideoConfig& v) override + { + return std::make_unique(c, v); + } + std::unique_ptr subscriber(const mt::Connection& c, const std::string& p, const std::string& t) override + { + return std::make_unique(c, p, t); + } + +private: + SdkLease sdk; +}; +} +extern "C" const isaaccapture::media_transport::PluginApi* isaac_media_transport_plugin_v2() +{ + static const isaaccapture::media_transport::PluginApi api{ 2, []() -> mt::Transport* { return new Transport; }, + [](mt::Transport* p) { delete p; } }; + return &api; +} diff --git a/src/plugins/transport_livekit/tools/setup_network.py b/src/plugins/transport_livekit/tools/setup_network.py new file mode 100644 index 0000000000..7eec14a669 --- /dev/null +++ b/src/plugins/transport_livekit/tools/setup_network.py @@ -0,0 +1,240 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# /// script +# requires-python = ">=3.11" +# dependencies = ["livekit-api==1.2.1", "pyyaml==6.0.3"] +# /// +"""Create private, matched LiveKit test bundles without installing a media runtime.""" + +import argparse +from datetime import timedelta +import ipaddress +import os +from pathlib import Path +import secrets +import shlex +import shutil +import subprocess +import sys + +from livekit import api +import yaml + + +def write_private(path, text): + with open(path, "x", opener=lambda p, flags: os.open(p, flags, 0o600)) as handle: + handle.write(text) + + +def generate(output, host_ip, hours=24): + address = ipaddress.IPv4Address(host_ip) + if ( + address.is_loopback + or address.is_unspecified + or address.is_multicast + or address.is_link_local + ): + raise ValueError("Use the host LAN/VPN IPv4 address") + if not 1 <= hours <= 168: + raise ValueError("Token lifetime must be between 1 and 168 hours") + output = Path(output).absolute() + # Exclusive creation never replaces an active server's credentials or follows a symlink. + output.mkdir(mode=0o700, parents=True, exist_ok=False) + try: + _populate(output, str(address), hours) + except BaseException: + shutil.rmtree(output) + raise + return output + + +def _populate(output, address, hours): + key, secret = "mb-" + secrets.token_hex(8), secrets.token_urlsafe(48) + room = "media-bridge-" + secrets.token_hex(6) + write_private(output / ".gitignore", "*\n") + + def token(identity, publish=False, subscribe=False, data=False): + return ( + api.AccessToken(key, secret) + .with_identity(identity) + .with_ttl(timedelta(hours=hours)) + .with_grants( + api.VideoGrants( + room_join=True, + room=room, + can_publish=publish, + can_subscribe=subscribe, + can_publish_data=data, + ) + ) + .to_jwt() + ) + + for role in ("host", "client"): + site = output / role + site.mkdir(mode=0o700) + write_private( + site / "video.token", + token("client-camera", publish=True) + if role == "client" + else token("host-video", subscribe=True), + ) + write_private(site / "messages.token", token(role + "-session", data=True)) + write_private( + site / "connection.env", + f"export LIVEKIT_URL={shlex.quote(f'wss://{address}:8443')}\n" + f"export LIVEKIT_ROOM={shlex.quote(room)}\n", + ) + server = { + "development": False, + "port": 7880, + "bind_addresses": ["127.0.0.1"], + "keys": {key: secret}, + "rtc": { + "node_ip": address, + "use_external_ip": False, + "tcp_port": 7881, + "udp_port": 7882, + "ips": {"includes": [address + "/32"]}, + "data_channel_max_buffered_amount": 1048576, + }, + "logging": {"level": "info"}, + } + write_private(output / "host/livekit.yaml", yaml.safe_dump(server, sort_keys=False)) + tls = output / "host/tls" + tls.mkdir(mode=0o700) + make_certificates(tls, address) + for role in ("host", "client"): + write_private(output / role / "ca.crt", (tls / "ca.crt").read_text()) + write_private( + output / "host/nginx.conf", + f"""events {{}} +http {{ + access_log off; + map $http_upgrade $connection_upgrade {{ default upgrade; '' close; }} + server {{ + listen {address}:8443 ssl; + ssl_certificate /etc/nginx/tls/server.crt; + ssl_certificate_key /etc/nginx/tls/server.key; + ssl_protocols TLSv1.2 TLSv1.3; + location / {{ + proxy_pass http://127.0.0.1:7880; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_read_timeout 3600s; + proxy_buffering off; + }} + }} +}} +""", + ) + compose = { + "name": "isaac-media-bridge-network", + "services": { + "livekit": { + "image": "livekit/livekit-server:v1.13.7", + "network_mode": "host", + "command": ["--config", "/etc/livekit.yaml"], + "volumes": ["./livekit.yaml:/etc/livekit.yaml:ro"], + }, + "signaling": { + "image": "nginx:1.28.0-alpine", + "network_mode": "host", + "depends_on": ["livekit"], + "volumes": [ + "./nginx.conf:/etc/nginx/nginx.conf:ro", + "./tls:/etc/nginx/tls:ro", + ], + }, + }, + } + write_private( + output / "host/compose.yaml", yaml.safe_dump(compose, sort_keys=False) + ) + + +def make_certificates(tls, address): + def openssl(*args): + subprocess.run(["openssl", *args], cwd=tls, check=True, capture_output=True) + + openssl( + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-days", + "7", + "-keyout", + "ca.key", + "-out", + "ca.crt", + "-subj", + "/CN=Media Bridge Test CA", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign", + ) + openssl( + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + "server.key", + "-out", + "server.csr", + "-subj", + f"/CN={address}", + ) + write_private( + tls / "server.ext", + f"subjectAltName=IP:{address}\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\n", + ) + openssl( + "x509", + "-req", + "-in", + "server.csr", + "-CA", + "ca.crt", + "-CAkey", + "ca.key", + "-CAcreateserial", + "-out", + "server.crt", + "-days", + "7", + "-extfile", + "server.ext", + ) + for path in tls.iterdir(): + path.chmod(0o600) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--host-ip", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--hours", type=int, default=24) + args = parser.parse_args() + try: + output = generate(args.output, args.host_ip, args.hours) + except (ValueError, OSError, subprocess.CalledProcessError) as exc: + print(f"Network setup: {exc}", file=sys.stderr) + return 1 + print(f"Created {output}/host and {output}/client for the same room.") + print(f"Tokens expire in {args.hours} hours; certificates expire in 7 days.") + print( + "Keep host private; transfer only client. Use a fresh output directory to regenerate." + ) + print("This generation did not install packages or start services.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/python/plugins/transport_livekit/pyproject.toml b/tests/python/plugins/transport_livekit/pyproject.toml new file mode 100644 index 0000000000..f27f17cd03 --- /dev/null +++ b/tests/python/plugins/transport_livekit/pyproject.toml @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +[project] +name = "test-native-livekit-setup" +version = "0.0.0" +requires-python = ">=3.11" +dependencies = ["pytest>=8", "livekit-api==1.2.1", "pyyaml==6.0.3"] diff --git a/tests/python/plugins/transport_livekit/test_setup.py b/tests/python/plugins/transport_livekit/test_setup.py new file mode 100644 index 0000000000..97694338d8 --- /dev/null +++ b/tests/python/plugins/transport_livekit/test_setup.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import importlib.util +from pathlib import Path +import stat +import subprocess + +import jwt +import pytest +import yaml + +# Use the shared repository locator independently of pytest's working directory. +import sys + +sys.path.insert( + 0, + str( + next( + p + for p in Path(__file__).resolve().parents + if (p / "repo_paths.py").is_file() + ) + ), +) +from repo_paths import repo_root + +ROOT = repo_root() +spec = importlib.util.spec_from_file_location( + "setup_network", ROOT / "src/plugins/transport_livekit/tools/setup_network.py" +) +setup = importlib.util.module_from_spec(spec) +spec.loader.exec_module(setup) + + +def test_matched_credentials_permissions_and_tls(tmp_path): + bundle = setup.generate(tmp_path / "bundle", "192.168.90.1") + server = yaml.safe_load((bundle / "host/livekit.yaml").read_text()) + key, secret = next(iter(server["keys"].items())) + rooms = set() + for role in ("host", "client"): + for kind in ("video", "messages"): + claims = jwt.decode( + (bundle / role / f"{kind}.token").read_text(), + secret, + algorithms=["HS256"], + issuer=key, + ) + rooms.add(claims["video"]["room"]) + assert claims["video"]["roomJoin"] + assert claims["video"]["canPublishData"] == (kind == "messages") + assert claims["video"]["canPublish"] == ( + kind == "video" and role == "client" + ) + assert claims["video"]["canSubscribe"] == ( + kind == "video" and role == "host" + ) + assert claims["exp"] - claims["nbf"] == 86400 + assert not list((bundle / role).glob("*.key")) + assert len(rooms) == 1 + for path in bundle.rglob("*"): + assert stat.S_IMODE(path.stat().st_mode) == (0o700 if path.is_dir() else 0o600) + subprocess.run( + [ + "openssl", + "verify", + "-CAfile", + str(bundle / "client/ca.crt"), + "-verify_ip", + "192.168.90.1", + str(bundle / "host/tls/server.crt"), + ], + check=True, + capture_output=True, + ) + before = (bundle / "client/video.token").read_bytes() + with pytest.raises(FileExistsError): + setup.generate(bundle, "192.168.90.1") + assert before == (bundle / "client/video.token").read_bytes() + + +def test_failure_removes_only_new_bundle(tmp_path, monkeypatch): + def fail(*args): + raise RuntimeError("certificate failure") + + monkeypatch.setattr(setup, "make_certificates", fail) + with pytest.raises(RuntimeError): + setup.generate(tmp_path / "bundle", "192.168.90.1") + assert not (tmp_path / "bundle").exists() + (tmp_path / "link").symlink_to(tmp_path, target_is_directory=True) + with pytest.raises(FileExistsError): + setup.generate(tmp_path / "link", "192.168.90.1") + assert (tmp_path / "link").is_symlink() + + +@pytest.mark.parametrize( + "address,hours", + [("127.0.0.1", 24), ("::1", 24), ("192.168.90.1", 0), ("192.168.90.1", 169)], +) +def test_invalid_input_leaves_no_bundle(tmp_path, address, hours): + with pytest.raises(ValueError): + setup.generate(tmp_path / "bundle", address, hours) + assert not (tmp_path / "bundle").exists() From 796c3064512dcf1b8cda5773e2882a743085d919 Mon Sep 17 00:00:00 2001 From: Juan Sepulveda Date: Tue, 1 Dec 2026 18:02:18 -0800 Subject: [PATCH 2/4] Register LiveKit provisioning checks with CTest Signed-off-by: Juan Sepulveda --- tests/python/CMakeLists.txt | 4 ++++ tests/python/plugins/transport_livekit/CMakeLists.txt | 8 ++++++++ 2 files changed, 12 insertions(+) create mode 100644 tests/python/plugins/transport_livekit/CMakeLists.txt diff --git a/tests/python/CMakeLists.txt b/tests/python/CMakeLists.txt index f2609a4e58..00ca912363 100644 --- a/tests/python/CMakeLists.txt +++ b/tests/python/CMakeLists.txt @@ -33,3 +33,7 @@ endif() if(BUILD_EXAMPLES AND BUILD_PYTHON_BINDINGS) add_subdirectory(examples/teleop_keyboard) endif() + +if(BUILD_TRANSPORT_LIVEKIT_NATIVE) + add_subdirectory(plugins/transport_livekit) +endif() diff --git a/tests/python/plugins/transport_livekit/CMakeLists.txt b/tests/python/plugins/transport_livekit/CMakeLists.txt new file mode 100644 index 0000000000..d77bd21c30 --- /dev/null +++ b/tests/python/plugins/transport_livekit/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +add_test( + NAME livekit_network_setup + COMMAND uv run --python ${ISAAC_TELEOP_PYTHON_VERSION} pytest -v --tb=short test_setup.py + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" +) +set_tests_properties(livekit_network_setup PROPERTIES LABELS "unit") From 4d6151bce10fc4b3b62de8ac2d6a066404113214 Mon Sep 17 00:00:00 2001 From: Juan Sepulveda Date: Wed, 2 Dec 2026 08:21:46 -0800 Subject: [PATCH 3/4] Document per-process TLS trust for native LiveKit bundles Signed-off-by: Juan Sepulveda --- src/plugins/transport_livekit/README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/plugins/transport_livekit/README.md b/src/plugins/transport_livekit/README.md index 9eec37b471..3db33b3d87 100644 --- a/src/plugins/transport_livekit/README.md +++ b/src/plugins/transport_livekit/README.md @@ -29,3 +29,25 @@ first joins with its generated token. This is a single-host test deployment. It does not provision public DNS, TURN, production certificate renewal or an Internet-facing SFU cluster. + +## Trust the generated test CA on both sites + +Before starting **each** application process, source that site's connection file +and point the SDK at the CA from the same bundle. `SITE_BUNDLE` is the host folder +on the host, or the transferred client folder on the client: + +```bash +export SITE_BUNDLE="$HOME/REPLACE_WITH_THIS_SITES_BUNDLE" +source "$SITE_BUNDLE/connection.env" +export SSL_CERT_FILE="$SITE_BUNDLE/ca.crt" +``` + +The pinned Linux SDK accepts `SSL_CERT_FILE`; the native host/client hardware +checks use this per-process trust path. `connection.env` intentionally contains +no generated absolute CA path because the client bundle moves to another machine. +Sourcing it alone does not establish trust. A successful curl with `--cacert` also +does not configure the SDK process. Do not disable certificate verification or +copy the host's CA private key to the client. + +For provider-independent design, see the [network interface](../../core/media_transport/INTERFACE.md) +and [opaque-message interface](../../core/media_transport/messages/INTERFACE.md). From 15e608dc044b150f32bddf9ac24a62f9c798a002 Mon Sep 17 00:00:00 2001 From: Juan Sepulveda Date: Wed, 2 Dec 2026 08:27:31 -0800 Subject: [PATCH 4/4] Constrain native subscriptions and isolate generated server credentials Signed-off-by: Juan Sepulveda --- src/plugins/transport_livekit/cpp/plugin.cpp | 21 ++++++++++++++++++- .../transport_livekit/tools/setup_network.py | 5 +++-- .../plugins/transport_livekit/test_setup.py | 6 ++++++ 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/plugins/transport_livekit/cpp/plugin.cpp b/src/plugins/transport_livekit/cpp/plugin.cpp index d2ac7f732d..4900303e1e 100644 --- a/src/plugins/transport_livekit/cpp/plugin.cpp +++ b/src/plugins/transport_livekit/cpp/plugin.cpp @@ -44,6 +44,21 @@ class Selection : public livekit::RoomDelegate { public: std::string publisher, name; + void request(livekit::RemoteParticipant* participant, + const std::shared_ptr& publication) + { + if (participant && publication && participant->identity() == publisher && publication->name() == name) + publication->setSubscribed(true); + } + void onTrackPublished(livekit::Room&, const livekit::TrackPublishedEvent& event) override + { + request(event.participant, event.publication); + } + void onDisconnected(livekit::Room&, const livekit::DisconnectedEvent&) override + { + std::lock_guard guard(mutex); + ended = true; + } void onTrackSubscribed(livekit::Room&, const livekit::TrackSubscribedEvent& event) override { if (!event.participant || !event.track || event.participant->identity() != publisher || @@ -231,9 +246,13 @@ class Subscriber final : public mt::Subscriber selection.name = track; room.setDelegate(&selection); livekit::RoomOptions options; - options.auto_subscribe = true; + options.auto_subscribe = false; if (!room.connect(c.url, c.token, options)) throw std::runtime_error("LiveKit subscriber connection failed"); + for (const auto& weak : room.remoteParticipants()) + if (auto participant = weak.lock()) + for (const auto& entry : participant->trackPublications()) + selection.request(participant.get(), entry.second); } ~Subscriber() override { diff --git a/src/plugins/transport_livekit/tools/setup_network.py b/src/plugins/transport_livekit/tools/setup_network.py index 7eec14a669..8d6a206201 100644 --- a/src/plugins/transport_livekit/tools/setup_network.py +++ b/src/plugins/transport_livekit/tools/setup_network.py @@ -131,7 +131,7 @@ def token(identity, publish=False, subscribe=False, data=False): """, ) compose = { - "name": "isaac-media-bridge-network", + "name": room, "services": { "livekit": { "image": "livekit/livekit-server:v1.13.7", @@ -145,7 +145,8 @@ def token(identity, publish=False, subscribe=False, data=False): "depends_on": ["livekit"], "volumes": [ "./nginx.conf:/etc/nginx/nginx.conf:ro", - "./tls:/etc/nginx/tls:ro", + "./tls/server.crt:/etc/nginx/tls/server.crt:ro", + "./tls/server.key:/etc/nginx/tls/server.key:ro", ], }, }, diff --git a/tests/python/plugins/transport_livekit/test_setup.py b/tests/python/plugins/transport_livekit/test_setup.py index 97694338d8..303d10a907 100644 --- a/tests/python/plugins/transport_livekit/test_setup.py +++ b/tests/python/plugins/transport_livekit/test_setup.py @@ -57,6 +57,12 @@ def test_matched_credentials_permissions_and_tls(tmp_path): assert claims["exp"] - claims["nbf"] == 86400 assert not list((bundle / role).glob("*.key")) assert len(rooms) == 1 + compose = yaml.safe_load((bundle / "host/compose.yaml").read_text()) + assert compose["name"] == next(iter(rooms)) + mounts = compose["services"]["signaling"]["volumes"] + assert "./tls/server.crt:/etc/nginx/tls/server.crt:ro" in mounts + assert "./tls/server.key:/etc/nginx/tls/server.key:ro" in mounts + assert all("ca.key" not in mount and "./tls:" not in mount for mount in mounts) for path in bundle.rglob("*"): assert stat.S_IMODE(path.stat().st_mode) == (0o700 if path.is_dir() else 0o600) subprocess.run(