From 288958e7406e624fcb263a00b54a2ce708feeddb Mon Sep 17 00:00:00 2001 From: Juan Sepulveda Date: Tue, 1 Dec 2026 17:53:05 -0800 Subject: [PATCH 1/3] Add native media transport contracts and loadable provider lifetime Signed-off-by: Juan Sepulveda --- src/core/CMakeLists.txt | 1 + src/core/media_transport/CMakeLists.txt | 3 + src/core/media_transport/NATIVE.md | 110 ++++++++++++++++++ src/core/media_transport/cpp/CMakeLists.txt | 8 ++ .../cpp/inc/media_transport/messages.hpp | 61 ++++++++++ .../cpp/inc/media_transport/transport.hpp | 96 +++++++++++++++ src/core/media_transport/cpp/messages.cpp | 60 ++++++++++ src/core/media_transport/cpp/plugin.cpp | 89 ++++++++++++++ tests/cpp/core/CMakeLists.txt | 4 + tests/cpp/core/media_transport/CMakeLists.txt | 6 + .../media_transport/loader/CMakeLists.txt | 5 + .../cpp/core/media_transport/loader/main.cpp | 77 ++++++++++++ .../media_transport/messages/CMakeLists.txt | 6 + .../messages/test_messages.cpp | 84 +++++++++++++ .../core/media_transport/mock/CMakeLists.txt | 4 + .../cpp/core/media_transport/mock/plugin.cpp | 79 +++++++++++++ 16 files changed, 693 insertions(+) create mode 100644 src/core/media_transport/CMakeLists.txt create mode 100644 src/core/media_transport/NATIVE.md create mode 100644 src/core/media_transport/cpp/CMakeLists.txt create mode 100644 src/core/media_transport/cpp/inc/media_transport/messages.hpp create mode 100644 src/core/media_transport/cpp/inc/media_transport/transport.hpp create mode 100644 src/core/media_transport/cpp/messages.cpp create mode 100644 src/core/media_transport/cpp/plugin.cpp create mode 100644 tests/cpp/core/media_transport/CMakeLists.txt create mode 100644 tests/cpp/core/media_transport/loader/CMakeLists.txt create mode 100644 tests/cpp/core/media_transport/loader/main.cpp create mode 100644 tests/cpp/core/media_transport/messages/CMakeLists.txt create mode 100644 tests/cpp/core/media_transport/messages/test_messages.cpp create mode 100644 tests/cpp/core/media_transport/mock/CMakeLists.txt create mode 100644 tests/cpp/core/media_transport/mock/plugin.cpp diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index a0795b0723..e29428ee3c 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -28,6 +28,7 @@ add_subdirectory(plugin_manager) # Camera interface: Linux only, for its shared memory and the socket between processes if(CMAKE_SYSTEM_NAME STREQUAL "Linux") add_subdirectory(camera) + add_subdirectory(media_transport) endif() # Build OXR library (depends on oxr_utils for types) diff --git a/src/core/media_transport/CMakeLists.txt b/src/core/media_transport/CMakeLists.txt new file mode 100644 index 0000000000..4dc73117f9 --- /dev/null +++ b/src/core/media_transport/CMakeLists.txt @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +add_subdirectory(cpp) diff --git a/src/core/media_transport/NATIVE.md b/src/core/media_transport/NATIVE.md new file mode 100644 index 0000000000..feeca42d85 --- /dev/null +++ b/src/core/media_transport/NATIVE.md @@ -0,0 +1,110 @@ + + +# Native video transport interface — initial milestone + +The C++ interface in `cpp/inc/media_transport/transport.hpp` separates Media Bridge +applications from the SDK implementation. The sender owns CameraReader/NVENC; the +viewer owns SDL. Neither includes nor links LiveKit. A selected shared library +implements transport sessions. The initial provider is +`src/plugins/transport_livekit/cpp`, using the official unmodified SDK. + +```text +OAK plugin → CameraReader → NVENC → Publisher interface + ↓ loaded LiveKit plugin + network + ↓ loaded LiveKit plugin +SDL window ← CPU RGBA frame ← Subscriber interface +``` + +## Contract + +- `Connection` carries provider endpoint and token. Keep tokens private; the + examples read files generated from site bundles. The LiveKit provider requires TLS. +- A publisher is configured for one H.264 track with fixed dimensions, fps and + bitrate. `publish` consumes an owned Annex-B access unit, keyframe flag, frame ID + and sender-monotonic timestamp. Local acceptance is not a delivery guarantee. +- `feedback` returns keyframe requests and target bitrate; the sender applies + them to its encoder. The initial implementation does not implement frame-rate + adaptation, other codecs, reconnect, or an encoded-stream recovery protocol. +- A subscriber selects one publisher identity and track. `take` is nonblocking + and returns the newest available frame, or empty. Failures throw; `finished` + reports end-of-stream. Call a session's methods from one application thread. +- Decoded output is tightly packed **CPU RGBA**, with explicit dimensions, byte + extent and shared ownership. Sender frame ID/timestamp are optional; missing + metadata must not be fabricated. This timestamp is not host-clock qualified. +- The LiveKit provider has a one-frame SDK queue and one-frame application slot. + Its counters expose worker reads and slot overwrites, not all network/SDK drops. +- Sessions retain the provider instance. Retained frames retain that instance too, + so pixel buffers remain valid even after the subscriber and `Plugin` are gone. + Frames alias the SDK-owned buffer; the interface adds no full-frame pixel copy. + +## Opaque messages + +`Plugin::messages(Connection, MessageConfig)` creates a bidirectional session for +one explicit peer and topic. `send` accepts owned-by-caller binary bytes during a +synchronous call; implementations must not retain the caller's storage after it +returns. `take` transfers an owned message out of a bounded FIFO without waiting. +Use the session from one application thread; provider callbacks feed the +thread-safe `MessageInbox`. Sessions retain the plugin just as video sessions do. + +Payloads are limited to 1–1024 bytes. Peer/topic limits are 256/128 bytes; empty +strings and embedded NUL are rejected. The inbox defaults to 64 packets, accepts +capacities 1–1024, and rejects newest on overflow. `accepted`, `dropped`, `filtered` +and `queued` expose local receive behavior; none is a network delivery counter. +Unknown senders/topics are filtered before payload copying. No payload schema, +clock domain, timestamp interpretation or actuator policy is imposed. + +`Reliable` requests the provider's reliable channel and `Lossy` requests its lossy +channel. Neither promises durable delivery, recipient acknowledgement or replay. +Send may block/throw; it belongs outside capture and real-time control callbacks. +`finished` indicates terminal session end. The LiveKit provider uses stock +`publishData` and `onUserPacketReceived`, with video subscription disabled. + +The experimental ABI is now v2 because adding a session factory changes the C++ +vtable. Rebuild both sides of the plugin boundary; v1 libraries fail loading +rather than being invoked with an incompatible layout. + +## Loading and building + +`Plugin` loads an explicit absolute path with `RTLD_LOCAL` and validates the +`isaac_media_transport_plugin_v2` descriptor before calling its factory. This is +an **experimental same-toolchain C++ ABI**, not a stable cross-compiler plugin ABI. +Build providers with the matching header, compiler, standard library and ABI. +Load only trusted libraries: a native plugin executes code in the application. + +`BUILD_TRANSPORT_LIVEKIT_NATIVE=ON` builds `isaac_transport_livekit_native` and +requires the SDK. With it OFF (the default), neither the core nor the examples +require LiveKit package discovery. The option is independent of `BUILD_PLUGINS`, +which controls the existing device-plugin executables. Build the selected provider +explicitly alongside the application, then pass its library via `--transport-plugin`. +The application has no hardcoded provider path or default fallback. + +A new provider implements `Transport`, `Publisher`, `Subscriber`, and +`MessageSession`, and exports +its factory descriptor. Match the documented buffer, lifetime and error contracts. +Do not claim support for a different memory type by placing a GPU address in the +CPU frame field; GPU output needs an explicit future interface extension. + +With `BUILD_TESTING=ON`, build `media_transport_loader_test` and +`media_transport_message_tests`, then run +`ctest --test-dir "$BUILD_DIR" -R '^media_transport_(native_lifetime|messages)$' --output-on-failure`. +The test uses a mock provider, requires no LiveKit SDK, and checks invalid paths, +ABI rejection, null factory results, and frames/messages surviving session/loader +destruction. Message tests also cover binary ownership, bounds, filtering, FIFO +overflow and concurrent producer/consumer use. + +## Boundaries still to address + +This milestone provides native video and opaque messages. It does not implement +the Python robot-control adapter or its plugin discovery/package installer. +Audio/tactile schemas, capability negotiation, production binary +packaging, and clock-qualified latency reporting remain subsequent work. Keep +those additions explicit rather than implying that this video subset is the +complete transport contract already under review. + +Stock LiveKit reception still exposes CPU buffers. Plugin extraction does not +restore NVDEC/CUDA IPC or immediate playout. Compare timing only after equivalent +instrumentation is restored; frame delivery alone is not latency parity. diff --git a/src/core/media_transport/cpp/CMakeLists.txt b/src/core/media_transport/cpp/CMakeLists.txt new file mode 100644 index 0000000000..5527f0ff40 --- /dev/null +++ b/src/core/media_transport/cpp/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +add_library(media_transport_native STATIC plugin.cpp messages.cpp) +set_target_properties(media_transport_native PROPERTIES POSITION_INDEPENDENT_CODE ON) +target_compile_features(media_transport_native PUBLIC cxx_std_20) +target_include_directories(media_transport_native INTERFACE inc) +target_link_libraries(media_transport_native PRIVATE ${CMAKE_DL_LIBS}) +add_library(media_transport::native ALIAS media_transport_native) diff --git a/src/core/media_transport/cpp/inc/media_transport/messages.hpp b/src/core/media_transport/cpp/inc/media_transport/messages.hpp new file mode 100644 index 0000000000..fa72424853 --- /dev/null +++ b/src/core/media_transport/cpp/inc/media_transport/messages.hpp @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +#pragma once +#include +#include +#include +#include +#include +#include +#include +namespace isaaccapture::media_transport +{ +enum class Delivery +{ + Reliable, + Lossy +}; +inline constexpr std::size_t max_message_bytes = 1024; +struct MessageConfig +{ + std::string peer, topic; + std::size_t capacity = 64; +}; +struct Message +{ + std::vector payload; + std::string sender, topic; + Delivery delivery = Delivery::Reliable; +}; +struct MessageStats +{ + std::uint64_t accepted = 0, dropped = 0, filtered = 0; + std::size_t queued = 0; +}; +void validate_payload(const std::vector&, Delivery); +// Bounded FIFO for provider callbacks. Reject newest on overflow; counters never imply network loss. +class MessageInbox +{ +public: + explicit MessageInbox(MessageConfig config); + void push(const std::string& sender, const std::string& topic, const std::vector& payload, Delivery); + std::optional take(); + MessageStats stats(); + +private: + MessageConfig config; + std::mutex mutex; + std::deque queue; + MessageStats counts; +}; +class MessageSession +{ +public: + virtual ~MessageSession() = default; + // Synchronous SDK submission; may block/throw. No recipient acknowledgement or replay guarantee. + virtual void send(const std::vector& payload, Delivery) = 0; + virtual std::optional take() = 0; + virtual MessageStats stats() = 0; + virtual bool finished() = 0; +}; +} diff --git a/src/core/media_transport/cpp/inc/media_transport/transport.hpp b/src/core/media_transport/cpp/inc/media_transport/transport.hpp new file mode 100644 index 0000000000..7e74efc7d3 --- /dev/null +++ b/src/core/media_transport/cpp/inc/media_transport/transport.hpp @@ -0,0 +1,96 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +#pragma once +#include "messages.hpp" + +#include +#include +#include +#include +#include +#include +namespace isaaccapture::media_transport +{ +struct Connection +{ + std::string url, token; +}; +struct VideoConfig +{ + std::string track = "cam"; + std::uint32_t width = 0, height = 0, fps = 30, bitrate = 4000000; +}; +struct EncodedFrame +{ + // Owns one Annex-B H.264 access unit. Timestamp uses the sender's monotonic clock. + std::vector data; + std::uint64_t timestamp_us = 0; + std::uint32_t frame_id = 0; + bool keyframe = false; +}; +struct Feedback +{ + bool keyframe_requested = false; + std::optional target_bitrate_bps; +}; +struct DecodedFrame +{ + // Tightly packed CPU RGBA. GPU handles require a future, explicit memory contract. + std::shared_ptr pixels; + std::size_t byte_size = 0; + int width = 0, height = 0; + std::optional sender_timestamp_us; + std::optional frame_id; +}; +struct ReceiveStats +{ + std::uint64_t received = 0, overwritten = 0; + std::string decoder; +}; +class Publisher +{ +public: + virtual ~Publisher() = default; + virtual Feedback feedback() = 0; + // Consumes the owned access unit; false indicates local rejection, not delivery status. + virtual bool publish(EncodedFrame frame) = 0; +}; +class Subscriber +{ +public: + virtual ~Subscriber() = default; + // Nonblocking newest-frame read; empty means no new frame. Errors throw. + virtual std::optional take() = 0; + virtual bool finished() = 0; + virtual ReceiveStats stats() = 0; +}; +class Transport +{ +public: + virtual ~Transport() = default; + virtual std::unique_ptr messages(const Connection&, const MessageConfig&) = 0; + virtual std::unique_ptr publisher(const Connection&, const VideoConfig&) = 0; + virtual std::unique_ptr subscriber(const Connection&, + const std::string& publisher, + const std::string& track) = 0; +}; +// Experimental same-toolchain C++ ABI, not a stable third-party binary interface. +struct PluginApi +{ + std::uint32_t version; + Transport* (*create)(); + void (*destroy)(Transport*); +}; +using PluginEntry = const PluginApi* (*)(); +class Plugin +{ +public: + explicit Plugin(const std::string& library); + std::shared_ptr messages(const Connection&, const MessageConfig&) const; + std::shared_ptr publisher(const Connection&, const VideoConfig&) const; + std::shared_ptr subscriber(const Connection&, const std::string& publisher, const std::string& track) const; + +private: + std::shared_ptr transport; +}; +} diff --git a/src/core/media_transport/cpp/messages.cpp b/src/core/media_transport/cpp/messages.cpp new file mode 100644 index 0000000000..193c0ec049 --- /dev/null +++ b/src/core/media_transport/cpp/messages.cpp @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +#include "inc/media_transport/messages.hpp" + +#include +#include +namespace isaaccapture::media_transport +{ +void validate_payload(const std::vector& payload, Delivery delivery) +{ + if (payload.empty() || payload.size() > max_message_bytes) + throw std::invalid_argument("Messages require 1..1024 payload bytes"); + if (delivery != Delivery::Reliable && delivery != Delivery::Lossy) + throw std::invalid_argument("Invalid message delivery mode"); +} +MessageInbox::MessageInbox(MessageConfig c) : config(std::move(c)) +{ + if (config.peer.empty() || config.peer.size() > 256 || config.topic.empty() || config.topic.size() > 128 || + config.peer.find('\0') != std::string::npos || config.topic.find('\0') != std::string::npos || + !config.capacity || config.capacity > 1024) + throw std::invalid_argument( + "Messages require a peer (1..256 bytes), topic (1..128 bytes), and capacity (1..1024)"); +} +void MessageInbox::push(const std::string& sender, + const std::string& topic, + const std::vector& payload, + Delivery delivery) +{ + std::lock_guard lock(mutex); + if (sender != config.peer || topic != config.topic) + { + ++counts.filtered; + return; + } + if (payload.empty() || payload.size() > max_message_bytes || queue.size() == config.capacity || + (delivery != Delivery::Reliable && delivery != Delivery::Lossy)) + { + ++counts.dropped; + return; + } + queue.push_back({ payload, sender, topic, delivery }); + ++counts.accepted; +} +std::optional MessageInbox::take() +{ + std::lock_guard lock(mutex); + if (queue.empty()) + return {}; + auto next = std::move(queue.front()); + queue.pop_front(); + return next; +} +MessageStats MessageInbox::stats() +{ + std::lock_guard lock(mutex); + auto result = counts; + result.queued = queue.size(); + return result; +} +} diff --git a/src/core/media_transport/cpp/plugin.cpp b/src/core/media_transport/cpp/plugin.cpp new file mode 100644 index 0000000000..741d1aef76 --- /dev/null +++ b/src/core/media_transport/cpp/plugin.cpp @@ -0,0 +1,89 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +#include "inc/media_transport/transport.hpp" + +#include +#include +namespace isaaccapture::media_transport +{ +Plugin::Plugin(const std::string& path) +{ + if (path.empty() || path.front() != '/') + throw std::invalid_argument("Transport plugin requires an absolute library path"); + void* raw = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!raw) + throw std::runtime_error(std::string("Cannot load transport plugin: ") + dlerror()); + auto library = std::shared_ptr(raw, [](void* p) { dlclose(p); }); + dlerror(); + auto entry = reinterpret_cast(dlsym(raw, "isaac_media_transport_plugin_v2")); + const char* error = dlerror(); + if (error || !entry) + throw std::runtime_error("Transport plugin is missing isaac_media_transport_plugin_v2"); + const PluginApi* api = entry(); + if (!api || api->version != 2 || !api->create || !api->destroy) + throw std::runtime_error("Unsupported transport plugin ABI"); + auto* instance = api->create(); + if (!instance) + throw std::runtime_error("Transport plugin creation failed"); + transport = std::shared_ptr(instance, [library, destroy = api->destroy](Transport* p) { destroy(p); }); +} +std::shared_ptr Plugin::messages(const Connection& c, const MessageConfig& config) const +{ + auto object = transport->messages(c, config); + if (!object) + throw std::runtime_error("Transport returned no message session"); + return std::shared_ptr(object.release(), [owner = transport](MessageSession* p) { delete p; }); +} +std::shared_ptr Plugin::publisher(const Connection& c, const VideoConfig& v) const +{ + auto object = transport->publisher(c, v); + if (!object) + throw std::runtime_error("Transport returned no publisher"); + return std::shared_ptr(object.release(), [owner = transport](Publisher* p) { delete p; }); +} +namespace +{ +struct FrameLease +{ + std::shared_ptr transport; + std::shared_ptr pixels; +}; +class BoundSubscriber final : public Subscriber +{ +public: + BoundSubscriber(std::shared_ptr owner, std::unique_ptr backend) + : owner(std::move(owner)), backend(std::move(backend)) + { + } + std::optional take() override + { + auto frame = backend->take(); + if (frame && frame->pixels) + { + auto lease = std::make_shared(FrameLease{ owner, frame->pixels }); + frame->pixels = std::shared_ptr(lease, lease->pixels.get()); + } + return frame; + } + bool finished() override + { + return backend->finished(); + } + ReceiveStats stats() override + { + return backend->stats(); + } + +private: + std::shared_ptr owner; + std::unique_ptr backend; +}; +} +std::shared_ptr Plugin::subscriber(const Connection& c, const std::string& p, const std::string& t) const +{ + auto object = transport->subscriber(c, p, t); + if (!object) + throw std::runtime_error("Transport returned no subscriber"); + return std::make_shared(transport, std::move(object)); +} +} diff --git a/tests/cpp/core/CMakeLists.txt b/tests/cpp/core/CMakeLists.txt index bcd3773693..6edca06b44 100644 --- a/tests/cpp/core/CMakeLists.txt +++ b/tests/cpp/core/CMakeLists.txt @@ -26,3 +26,7 @@ endif() if(BUILD_OVXR_CAMERA_QUADS) add_subdirectory(ovxr_pip_layer) endif() + +if(TARGET media_transport_native) + add_subdirectory(media_transport) +endif() diff --git a/tests/cpp/core/media_transport/CMakeLists.txt b/tests/cpp/core/media_transport/CMakeLists.txt new file mode 100644 index 0000000000..feec8e12ba --- /dev/null +++ b/tests/cpp/core/media_transport/CMakeLists.txt @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +add_subdirectory(mock) +add_subdirectory(loader) +add_test(NAME media_transport_native_lifetime COMMAND media_transport_loader_test $ "${CMAKE_CURRENT_BINARY_DIR}/destroyed.txt") +add_subdirectory(messages) diff --git a/tests/cpp/core/media_transport/loader/CMakeLists.txt b/tests/cpp/core/media_transport/loader/CMakeLists.txt new file mode 100644 index 0000000000..8c14b2b97e --- /dev/null +++ b/tests/cpp/core/media_transport/loader/CMakeLists.txt @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +add_executable(media_transport_loader_test main.cpp) +target_link_libraries(media_transport_loader_test PRIVATE media_transport::native) +add_dependencies(media_transport_loader_test media_transport_mock) diff --git a/tests/cpp/core/media_transport/loader/main.cpp b/tests/cpp/core/media_transport/loader/main.cpp new file mode 100644 index 0000000000..d9029f7d1c --- /dev/null +++ b/tests/cpp/core/media_transport/loader/main.cpp @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include +namespace mt = isaaccapture::media_transport; +void check(bool condition) +{ + if (!condition) + throw std::runtime_error("Transport loader invariant failed"); +} +template +void rejects(F f) +{ + bool rejected = false; + try + { + f(); + } + catch (const std::exception&) + { + rejected = true; + } + check(rejected); +} +int main(int argc, char** argv) +{ + try + { + check(argc == 3); + std::filesystem::remove(argv[2]); + check(setenv("MOCK_DESTROYED", argv[2], 1) == 0); + rejects([] { mt::Plugin invalid("relative.so"); }); + rejects([] { mt::Plugin invalid("/no/such/transport-plugin.so"); }); + check(setenv("MOCK_BAD_ABI", "1", 1) == 0); + rejects([&] { mt::Plugin invalid(argv[1]); }); + unsetenv("MOCK_BAD_ABI"); + std::shared_ptr messages; + { + mt::Plugin plugin(argv[1]); + rejects([&] { plugin.messages({}, {}); }); + messages = plugin.messages({}, { "peer", "topic" }); + } + check(!std::filesystem::exists(argv[2])); + messages->send({ 0, 255, 42 }, mt::Delivery::Reliable); + auto message = messages->take(); + messages.reset(); + check(std::filesystem::exists(argv[2])); + check(message && message->payload == std::vector({ 0, 255, 42 })); + std::filesystem::remove(argv[2]); + std::shared_ptr subscriber; + { + mt::Plugin plugin(argv[1]); + rejects([&] { plugin.publisher({}, {}); }); + subscriber = plugin.subscriber({}, "publisher", "track"); + } + check(!std::filesystem::exists(argv[2])); + auto frame = subscriber->take(); + check(frame && frame->pixels.get()[0] == 42); + subscriber.reset(); + check(!std::filesystem::exists(argv[2])); + check(frame->pixels.get()[0] == 42); + frame.reset(); + check(std::filesystem::exists(argv[2])); + std::filesystem::remove(argv[2]); + std::cout << "Native transport loader errors and retained frame lifetime: passed\n"; + return 0; + } + catch (const std::exception& e) + { + std::cerr << e.what() << '\n'; + return 1; + } +} diff --git a/tests/cpp/core/media_transport/messages/CMakeLists.txt b/tests/cpp/core/media_transport/messages/CMakeLists.txt new file mode 100644 index 0000000000..f4797b3025 --- /dev/null +++ b/tests/cpp/core/media_transport/messages/CMakeLists.txt @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +find_package(Threads REQUIRED) +add_executable(media_transport_message_tests test_messages.cpp) +target_link_libraries(media_transport_message_tests PRIVATE media_transport::native Threads::Threads) +add_test(NAME media_transport_messages COMMAND media_transport_message_tests) diff --git a/tests/cpp/core/media_transport/messages/test_messages.cpp b/tests/cpp/core/media_transport/messages/test_messages.cpp new file mode 100644 index 0000000000..487ee5a519 --- /dev/null +++ b/tests/cpp/core/media_transport/messages/test_messages.cpp @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include +namespace mt = isaaccapture::media_transport; +void check(bool ok) +{ + if (!ok) + throw std::runtime_error("Message contract check failed"); +} +template +void rejects(F operation) +{ + bool rejected = false; + try + { + operation(); + } + catch (const std::invalid_argument&) + { + rejected = true; + } + check(rejected); +} +int main() +{ + try + { + rejects([] { mt::MessageInbox inbox({ "", "topic" }); }); + rejects([] { mt::MessageInbox inbox({ "peer", "topic", 0 }); }); + rejects([] { mt::MessageInbox inbox({ "peer", "topic", 1025 }); }); + rejects([] { mt::MessageInbox inbox({ std::string(257, 'x'), "topic" }); }); + rejects([] { mt::MessageInbox inbox({ "peer", std::string("a\0b", 3) }); }); + rejects([] { mt::validate_payload({}, mt::Delivery::Reliable); }); + rejects([] { mt::validate_payload(std::vector(1025), mt::Delivery::Reliable); }); + rejects([] { mt::validate_payload({ 1 }, static_cast(99)); }); + mt::validate_payload(std::vector(1024), mt::Delivery::Lossy); + mt::MessageInbox inbox({ "peer", "topic", 2 }); + std::vector bytes{ 0, 255, 42 }; + inbox.push("other", "topic", bytes, mt::Delivery::Reliable); + inbox.push("peer", "other", bytes, mt::Delivery::Reliable); + inbox.push("peer", "topic", bytes, mt::Delivery::Reliable); + bytes[0] = 19; + inbox.push("peer", "topic", bytes, mt::Delivery::Lossy); + inbox.push("peer", "topic", { 7 }, mt::Delivery::Reliable); + auto stats = inbox.stats(); + check(stats.queued == 2 && stats.accepted == 2 && stats.dropped == 1 && stats.filtered == 2); + auto first = inbox.take(), second = inbox.take(); + check(first && first->payload[0] == 0 && first->payload[1] == 255 && first->sender == "peer"); + check(second && second->payload[0] == 19 && second->delivery == mt::Delivery::Lossy); + check(!inbox.take() && inbox.stats().queued == 0); + inbox.push("peer", "topic", {}, mt::Delivery::Reliable); + inbox.push("peer", "topic", std::vector(1025), mt::Delivery::Reliable); + check(inbox.stats().dropped == 3); + std::atomic done = false; + std::thread producer( + [&] + { + for (int i = 0; i < 10000; ++i) + inbox.push("peer", "topic", { 42 }, mt::Delivery::Reliable); + done = true; + }); + std::size_t consumed = 0; + while (!done || inbox.stats().queued) + { + if (inbox.take()) + ++consumed; + std::this_thread::yield(); + } + producer.join(); + stats = inbox.stats(); + check(stats.accepted - 2 == consumed && stats.accepted + stats.dropped == 10005); + std::cout << "Message bounds, filtering, FIFO, binary ownership and concurrent delivery: passed\n"; + } + catch (const std::exception& e) + { + std::cerr << e.what() << '\n'; + return 1; + } +} diff --git a/tests/cpp/core/media_transport/mock/CMakeLists.txt b/tests/cpp/core/media_transport/mock/CMakeLists.txt new file mode 100644 index 0000000000..0845c9a20c --- /dev/null +++ b/tests/cpp/core/media_transport/mock/CMakeLists.txt @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +add_library(media_transport_mock MODULE plugin.cpp) +target_link_libraries(media_transport_mock PRIVATE media_transport::native) diff --git a/tests/cpp/core/media_transport/mock/plugin.cpp b/tests/cpp/core/media_transport/mock/plugin.cpp new file mode 100644 index 0000000000..eaf763cee0 --- /dev/null +++ b/tests/cpp/core/media_transport/mock/plugin.cpp @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +namespace mt = isaaccapture::media_transport; +class Sub : public mt::Subscriber +{ +public: + std::optional take() override + { + mt::DecodedFrame f; + f.width = f.height = 1; + f.byte_size = 4; + auto p = std::shared_ptr(new std::uint8_t[4]{ 42, 0, 0, 255 }, [](auto* p) { delete[] p; }); + f.pixels = p; + return f; + } + bool finished() override + { + return false; + } + mt::ReceiveStats stats() override + { + return {}; + } +}; +class Messages : public mt::MessageSession +{ +public: + void send(const std::vector& data, mt::Delivery) override + { + payload = data; + } + std::optional take() override + { + return mt::Message{ payload, "peer", "topic" }; + } + mt::MessageStats stats() override + { + return {}; + } + bool finished() override + { + return false; + } + +private: + std::vector payload; +}; +class Transport : public mt::Transport +{ +public: + std::unique_ptr messages(const mt::Connection&, const mt::MessageConfig& c) override + { + if (c.peer.empty()) + return {}; + return std::make_unique(); + } + ~Transport() + { + std::ofstream(std::getenv("MOCK_DESTROYED")) << "destroyed\n"; + } + std::unique_ptr publisher(const mt::Connection&, const mt::VideoConfig&) override + { + return {}; + } + std::unique_ptr subscriber(const mt::Connection&, const std::string&, const std::string&) override + { + return std::make_unique(); + } +}; +extern "C" const mt::PluginApi* isaac_media_transport_plugin_v2() +{ + static mt::PluginApi api{ 2, []() -> mt::Transport* { return new Transport; }, [](mt::Transport* p) { delete p; } }; + api.version = std::getenv("MOCK_BAD_ABI") ? 99 : 2; + return &api; +} From 64ad59c718d5cdd787114ed435322817b1cea903 Mon Sep 17 00:00:00 2001 From: Juan Sepulveda Date: Wed, 2 Dec 2026 08:21:24 -0800 Subject: [PATCH 2/3] Translate provider initialization errors and document native interfaces Signed-off-by: Juan Sepulveda --- src/core/media_transport/INTERFACE.md | 98 +++++++++++++++++++ src/core/media_transport/NATIVE.md | 7 +- src/core/media_transport/cpp/plugin.cpp | 22 ++++- .../media_transport/messages/INTERFACE.md | 76 ++++++++++++++ .../cpp/core/media_transport/loader/main.cpp | 22 +++++ .../cpp/core/media_transport/mock/plugin.cpp | 29 +++++- 6 files changed, 247 insertions(+), 7 deletions(-) create mode 100644 src/core/media_transport/INTERFACE.md create mode 100644 src/core/media_transport/messages/INTERFACE.md diff --git a/src/core/media_transport/INTERFACE.md b/src/core/media_transport/INTERFACE.md new file mode 100644 index 0000000000..c8e3b9c807 --- /dev/null +++ b/src/core/media_transport/INTERFACE.md @@ -0,0 +1,98 @@ + + +# Network transport interface + +This is the implemented native C++ contract, not the broader future media API. +The authoritative declarations are in [transport.hpp](cpp/inc/media_transport/transport.hpp). +Applications choose a provider library; their capture, encoding and display code +uses these interfaces without including the provider SDK. + +## Responsibilities and classes + +```text +Camera plugin → CameraReader → application encoder → Publisher + │ + Transport implementation + │ network + Transport implementation + │ +Application display/consumer ← DecodedFrame ← Subscriber +``` + +| Class / value | Responsibility | +| --- | --- | +| `Plugin` | Load an explicit absolute library path, check ABI, retain provider lifetime. | +| `Transport` | Factory for a `Publisher`, `Subscriber`, or `MessageSession`. | +| `Connection` | Provider endpoint URL and private authentication token. | +| `VideoConfig` | One track: dimensions, frame rate and target bitrate. | +| `Publisher` | Accept encoded frames and expose encoder feedback. | +| `EncodedFrame` | Owned Annex-B H.264 access unit, keyframe flag, frame ID and sender-monotonic microseconds. | +| `Feedback` | Keyframe request and optional target bitrate; the application controls the encoder. | +| `Subscriber` | Nonblocking newest-frame read, terminal status and local receive statistics. | +| `DecodedFrame` | Shared, tightly packed CPU RGBA pixels, dimensions/extent, optional sender frame ID and timestamp. | +| `MessageSession` | Bidirectional opaque bytes; see the [messaging interface](messages/INTERFACE.md). | + +## Application flow + +```cpp +namespace mt = isaaccapture::media_transport; +mt::Plugin provider(absolute_library_path); +auto publisher = provider.publisher(connection, video_config); +auto feedback = publisher->feedback(); // Apply to the application's encoder. +bool accepted = publisher->publish(std::move(encoded_frame)); + +// On the receiving machine: +auto subscriber = provider.subscriber(connection, publisher_identity, track_name); +const bool ended = subscriber->finished(); +if (auto frame = subscriber->take()) { + consume(*frame); +} else if (ended) { + // Drain before ending: a final frame may remain after finished() becomes true. +} +``` + +Factories establish sessions and may block or throw. Call each session's methods +from one application thread. `publish` consumes its frame; `false` is local +rejection, not a remote delivery acknowledgement. The application owns encoder +adaptation and decides how to handle rejection. `take` returns empty when there is +no new frame; it does not wait. Provider failures throw. No automatic application +reconnect or durable replay is promised. + +Sessions keep the provider loaded. Returned pixel leases remain valid after the +subscriber or loader is destroyed. Keep the `DecodedFrame` ownership while using +its pixels; never retain only its raw pointer. Plugin initialization exceptions +are translated before unloading the library. Provider destructors must not throw. + +A timestamp received from another machine is not automatically comparable to the +local clock. Missing metadata remains absent. `ReceiveStats.received` and +`overwritten` count local reads and slot replacement, not network packet loss or +photon-to-photon latency. + +## Implementing another provider + +Implement `Transport`, `Publisher`, `Subscriber`, and `MessageSession`, then export +`isaac_media_transport_plugin_v2()` returning `PluginApi{2, create, destroy}`. +Build the application and provider with matching headers, compiler, standard +library and ABI settings. This is an experimental same-toolchain C++ boundary, +not a stable cross-compiler binary interface. Load only trusted libraries. + +Keep SDK setup, sessions, callback threads and cleanup inside the provider. Keep +camera drivers, encoder configuration and presentation outside it. Validate +ownership, bounded queues, error paths and shutdown against the core tests. +Selecting only one provider must not require other providers' SDKs. + +## Cameras, clients and future streams + +The transport sees encoded video, not camera brands or Jetson models. The example +uses `CameraReader` and Jetson Multimedia API, with JetPack-specific encoder +handling for Orin and Thor. Its current input is one host-memory NV12 stream; +a camera backend is usable when it supplies that layout through CameraReader. +Device support requires that backend and compatible local dependencies. + +Audio, tactile media, other codecs, GPU frame handles and capability negotiation +need explicit extensions with their own format, clock, ownership and recovery +contracts. Opaque messages can already carry small application-defined sensor or +control records; that is not an implemented audio or tactile streaming pipeline. diff --git a/src/core/media_transport/NATIVE.md b/src/core/media_transport/NATIVE.md index feeca42d85..339ce97ef7 100644 --- a/src/core/media_transport/NATIVE.md +++ b/src/core/media_transport/NATIVE.md @@ -3,7 +3,10 @@ SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All SPDX-License-Identifier: Apache-2.0 --> -# Native video transport interface — initial milestone +# Native media transport — implementation notes + +Start with the [network interface](INTERFACE.md) and +[opaque messaging interface](messages/INTERFACE.md) for the public contracts. The C++ interface in `cpp/inc/media_transport/transport.hpp` separates Media Bridge applications from the SDK implementation. The sender owns CameraReader/NVENC; the @@ -12,7 +15,7 @@ implements transport sessions. The initial provider is `src/plugins/transport_livekit/cpp`, using the official unmodified SDK. ```text -OAK plugin → CameraReader → NVENC → Publisher interface +Camera plugin → CameraReader → NVENC → Publisher interface ↓ loaded LiveKit plugin network ↓ loaded LiveKit plugin diff --git a/src/core/media_transport/cpp/plugin.cpp b/src/core/media_transport/cpp/plugin.cpp index 741d1aef76..adefb27cd6 100644 --- a/src/core/media_transport/cpp/plugin.cpp +++ b/src/core/media_transport/cpp/plugin.cpp @@ -19,10 +19,24 @@ Plugin::Plugin(const std::string& path) const char* error = dlerror(); if (error || !entry) throw std::runtime_error("Transport plugin is missing isaac_media_transport_plugin_v2"); - const PluginApi* api = entry(); - if (!api || api->version != 2 || !api->create || !api->destroy) - throw std::runtime_error("Unsupported transport plugin ABI"); - auto* instance = api->create(); + const PluginApi* api = nullptr; + Transport* instance = nullptr; + // Destroy provider exceptions before dlclose: their what()/destructor may live in the DSO. + try + { + api = entry(); + if (!api || api->version != 2 || !api->create || !api->destroy) + throw std::runtime_error("Unsupported transport plugin ABI"); + instance = api->create(); + } + catch (const std::exception& error) + { + throw std::runtime_error(std::string("Transport plugin initialization: ") + error.what()); + } + catch (...) + { + throw std::runtime_error("Transport plugin initialization failed with a non-standard exception"); + } if (!instance) throw std::runtime_error("Transport plugin creation failed"); transport = std::shared_ptr(instance, [library, destroy = api->destroy](Transport* p) { destroy(p); }); diff --git a/src/core/media_transport/messages/INTERFACE.md b/src/core/media_transport/messages/INTERFACE.md new file mode 100644 index 0000000000..1074ca24b2 --- /dev/null +++ b/src/core/media_transport/messages/INTERFACE.md @@ -0,0 +1,76 @@ + + +# Opaque messaging interface + +Applications exchange binary records without teaching the transport their schema. +Use this for status, commands, acknowledgements or small sensor samples. The +application owns serialization, versioning, units, timestamps and command safety. +Declarations live in [messages.hpp](../cpp/inc/media_transport/messages.hpp); +creation uses the [transport interface](../INTERFACE.md). + +```text +Application encode → MessageSession.send(bytes, delivery) → provider → network +Application decode ← MessageSession.take() ← bounded inbox ← provider callback +``` + +| Class / value | Contract | +| --- | --- | +| `MessageConfig` | Explicit peer identity and topic, plus inbox capacity (default 64). | +| `MessageSession` | `send`, nonblocking `take`, `stats`, and terminal `finished`. | +| `Message` | Owned payload bytes, sender, topic and delivery mode. | +| `Delivery` | `Reliable` or `Lossy`; selects the provider's channel behavior. | +| `MessageInbox` | Thread-safe bounded FIFO for provider callbacks; application callbacks do not run on SDK threads. | +| `MessageStats` | Local `accepted`, `dropped`, `filtered` and current `queued` count. | + +## Minimal application flow + +```cpp +namespace mt = isaaccapture::media_transport; +mt::Plugin provider(absolute_library_path); +auto session = provider.messages(connection, {"peer-identity", "status/v1", 64}); +session->send({0x01, 0x00, 0xff}, mt::Delivery::Reliable); +const bool ended = session->finished(); +if (auto message = session->take()) { + decode_and_validate(message->payload); +} else if (ended) { + // No buffered message remains. +} +``` + +Use each session from one application thread. `send` is synchronous and may block +or throw; it must not retain caller storage after returning. Keep it outside +capture callbacks and hard real-time control loops. `take` transfers an owned +message out of the inbox without waiting; received bytes outlive the session. +Session ownership keeps the provider loaded. + +## Bounds and delivery semantics + +Payloads contain **1–1024 bytes**, including arbitrary zero bytes. Peer names are +1–256 bytes; topics are 1–128 bytes; neither accepts embedded NUL. Capacity is +1–1024 messages. Exact peer/topic mismatches are filtered. Full inboxes reject the +newest arrival, preserving the queued FIFO. Invalid payloads are dropped. + +`Reliable` is not durability or proof of application receipt: a peer can leave, +the session can fail, or its local inbox can overflow. `Lossy` permits loss and +has no application replay. Neither mode provides application acknowledgements, +exactly-once execution, deadlines or clock synchronization. Add sequence numbers, +freshness checks and acknowledgements to the application schema when needed. + +`accepted` counts inbox admissions; `filtered` counts identity/topic mismatches; +`dropped` counts matching invalid or overflowed messages. These are local receive +counters, not sent-message acknowledgements or network loss measurements. + +## Provider and extension boundary + +Providers map identities/topics and delivery modes to their SDK, feed bounded +owned payloads into the inbox, and report terminal session state. The LiveKit +implementation uses public data-channel APIs independently of video subscriptions. +An application can use messages with no camera or video stream. + +Larger data, continuous audio/tactile streams, multi-peer routing and schema +negotiation are not part of this contract. Extend the interface deliberately; +do not bypass bounds or split large payloads without defining reassembly, +backpressure and recovery behavior. diff --git a/tests/cpp/core/media_transport/loader/main.cpp b/tests/cpp/core/media_transport/loader/main.cpp index d9029f7d1c..d482885175 100644 --- a/tests/cpp/core/media_transport/loader/main.cpp +++ b/tests/cpp/core/media_transport/loader/main.cpp @@ -38,6 +38,28 @@ int main(int argc, char** argv) check(setenv("MOCK_BAD_ABI", "1", 1) == 0); rejects([&] { mt::Plugin invalid(argv[1]); }); unsetenv("MOCK_BAD_ABI"); + for (const char* stage : { "MOCK_THROW_ENTRY", "MOCK_THROW_CREATE" }) + { + check(setenv(stage, "1", 1) == 0); + for (const bool unknown : { false, true }) + { + if (unknown) + check(setenv("MOCK_THROW_UNKNOWN", "1", 1) == 0); + bool translated = false; + try + { + mt::Plugin invalid(argv[1]); + } + catch (const std::runtime_error& error) + { + const std::string text = error.what(); + translated = text.find(unknown ? "non-standard" : "mock provider failure") != std::string::npos; + } + check(translated); + unsetenv("MOCK_THROW_UNKNOWN"); + } + unsetenv(stage); + } std::shared_ptr messages; { mt::Plugin plugin(argv[1]); diff --git a/tests/cpp/core/media_transport/mock/plugin.cpp b/tests/cpp/core/media_transport/mock/plugin.cpp index eaf763cee0..cf2ef75480 100644 --- a/tests/cpp/core/media_transport/mock/plugin.cpp +++ b/tests/cpp/core/media_transport/mock/plugin.cpp @@ -4,6 +4,26 @@ #include #include +namespace +{ +class ProviderError final : public std::exception +{ +public: + const char* what() const noexcept override + { + return "mock provider failure"; + } +}; +void fail_if_requested(const char* stage) +{ + if (std::getenv(stage)) + { + if (std::getenv("MOCK_THROW_UNKNOWN")) + throw 42; + throw ProviderError{}; + } +} +} namespace mt = isaaccapture::media_transport; class Sub : public mt::Subscriber { @@ -73,7 +93,14 @@ class Transport : public mt::Transport }; extern "C" const mt::PluginApi* isaac_media_transport_plugin_v2() { - static mt::PluginApi api{ 2, []() -> mt::Transport* { return new Transport; }, [](mt::Transport* p) { delete p; } }; + fail_if_requested("MOCK_THROW_ENTRY"); + static mt::PluginApi api{ 2, + []() -> mt::Transport* + { + fail_if_requested("MOCK_THROW_CREATE"); + return new Transport; + }, + [](mt::Transport* p) { delete p; } }; api.version = std::getenv("MOCK_BAD_ABI") ? 99 : 2; return &api; } From 426794bb4cefcb87fc9c7601df59b39e0858ea63 Mon Sep 17 00:00:00 2001 From: Juan Sepulveda Date: Wed, 2 Dec 2026 08:27:10 -0800 Subject: [PATCH 3/3] Release provider ownership when the last session owner ends Signed-off-by: Juan Sepulveda --- src/core/media_transport/cpp/plugin.cpp | 14 ++++++++++++-- tests/cpp/core/media_transport/loader/main.cpp | 3 +++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/core/media_transport/cpp/plugin.cpp b/src/core/media_transport/cpp/plugin.cpp index adefb27cd6..296c1810d7 100644 --- a/src/core/media_transport/cpp/plugin.cpp +++ b/src/core/media_transport/cpp/plugin.cpp @@ -46,14 +46,24 @@ std::shared_ptr Plugin::messages(const Connection& c, const Mess auto object = transport->messages(c, config); if (!object) throw std::runtime_error("Transport returned no message session"); - return std::shared_ptr(object.release(), [owner = transport](MessageSession* p) { delete p; }); + return std::shared_ptr(object.release(), + [owner = transport](MessageSession* p) mutable + { + delete p; + owner.reset(); + }); } std::shared_ptr Plugin::publisher(const Connection& c, const VideoConfig& v) const { auto object = transport->publisher(c, v); if (!object) throw std::runtime_error("Transport returned no publisher"); - return std::shared_ptr(object.release(), [owner = transport](Publisher* p) { delete p; }); + return std::shared_ptr(object.release(), + [owner = transport](Publisher* p) mutable + { + delete p; + owner.reset(); + }); } namespace { diff --git a/tests/cpp/core/media_transport/loader/main.cpp b/tests/cpp/core/media_transport/loader/main.cpp index d482885175..7493e01769 100644 --- a/tests/cpp/core/media_transport/loader/main.cpp +++ b/tests/cpp/core/media_transport/loader/main.cpp @@ -69,8 +69,11 @@ int main(int argc, char** argv) check(!std::filesystem::exists(argv[2])); messages->send({ 0, 255, 42 }, mt::Delivery::Reliable); auto message = messages->take(); + std::weak_ptr observer = messages; messages.reset(); check(std::filesystem::exists(argv[2])); + check(observer.expired()); + observer.reset(); check(message && message->payload == std::vector({ 0, 255, 42 })); std::filesystem::remove(argv[2]); std::shared_ptr subscriber;