diff --git a/CMakeLists.txt b/CMakeLists.txt index 10171c609f..f566bfefef 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -78,6 +78,7 @@ option(BUILD_PLUGIN_CAMERA_OAK "Build the OAK camera plugin of the camera interf option(BUILD_PLUGIN_REMOTE_DEVICE_BRIDGE "Build the remote device bridge wire codec library (Teleop::remote_plugin_session)" ON) option(BUILD_PLUGIN_POSE_PROVIDER "Build the Pose Provider plugin, engine interface and stub adapter" OFF) option(BUILD_EXAMPLES "Build examples" ON) +option(BUILD_EXAMPLE_MEDIA_BRIDGE "Build native media bridge examples" OFF) option(BUILD_EXAMPLE_TELEOP_ROS2 "Build only the teleop_ros2 ROS 2 reference integration (e.g. for Docker)" OFF) option(BUILD_TESTING "Build unit tests" ON) option(BUILD_OVXR_CAMERA_QUADS "Build optional application-owned OVXR camera quad support" OFF) @@ -173,7 +174,7 @@ add_subdirectory(deps/cloudxr/openxr_extensions) add_subdirectory(src) # Build examples if requested (examples/CMakeLists.txt honours both options). -if(BUILD_EXAMPLES OR BUILD_EXAMPLE_TELEOP_ROS2) +if(BUILD_EXAMPLES OR BUILD_EXAMPLE_TELEOP_ROS2 OR BUILD_EXAMPLE_MEDIA_BRIDGE) add_subdirectory(examples) endif() diff --git a/deps/third_party/CMakeLists.txt b/deps/third_party/CMakeLists.txt index 76352a70c6..b3b4f15ef4 100644 --- a/deps/third_party/CMakeLists.txt +++ b/deps/third_party/CMakeLists.txt @@ -128,7 +128,13 @@ set(SPDLOG_INSTALL OFF CACHE BOOL "Skip spdlog install target" FORCE) # Set in both directions, because FORCE writes the cache: setting it only in the # ON branch left an earlier -DBUILD_PLUGIN_OAK_CAMERA=ON standing in a build # directory reconfigured with the option off. -if(BUILD_PLUGIN_OAK_CAMERA) +# The optional CameraReader backend must still configure without its SDK installed. +# Probe fmt quietly here; DepthAI's own package resolves required dependencies later. +if(BUILD_PLUGIN_CAMERA_OAK AND NOT BUILD_PLUGIN_OAK_CAMERA) + find_package(fmt CONFIG QUIET) +endif() +if(BUILD_PLUGIN_OAK_CAMERA OR (BUILD_PLUGIN_CAMERA_OAK AND fmt_FOUND)) + # Both OAK plugins must share the fmt ABI used by DepthAI. # Explicit, though spdlog would find_package(fmt) on its own: a missing fmt # should fail here, naming this as the reason, not inside spdlog's build. find_package(fmt CONFIG REQUIRED) diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index b1855c9a1d..400ee8f7d9 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -27,3 +27,7 @@ elseif(BUILD_EXAMPLE_TELEOP_ROS2) # Only the ROS 2 reference integration (e.g. for Docker). add_subdirectory(teleop_ros2) endif() + +if(BUILD_EXAMPLE_MEDIA_BRIDGE) + add_subdirectory(media_bridge) +endif() diff --git a/examples/media_bridge/AGENTS.md b/examples/media_bridge/AGENTS.md new file mode 100644 index 0000000000..31394f1a88 --- /dev/null +++ b/examples/media_bridge/AGENTS.md @@ -0,0 +1,45 @@ + + +# Media Bridge + +- Hardware test instructions must specify both computers' processes, fresh-terminal + exports, and a matched bundle/token flow. Do not require users to invent room + credentials or infer receiver/viewer commands from a sender-only smoke test. + +- Use the C++ CameraReader for discovery and frame acquisition; camera SDKs belong + in camera plugins. Do not add GStreamer to this example. +- Keep the stock LiveKit baseline free of private SDK patches. Treat compressed + reception, playout controls, and timing extensions as separate capability decisions. +- Preserve comparison builds outside the clean native review stack. Do not claim + latency equivalence from successful frame delivery alone. + +- Make the stock native test the primary documentation entry point. Label patched + reference paths explicitly and record the actual receiver and SDK used in trials. + +- Keep prepared-machine commands in one canonical guide. When changing clients, + update every linked entry point and copy the corrected docs to the client; + historical hardware-validation notes must not supply active launch commands. + +- Describe camera and client support through the required CameraReader format and + local encoder backend. Label device-specific commands as examples, not as the + scope of the transport; distinguish future modalities from implemented APIs. + +- Camera plugin build examples require BUILD_PLUGINS=ON; a backend-specific flag + does not enter src/plugins when the parent gate is disabled. + +- Provider-facing interface documentation should show the current C++ declarations + and implementation obligations; replace obsolete prototype APIs rather than + presenting diagrams or old registration code as the plugin contract. + +- When replacing a heading-adjacent document range with code, clear inherited + paragraph page breaks and verify an exported render; text readback alone + cannot catch one-code-line-per-page layout. + +- Use a persistent checkout path in operator instructions; keep clone destinations + and every fresh-terminal IC_DIR export consistent when changing that path. + +- Use explicit placeholders for site login usernames in public setup examples, + not a developer's account name; explain what readers must substitute. diff --git a/examples/media_bridge/CMakeLists.txt b/examples/media_bridge/CMakeLists.txt new file mode 100644 index 0000000000..0d1534bf8c --- /dev/null +++ b/examples/media_bridge/CMakeLists.txt @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "The media_bridge prototype requires Linux") +endif() +if(CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64|arm64") + add_subdirectory(jetson_mmapi) + add_subdirectory(sender) + set(_receiver_default OFF) +else() + set(_receiver_default ON) +endif() +option(BUILD_MEDIA_BRIDGE_RECEIVER "Build stock SDK receiver and SDL window" ${_receiver_default}) +if(BUILD_MEDIA_BRIDGE_RECEIVER) + add_subdirectory(receiver) +endif() + +add_subdirectory(messages) diff --git a/examples/media_bridge/README.md b/examples/media_bridge/README.md new file mode 100644 index 0000000000..5d848c1f47 --- /dev/null +++ b/examples/media_bridge/README.md @@ -0,0 +1,343 @@ + + +# Media Bridge + +A native C++ example: camera plugin → CameraReader → Jetson NVENC → transport +plugin → host receiver/window. Video and opaque messages use the official, +unmodified LiveKit C++ SDK. No GStreamer or Python process participates in the +media path. A small Python helper generates test credentials and server files. + +Camera backends are selected independently of the network provider. The sender +uses the common CameraReader interface, not an OAK-specific capture API. Jetson +clients include Orin and Thor with their matching JetPack/Multimedia API; the +example below uses an OAK color camera as one tested input. Other cameras need +a compatible camera plugin. Audio and tactile streaming are future extensions; +small application-defined records can already use opaque messaging. + +Initial scope: Linux, one host-memory NV12 camera stream, H.264, and a desktop +window. The receiver uses the SDK's CPU RGBA output and SDL2; this is **not** the +patched NVDEC/CUDA IPC path. Stereo, XR display, automatic application reconnect, +and clock-qualified partial photon-to-photon reports are not implemented here. +The sender preserves the camera's SDK-ready timestamp as frame metadata, but +clocks must be qualified before subtracting timestamps across computers. + +## One-time preparation + +Clone the review branch on **both computers** before following this guide: + +```bash +git clone --branch jsepulveda/media-bridge-native-example \ + https://github.com/NVIDIA/IsaacCapture.git "$HOME/IsaacTeleop" +export IC_DIR="$HOME/IsaacTeleop" +cd $IC_DIR +``` + +If that directory already contains your checkout, keep it and switch to the review +branch after saving any local changes; do not clone over it. After this stack merges, +use `main` instead. Run the host preparation on the desktop and the client preparation +on the Jetson. Use the same native revision on both computers. The **client** is the Jetson with +the camera; the **host** runs LiveKit and the desktop viewer. Set `IC_DIR` to each +site's checkout; this guide uses the persistent path `~/IsaacTeleop`. The repository +is still named IsaacCapture on GitHub. When changing checkout paths, configure +and build again at the new path rather than copying an existing CMake build +directory. Bundle transfer supplies credentials, not code or dependencies. + +Install the repository's [build prerequisites](../../CONTRIBUTING.md), and the +[official LiveKit C++ SDK 1.13.1](https://github.com/livekit/client-sdk-cpp/releases/tag/v1.13.1) +archive matching each computer's OS and architecture. Extract it outside the +checkout and set `LIVEKIT_CPP_DIR` to that directory. Build apps and providers +with the same toolchain; the experimental C++ plugin ABI is not a portable SDK ABI. + +### Host preparation + +Install SDL2, OpenSSL, curl, and Docker Engine with Compose. The setup helper uses +`uv` to resolve its own dependencies; no Python bridge package is needed. + +```bash +sudo apt-get install -y libsdl2-dev openssl curl +export IC_DIR="$HOME/IsaacTeleop" +export LIVEKIT_CPP_DIR="$HOME/media-bridge-deps/livekit-sdk-ubuntu-24.04-x64-1.13.1" +cd $IC_DIR +cmake -S . -B build-media-bridge -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_VIZ=OFF -DBUILD_EXAMPLES=OFF -DBUILD_EXAMPLE_MEDIA_BRIDGE=ON \ + -DBUILD_MEDIA_BRIDGE_RECEIVER=ON -DBUILD_TRANSPORT_LIVEKIT_NATIVE=ON \ + -DBUILD_TESTING=OFF -DBUILD_PLUGINS=OFF -DBUILD_PYTHON_BINDINGS=OFF \ + -DENABLE_CLOUDXR_BUNDLE_CHECK=OFF -DISAAC_TELEOP_PYTHON_VERSION=3.12 \ + -DLiveKit_DIR="$LIVEKIT_CPP_DIR/lib/cmake/LiveKit" +cmake --build build-media-bridge \ + --target media_bridge_receiver media_bridge_messages isaac_transport_livekit_native --parallel 4 +``` + +### Jetson client preparation + +Install Jetson Multimedia API matching JetPack, including +`/usr/src/jetson_multimedia_api`, CUDA, and the ARM64 LiveKit SDK. On Thor the +verified SDK archive is Ubuntu 24.04 ARM64; choose the matching OS archive for +other Jetsons. Run: + +```bash +export IC_DIR="$HOME/IsaacTeleop" +export LIVEKIT_CPP_DIR="$HOME/media-bridge-deps/livekit-sdk-ubuntu-24.04-arm64-1.13.1" +cd $IC_DIR +cmake -S . -B build-media-bridge -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_VIZ=OFF -DBUILD_EXAMPLES=OFF -DBUILD_EXAMPLE_MEDIA_BRIDGE=ON \ + -DBUILD_MEDIA_BRIDGE_RECEIVER=OFF -DBUILD_TRANSPORT_LIVEKIT_NATIVE=ON \ + -DBUILD_TESTING=OFF -DBUILD_PLUGINS=OFF -DBUILD_PYTHON_BINDINGS=OFF \ + -DENABLE_CLOUDXR_BUNDLE_CHECK=OFF -DISAAC_TELEOP_PYTHON_VERSION=3.12 \ + -DLiveKit_DIR="$LIVEKIT_CPP_DIR/lib/cmake/LiveKit" +cmake --build build-media-bridge \ + --target media_bridge_sender media_bridge_messages isaac_transport_livekit_native --parallel 4 +``` + +### Select a camera plugin — client only + +Select a backend that exposes a single host-memory NV12 stream through CameraReader. +Start it with its own camera configuration and use `media_bridge_sender --list` +to discover its group. Pass that group to `--group`; no host camera configuration +needs to be copied. The sender does not accept stereo gray8, GPU-only buffers or +encoded camera-plugin output yet. + +The following OAK setup is a concrete example, not a transport requirement. For +S56/Argus or another backend, use that plugin’s build/start instructions and confirm +its advertised format before testing. + +#### Example: OAK color input + +Build/install the [OAK camera plugin](../../src/plugins/camera_oak/README.md) +separately, with the **C++ DepthAI 3 SDK**. A Python `depthai` installation alone +does not provide the CMake package. Install DepthAI following its upstream build +instructions, then point `DEPTHAI_PREFIX` at its installation and +`DEPTHAI_DEPENDENCIES` at its dependency installation (including fmt/spdlog). +Use the same dependency versions that built DepthAI. + +```bash +sudo apt-get install -y libusb-1.0-0-dev libssl-dev +export DEPTHAI_PREFIX="$HOME/media-bridge-deps/depthai-install" +export DEPTHAI_DEPENDENCIES="$HOME/media-bridge-deps/depthai-build/vcpkg_installed/arm64-linux" +cd $IC_DIR +cmake -S . -B build-camera -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_VIZ=OFF -DBUILD_EXAMPLES=OFF -DBUILD_PLUGINS=ON \ + -DBUILD_PLUGIN_CAMERA_OAK=ON -DBUILD_TESTING=OFF \ + -DBUILD_PYTHON_BINDINGS=OFF -DENABLE_CLOUDXR_BUNDLE_CHECK=OFF \ + -DISAAC_TELEOP_PYTHON_VERSION=3.12 \ + -DCMAKE_PREFIX_PATH="$DEPTHAI_PREFIX;$DEPTHAI_DEPENDENCIES" +cmake --build build-camera --target camera_oak_plugin --parallel 4 +export CAMERA_PLUGIN="$IC_DIR/build-camera/src/plugins/camera_oak/app/camera_oak_plugin" +``` + +Adjust those dependency paths to your installation. If CMake says DepthAI was not +found, fix the package path before building; the camera target is skipped in that +case. Connect the OAK through USB 3 and install DepthAI's USB udev rules so your +normal user can open it. Do not run the camera plugin with sudo. + + An already working CameraReader-compatible plugin can +be reused: installing the transport does not require reinstalling DepthAI. +Set `CAMERA_PLUGIN` to its executable. The camera plugin and sender must run as +the same user. The shipped [oak-cameras.yaml](oak-cameras.yaml) selects one color +stream at 1280×720, 30 fps, in host memory. Camera configuration stays on the +client; the host learns dimensions from the video stream. + +If a configure is interrupted, repeat the entire configure command before building. +A missing target usually means the wrong checkout or missing CMake options. + +## Network setup for two computers + +### Host Site Setup + +**1. Select addresses and generate a fresh matched bundle.** Use reachable LAN/VPN +addresses; the following are examples for a direct Ethernet link. To inspect addresses: + +```bash +ip -brief -4 address +``` + +```bash +export IC_DIR="$HOME/IsaacTeleop" +export HOST_IP=192.168.90.1 +export CLIENT_IP=192.168.90.2 +export CLIENT_USER="[username_on_client]" # Replace with the client's login username +export BUNDLE="$HOME/media-bridge-livekit-$(date +%Y%m%d-%H%M%S)" +cd $IC_DIR +uv run --system-certs src/plugins/transport_livekit/tools/setup_network.py \ + --host-ip "$HOST_IP" --output "$BUNDLE" +``` + +Use uv 0.11 or newer for `--system-certs` (older versions call this option +`--native-tls`). This uses the operating system's trusted certificates, including +installed corporate CAs, when downloading dependencies from PyPI. TLS verification +remains enabled. If `SSL_CERT_FILE` or `SSL_CERT_DIR` was set for a previous LiveKit +session, clear that override in this setup terminal before running uv; a room's +CA alone cannot validate PyPI. + +Generation creates separate `host/` and `client/` folders for one room, with +video/message tokens, a CA certificate, and `connection.env`. The host folder +also holds server secrets. **Transfer only `client/`.** Tokens last 24 hours; +certificates last seven days. The room is created automatically on first join. +An existing output directory is refused to protect running sessions. + +**2. Start the server and verify signaling.** Stop an earlier test server using +its own Compose file first; two servers cannot share these ports. Docker commands +require your site's normal Docker permissions. + +```bash +docker compose -f "$BUNDLE/host/compose.yaml" up -d +curl --fail --silent --show-error --noproxy '*' --connect-timeout 5 \ + --cacert "$BUNDLE/host/ca.crt" \ + --write-out '\nLiveKit signaling HTTP status: %{http_code}\n' \ + "https://$HOST_IP:8443/" +``` + +Expect `OK` and status `200`. If startup is still in progress, retry the check. + +**3. Transfer the client bundle.** Use a fresh client destination for each room. +Save the printed paths for fresh terminals. + +```bash +export CLIENT_BUNDLE_NAME="$(basename "$BUNDLE")-client" +ssh "$CLIENT_USER@$CLIENT_IP" "umask 077; mkdir \"\$HOME/$CLIENT_BUNDLE_NAME\"" +scp -r "$BUNDLE/client/." "$CLIENT_USER@$CLIENT_IP:$CLIENT_BUNDLE_NAME/" +printf 'Host bundle: %s/host\nClient bundle: ~/%s\n' "$BUNDLE" "$CLIENT_BUNDLE_NAME" +``` + +### Firewall Setup + +For UFW-managed machines with a default allow-outgoing policy, allow these +inbound ports on the **host**, restricted to the client address: + +```bash +sudo ufw allow from "$CLIENT_IP" to any port 8443 proto tcp +sudo ufw allow from "$CLIENT_IP" to any port 7881 proto tcp +sudo ufw allow from "$CLIENT_IP" to any port 7882 proto udp +``` + +On the **client**, allow media traffic from the host to the SDK's dynamic UDP ports: + +```bash +sudo ufw allow from "$HOST_IP" proto udp +``` + +Each terminal needs the IP exports above. These commands add rules; they do not +disable or enable UFW. For another firewall or a restricted outgoing policy, ask +its administrator to allow the equivalent traffic. Docker host networking is +used; HTTP port 7880 is loopback-only and should not be opened remotely. + +The client rule allows all UDP from this host because WebRTC chooses local ports +at runtime; it is not restricted to this process. After testing, remove only the +rules you added for this test (keep any pre-existing rules): + +```bash +# Host +sudo ufw delete allow from "$CLIENT_IP" to any port 8443 proto tcp +sudo ufw delete allow from "$CLIENT_IP" to any port 7881 proto tcp +sudo ufw delete allow from "$CLIENT_IP" to any port 7882 proto udp +# Client +sudo ufw delete allow from "$HOST_IP" proto udp +``` + +### Client Site Processes + +**4. Start the camera plugin on the Jetson**, in its own terminal: + +```bash +export IC_DIR="$HOME/IsaacTeleop" +export CAMERA_PLUGIN="$IC_DIR/build-camera/src/plugins/camera_oak/app/camera_oak_plugin" +# Set CAMERA_PLUGIN to the actual executable from your camera plugin build. +export TRIAL=stock-native-1 +export LOG_DIR="$HOME/media-bridge-results/$TRIAL" +mkdir -p "$LOG_DIR" +set -o pipefail +"$CAMERA_PLUGIN" --config="$IC_DIR/examples/media_bridge/oak-cameras.yaml" \ + 2>&1 | tee "$LOG_DIR/camera.log" +``` + +**5. Start the sender**, in a second client terminal. Set `CLIENT_BUNDLE` to the +path printed by step 3 (replace the placeholder below): + +```bash +export IC_DIR="$HOME/IsaacTeleop" +export CLIENT_BUNDLE="$HOME/REPLACE_WITH_CLIENT_BUNDLE_NAME" +source "$CLIENT_BUNDLE/connection.env" +export SSL_CERT_FILE="$CLIENT_BUNDLE/ca.crt" +export TRANSPORT_PLUGIN="$IC_DIR/build-media-bridge/src/plugins/transport_livekit/cpp/libisaac_transport_livekit_native.so" +export MEDIA_BRIDGE_SENDER="$IC_DIR/build-media-bridge/examples/media_bridge/sender/media_bridge_sender" +export TRIAL=stock-native-1 +export LOG_DIR="$HOME/media-bridge-results/$TRIAL" +mkdir -p "$LOG_DIR" +"$MEDIA_BRIDGE_SENDER" --list +curl --fail --silent --show-error --noproxy '*' --connect-timeout 5 \ + --cacert "$CLIENT_BUNDLE/ca.crt" --write-out '\nHTTP status: %{http_code}\n' \ + "${LIVEKIT_URL/wss:/https:}/" +set -o pipefail +"$MEDIA_BRIDGE_SENDER" --group head --bitrate 4000000 --seconds 3600 \ + --transport-plugin "$TRANSPORT_PLUGIN" --url "$LIVEKIT_URL" \ + --token-file "$CLIENT_BUNDLE/video.token" --track cam \ + 2>&1 | tee "$LOG_DIR/sender.log" +``` + +`--list` should show `head/color`, 1280×720 at 30 fps. An empty list means no +camera endpoint is discoverable. For an isolated encoder check, run +`"$MEDIA_BRIDGE_SENDER" --group head --seconds 15 --output /tmp/media-bridge.h264`. +Do not run two senders on the same camera during a comparison. + +### Host Site Processes + +**6. Start the receiver/window**, with the host bundle from step 1: + +```bash +export IC_DIR="$HOME/IsaacTeleop" +export HOST_BUNDLE="$HOME/REPLACE_WITH_BUNDLE_NAME/host" +source "$HOST_BUNDLE/connection.env" +export SSL_CERT_FILE="$HOST_BUNDLE/ca.crt" +export TRANSPORT_PLUGIN="$IC_DIR/build-media-bridge/src/plugins/transport_livekit/cpp/libisaac_transport_livekit_native.so" +export TRIAL=stock-native-1 +export LOG_DIR="$HOME/media-bridge-results/$TRIAL" +mkdir -p "$LOG_DIR" +set -o pipefail +"$IC_DIR/build-media-bridge/examples/media_bridge/receiver/media_bridge_receiver" \ + --transport-plugin "$TRANSPORT_PLUGIN" --url "$LIVEKIT_URL" \ + --token-file "$HOST_BUNDLE/video.token" --publisher client-camera \ + --track cam --seconds 3600 2>&1 | tee "$LOG_DIR/receiver.log" +``` + +This one process receives and displays video; no separate CUDA IPC viewer is +needed. Use `--headless` for an automated delivery check. Check that received +frames and metadata counts increase, and steady frame rate approaches 30 fps. +Startup overwrites can occur; counters are not an optical latency measurement. +Press Escape or Ctrl+C to stop the window, then stop sender and camera. + +Collect client logs on the host using the **same trial name**: + +```bash +scp "$CLIENT_USER@$CLIENT_IP:media-bridge-results/$TRIAL/sender.log" "$LOG_DIR/" +scp "$CLIENT_USER@$CLIENT_IP:media-bridge-results/$TRIAL/camera.log" "$LOG_DIR/" +``` + +Use a fresh `TRIAL` for the next run; `tee` overwrites existing logs. Video capture +is optional for functional testing. For latency comparisons, keep camera, display, +resolution, bitrate and network constant; clock markers are a separate follow-up. + +## Opaque-message test + +[Run the native message example](messages/README.md) to verify application-defined +binary status/control data in both directions. This needs no camera and may run +alongside video using the separate message identities. + +## Review and extension boundaries + +The [network interface](../../src/core/media_transport/INTERFACE.md) and +[opaque messaging interface](../../src/core/media_transport/messages/INTERFACE.md) define ownership, +queues and plugin lifetimes. The [LiveKit provider](../../src/plugins/transport_livekit/README.md) +contains SDK-specific behavior and test provisioning. Camera SDKs remain in camera +plugins; the example owns CameraReader, encoding and display. OAK is an example +input, not a transport dependency. Other camera plugins must supply the supported +single-stream host NV12 layout; unsupported layouts fail explicitly. + +SDK modifications, GPU receive/IPC, immediate playout controls and clock-qualified +latency instrumentation belong on a separate optimization branch. This stock +baseline deliberately makes no claim of matching the patched path's latency. + +Encoded recordings created with `--output` are private to the current user and +must use a new filename; the sender refuses to overwrite an existing recording. diff --git a/examples/media_bridge/jetson_mmapi/CMakeLists.txt b/examples/media_bridge/jetson_mmapi/CMakeLists.txt new file mode 100644 index 0000000000..bf3293436c --- /dev/null +++ b/examples/media_bridge/jetson_mmapi/CMakeLists.txt @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +set(JETSON_MMAPI_ROOT /usr/src/jetson_multimedia_api CACHE PATH "Jetson Multimedia API") +set(_sources) +foreach(_class NvBuffer NvElement NvElementProfiler NvLogging NvV4l2Element NvV4l2ElementPlane NvVideoEncoder) + list(APPEND _sources "${JETSON_MMAPI_ROOT}/samples/common/classes/${_class}.cpp") +endforeach() +add_library(media_bridge_jetson_mmapi STATIC ${_sources}) +target_include_directories(media_bridge_jetson_mmapi SYSTEM PUBLIC "${JETSON_MMAPI_ROOT}/include") +find_library(_nvv4l2 nvv4l2 HINTS /usr/lib/aarch64-linux-gnu/nvidia /usr/lib/aarch64-linux-gnu/tegra REQUIRED) +find_library(_nvbufsurface nvbufsurface HINTS /usr/lib/aarch64-linux-gnu/nvidia /usr/lib/aarch64-linux-gnu/tegra REQUIRED) +find_package(Threads REQUIRED) +# JetPack 7 MMAPI encoder sources include CUDA headers even for the V4L2 path. +find_package(CUDAToolkit REQUIRED) +target_link_libraries(media_bridge_jetson_mmapi PRIVATE CUDA::cudart) +target_link_libraries(media_bridge_jetson_mmapi PUBLIC ${_nvv4l2} ${_nvbufsurface} Threads::Threads) +add_library(media_bridge::jetson_mmapi ALIAS media_bridge_jetson_mmapi) diff --git a/examples/media_bridge/messages/CMakeLists.txt b/examples/media_bridge/messages/CMakeLists.txt new file mode 100644 index 0000000000..8b01a40bc7 --- /dev/null +++ b/examples/media_bridge/messages/CMakeLists.txt @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +add_executable(media_bridge_messages main.cpp) +target_link_libraries(media_bridge_messages PRIVATE media_transport::native log_bridge::log_bridge_core) diff --git a/examples/media_bridge/messages/README.md b/examples/media_bridge/messages/README.md new file mode 100644 index 0000000000..6850ec1828 --- /dev/null +++ b/examples/media_bridge/messages/README.md @@ -0,0 +1,64 @@ + + +# Opaque messages + +Exchange application-defined binary status or control data without imposing a +payload schema on the transport. This connectivity example has no actuator safety, +command expiry or acknowledgement policy; those belong in the application. + +Complete the [build and network setup](../README.md) first. Camera processes are +not required. The host and client must use bundles generated together. Start both +commands within 60 seconds; each exits unsuccessfully if it receives no messages. + +## Host terminal + +Replace the bundle placeholder with your generated host path: + +```bash +export IC_DIR="$HOME/IsaacCapture" +export HOST_BUNDLE="$HOME/REPLACE_WITH_BUNDLE_NAME/host" +source "$HOST_BUNDLE/connection.env" +export SSL_CERT_FILE="$HOST_BUNDLE/ca.crt" +export TRANSPORT_PLUGIN="$IC_DIR/build-media-bridge/src/plugins/transport_livekit/cpp/libisaac_transport_livekit_native.so" +"$IC_DIR/build-media-bridge/examples/media_bridge/messages/media_bridge_messages" \ + --transport-plugin "$TRANSPORT_PLUGIN" --url "$LIVEKIT_URL" \ + --token-file "$HOST_BUNDLE/messages.token" --peer client-session \ + --topic media-bridge/demo --seconds 60 --verify-payload +``` + +## Client terminal + +Replace the bundle placeholder with the transferred client path: + +```bash +export IC_DIR="$HOME/IsaacCapture" +export CLIENT_BUNDLE="$HOME/REPLACE_WITH_CLIENT_BUNDLE_NAME" +source "$CLIENT_BUNDLE/connection.env" +export SSL_CERT_FILE="$CLIENT_BUNDLE/ca.crt" +export TRANSPORT_PLUGIN="$IC_DIR/build-media-bridge/src/plugins/transport_livekit/cpp/libisaac_transport_livekit_native.so" +"$IC_DIR/build-media-bridge/examples/media_bridge/messages/media_bridge_messages" \ + --transport-plugin "$TRANSPORT_PLUGIN" --url "$LIVEKIT_URL" \ + --token-file "$CLIENT_BUNDLE/messages.token" --peer host-session \ + --topic media-bridge/demo --seconds 60 --verify-payload +``` + +Expect `Received message: bytes=4 delivery=reliable` on both terminals and nonzero +received totals. The default payload contains binary zero and 255; verification +checks every byte. Repeat with `--delivery lossy` on both commands to exercise the +unreliable channel. For other data, supply `--payload-file FILE` (1–1024 bytes). +With `--verify-payload`, both files must match. `--interval-ms` defaults to 1000. +Tokens and payload contents are never printed. + +A session filters one exact peer and topic; there is no wildcard or broadcast. +Its bounded inbox rejects new packets when full, including reliable ones, and +reports local drops. Reliable means SDK channel delivery, not application receipt +or replay: a disconnected peer can miss messages. Sending is synchronous and can +block; do not use it in hard real-time capture/control callbacks. Terminal room +disconnection ends the test. Do not start two processes with the same identity. + +The [messaging interface](../../../src/core/media_transport/messages/INTERFACE.md) documents bounds, +threading and ownership. Message traffic does not imply synchronized clocks or +provide a latency result. diff --git a/examples/media_bridge/messages/main.cpp b/examples/media_bridge/messages/main.cpp new file mode 100644 index 0000000000..aa9110af07 --- /dev/null +++ b/examples/media_bridge/messages/main.cpp @@ -0,0 +1,173 @@ +// 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 +namespace mt = isaaccapture::media_transport; +namespace +{ +static_assert(std::atomic::is_always_lock_free, "Signal stop flag must be lock-free"); +std::atomic stopped{ false }; +void stop(int) +{ + stopped.store(true, std::memory_order_relaxed); +} +int number(const std::string& text, int maximum) +{ + int value = 0; + auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value); + if (error != std::errc{} || end != text.data() + text.size() || value < 1 || value > maximum) + throw std::invalid_argument("Numeric argument is outside its allowed range"); + return value; +} +std::string read_file(const std::string& path, std::size_t limit) +{ + std::ifstream file(path, std::ios::binary); + if (!file) + throw std::runtime_error("Cannot open input file"); + std::string data(limit + 1, '\0'); + file.read(data.data(), static_cast(data.size())); + data.resize(static_cast(file.gcount())); + if (file.bad() || data.empty() || data.size() > limit) + throw std::runtime_error("Input file is empty, unreadable, or too large"); + return data; +} +void usage() +{ + std::cout << "media_bridge_messages --transport-plugin /absolute/plugin.so --url wss://host:8443\n" + " --token-file FILE --peer ID --topic TOPIC [--payload-file FILE]\n" + " [--delivery reliable|lossy] [--seconds 30] [--interval-ms 1000] [--verify-payload]\n" + "Uses 1..1024 opaque bytes. Exit 1 if no peer messages arrive. Never prints payloads/tokens.\n"; +} +} +int main(int argc, char** argv) +{ + std::string library, url, token_file, payload_file; + mt::MessageConfig config; + auto delivery = mt::Delivery::Reliable; + int seconds = 30, interval_ms = 1000; + bool verify_payload = false; + try + { + for (int i = 1; i < argc; ++i) + { + std::string key = argv[i]; + if (key == "--help") + { + usage(); + return 0; + } + if (key == "--verify-payload") + { + verify_payload = true; + continue; + } + if (i + 1 == argc) + throw std::invalid_argument("Missing option value"); + std::string value = argv[++i]; + if (key == "--transport-plugin") + library = value; + else if (key == "--url") + url = value; + else if (key == "--token-file") + token_file = value; + else if (key == "--peer") + config.peer = value; + else if (key == "--topic") + config.topic = value; + else if (key == "--payload-file") + payload_file = value; + else if (key == "--seconds") + seconds = number(value, 3600); + else if (key == "--interval-ms") + interval_ms = number(value, 60000); + else if (key == "--delivery" && value == "reliable") + delivery = mt::Delivery::Reliable; + else if (key == "--delivery" && value == "lossy") + delivery = mt::Delivery::Lossy; + else + throw std::invalid_argument("Unknown option or invalid delivery mode"); + } + if (library.empty() || url.empty() || token_file.empty()) + throw std::invalid_argument("Transport plugin, URL and token file are required"); + mt::MessageInbox validate(config); + } + catch (const std::exception& e) + { + std::cout << "Media Bridge: " << e.what() << '\n'; + usage(); + return 2; + } + auto log = isaaccapture::Logger::get("isaaccapture.media_bridge.messages"); + try + { + std::vector payload{ 'M', 'B', 0, 255 }; + if (!payload_file.empty()) + { + const auto bytes = read_file(payload_file, mt::max_message_bytes); + payload.assign(bytes.begin(), bytes.end()); + } + mt::validate_payload(payload, delivery); + auto token = read_file(token_file, 16384); + while (!token.empty() && (token.back() == '\n' || token.back() == '\r')) + token.pop_back(); + mt::Plugin plugin(library); + auto session = plugin.messages({ url, token }, config); + std::signal(SIGINT, stop); + std::signal(SIGTERM, stop); + using Clock = std::chrono::steady_clock; + auto now = Clock::now(), next = now, report = now + std::chrono::seconds(5); + const auto end = now + std::chrono::seconds(seconds); + std::uint64_t sent = 0, received = 0; + log->info("Message session ready; payload_bytes={} delivery={}", payload.size(), + delivery == mt::Delivery::Reliable ? "reliable" : "lossy"); + while (!stopped && (now = Clock::now()) < end) + { + if (session->finished()) + throw std::runtime_error("Message session disconnected"); + if (now >= next) + { + session->send(payload, delivery); + ++sent; + next = Clock::now() + std::chrono::milliseconds(interval_ms); + } + // Limit work per tick even if a peer continuously fills the inbox. + for (std::size_t i = 0; i < config.capacity; ++i) + { + auto message = session->take(); + if (!message) + break; + if (verify_payload && message->payload != payload) + throw std::runtime_error("Peer payload differs from the expected binary payload"); + ++received; + log->info("Received message: bytes={} delivery={}", message->payload.size(), + message->delivery == mt::Delivery::Reliable ? "reliable" : "lossy"); + } + if (now >= report) + { + const auto stats = session->stats(); + log->info("Messages sent={} received={} queued={} dropped={} filtered={}", sent, received, stats.queued, + stats.dropped, stats.filtered); + report = now + std::chrono::seconds(5); + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + const auto stats = session->stats(); + log->info("Finished: sent={} received={} dropped={} filtered={}", sent, received, stats.dropped, stats.filtered); + return received ? 0 : 1; + } + catch (const std::exception& e) + { + log->error("Message test failed: {}", e.what()); + return 1; + } +} diff --git a/examples/media_bridge/oak-cameras.yaml b/examples/media_bridge/oak-cameras.yaml new file mode 100644 index 0000000000..ce7edf7095 --- /dev/null +++ b/examples/media_bridge/oak-cameras.yaml @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +cameras: + head: + backend: oak + sensor: color + width: 1280 + height: 720 + fps: 30 + memory: host diff --git a/examples/media_bridge/receiver/CMakeLists.txt b/examples/media_bridge/receiver/CMakeLists.txt new file mode 100644 index 0000000000..69497161ec --- /dev/null +++ b/examples/media_bridge/receiver/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +find_package(SDL2 REQUIRED CONFIG) +find_package(Threads REQUIRED) +add_executable(media_bridge_receiver main.cpp) +target_compile_features(media_bridge_receiver PRIVATE cxx_std_20) +target_link_libraries(media_bridge_receiver PRIVATE media_transport::native SDL2::SDL2 Threads::Threads log_bridge::log_bridge_core) diff --git a/examples/media_bridge/receiver/main.cpp b/examples/media_bridge/receiver/main.cpp new file mode 100644 index 0000000000..a139b5518a --- /dev/null +++ b/examples/media_bridge/receiver/main.cpp @@ -0,0 +1,219 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include + +namespace mt = isaaccapture::media_transport; +namespace +{ +static_assert(std::atomic::is_always_lock_free, "Signal stop flag must be lock-free"); +std::atomic stopped{ false }; +void stop(int) +{ + stopped.store(true, std::memory_order_relaxed); +} +using Clock = std::chrono::steady_clock; +class Display +{ +public: + explicit Display(bool enabled) : enabled(enabled) + { + if (enabled && SDL_Init(SDL_INIT_VIDEO) != 0) + throw std::runtime_error(SDL_GetError()); + } + ~Display() + { + if (texture) + SDL_DestroyTexture(texture); + if (renderer) + SDL_DestroyRenderer(renderer); + if (window) + SDL_DestroyWindow(window); + if (enabled) + SDL_Quit(); + } + bool closed() + { + if (!enabled) + return false; + SDL_Event event; + while (SDL_PollEvent(&event)) + if (event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) + return true; + return false; + } + void show(const mt::DecodedFrame& frame) + { + const int w = frame.width, h = frame.height; + if (w <= 0 || h <= 0 || w > 8192 || h > 8192 || !frame.pixels || + frame.byte_size != static_cast(w) * h * 4) + throw std::runtime_error("Invalid decoded RGBA frame"); + if (!enabled) + return; + if (!window) + { + window = SDL_CreateWindow("Media Bridge — stock SDK CPU-buffer receiver", SDL_WINDOWPOS_CENTERED, + SDL_WINDOWPOS_CENTERED, w, h, SDL_WINDOW_RESIZABLE); + if (!window) + throw std::runtime_error(SDL_GetError()); + renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); + if (!renderer) + throw std::runtime_error(SDL_GetError()); + } + if (w != width || h != height) + { + if (texture) + SDL_DestroyTexture(texture); + texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STREAMING, w, h); + if (!texture) + throw std::runtime_error(SDL_GetError()); + if (SDL_RenderSetLogicalSize(renderer, w, h) != 0) + throw std::runtime_error(SDL_GetError()); + width = w; + height = h; + } + if (SDL_UpdateTexture(texture, nullptr, frame.pixels.get(), w * 4) != 0 || SDL_RenderClear(renderer) != 0 || + SDL_RenderCopy(renderer, texture, nullptr, nullptr) != 0) + throw std::runtime_error(SDL_GetError()); + SDL_RenderPresent(renderer); + } + +private: + bool enabled; + SDL_Window* window = nullptr; + SDL_Renderer* renderer = nullptr; + SDL_Texture* texture = nullptr; + int width = 0, height = 0; +}; +} +int main(int argc, char** argv) +{ + try + { + std::string url, token_file, plugin_path, publisher = "client-camera", track = "cam"; + double seconds = 3600; + bool headless = false; + for (int i = 1; i < argc; ++i) + { + const std::string arg = argv[i]; + if (arg == "--help") + { + std::cout + << "media_bridge_receiver --transport-plugin /absolute/plugin.so --url wss://HOST:8443 --token-file FILE\n" + " [--publisher client-camera] [--track cam] [--seconds 3600] [--headless]\n" + "Transport-decoded CPU RGBA; integrated SDL window, no CUDA IPC.\n"; + return 0; + } + if (arg == "--headless") + { + headless = true; + continue; + } + if (++i == argc) + throw std::invalid_argument("Missing value for " + arg); + const std::string value = argv[i]; + if (arg == "--url") + url = value; + else if (arg == "--transport-plugin") + plugin_path = value; + else if (arg == "--token-file") + token_file = value; + else if (arg == "--publisher") + publisher = value; + else if (arg == "--track") + track = value; + else if (arg == "--seconds") + { + std::size_t used = 0; + seconds = std::stod(value, &used); + if (used != value.size() || !std::isfinite(seconds) || seconds <= 0 || seconds > 3600) + throw std::invalid_argument("seconds must be in (0,3600]"); + } + else + throw std::invalid_argument("Unknown argument: " + arg); + } + if (url.empty() || token_file.empty() || publisher.empty() || track.empty()) + throw std::invalid_argument("Supply URL, token file, publisher and track"); + std::ifstream input(token_file); + if (!input) + throw std::runtime_error("Cannot open token file"); + std::string token((std::istreambuf_iterator(input)), {}); + while (!token.empty() && (token.back() == '\n' || token.back() == '\r')) + token.pop_back(); + if (token.empty()) + throw std::runtime_error("Empty token file"); + std::signal(SIGINT, stop); + std::signal(SIGTERM, stop); + mt::Plugin plugin(plugin_path); + auto reader = plugin.subscriber({ url, token }, publisher, track); + Display display(!headless); + const auto logger = isaaccapture::Logger::get("isaaccapture.media_bridge.receiver"); + logger->info("Transport receive: CPU RGBA buffers; no CUDA IPC or qualified P2P timing"); + const auto start = Clock::now(); + auto report = start, last_frame = start; + std::uint64_t shown = 0, metadata_count = 0, previous = 0; + + while (!stopped && std::chrono::duration(Clock::now() - start).count() < seconds && !display.closed()) + { + const bool ended = reader->finished(); + if (auto event = reader->take()) + { + display.show(*event); + ++shown; + last_frame = Clock::now(); + if (event->frame_id && event->sender_timestamp_us) + ++metadata_count; + if (shown == 1) + logger->info( + "First frame: {}x{} sender_metadata={}", event->width, event->height, metadata_count == 1); + } + else if (ended) + { + logger->info("Selected video track ended"); + break; + } + const auto now = Clock::now(); + if (std::chrono::duration(now - last_frame).count() > 15) + throw std::runtime_error("No video frame for 15 seconds; check publisher, track and sender"); + if (now - report >= std::chrono::seconds(5)) + { + const auto counts = reader->stats(); + logger->info("frames={} interval_fps={:.1f} metadata_frames={} sdk_read={} app_overwritten={} decoder={}", + shown, (shown - previous) / std::chrono::duration(now - report).count(), + metadata_count, counts.received, counts.overwritten, counts.decoder); + report = now; + previous = shown; + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + reader.reset(); + if (!shown) + throw std::runtime_error("No video frames received"); + logger->info("Finished: frames={} metadata_frames={}", shown, metadata_count); + return 0; + } + catch (const std::exception& e) + { + std::cerr << "Media bridge receiver: " << e.what() << '\n'; + return 1; + } +} diff --git a/examples/media_bridge/sender/CMakeLists.txt b/examples/media_bridge/sender/CMakeLists.txt new file mode 100644 index 0000000000..d016811a7a --- /dev/null +++ b/examples/media_bridge/sender/CMakeLists.txt @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_executable(media_bridge_sender main.cpp jetson_encoder.cpp jetson_encoder.hpp) +target_compile_features(media_bridge_sender PRIVATE cxx_std_20) +target_link_libraries(media_bridge_sender PRIVATE camera::camera media_bridge::jetson_mmapi media_transport::native log_bridge::log_bridge_core) diff --git a/examples/media_bridge/sender/jetson_encoder.cpp b/examples/media_bridge/sender/jetson_encoder.cpp new file mode 100644 index 0000000000..3cbbdf6bfe --- /dev/null +++ b/examples/media_bridge/sender/jetson_encoder.cpp @@ -0,0 +1,195 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +#include "jetson_encoder.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +void check(int result, const char* operation) +{ + if (result < 0) + throw std::runtime_error(std::string("Jetson encoder: ") + operation + ": " + std::strerror(errno)); +} +void dequeue(NvV4l2ElementPlane& plane, v4l2_buffer& buffer, NvBuffer*& returned, const char* operation) +{ + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + // MMAPI retries EAGAIN immediately; use a time budget instead of a busy retry count. + while (plane.dqBuffer(buffer, &returned, nullptr, 0) < 0) + { + if (errno != EAGAIN || std::chrono::steady_clock::now() >= deadline) + check(-1, operation); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } +} +} +JetsonEncoder::JetsonEncoder(std::uint32_t w, std::uint32_t h, std::uint32_t fps, std::uint32_t bitrate) + : encoder(NvVideoEncoder::createVideoEncoder("media_bridge_h264", O_NONBLOCK)), width(w), height(h) +{ + if (!encoder) + throw std::runtime_error("Cannot open Jetson hardware encoder"); + check(encoder->setCapturePlaneFormat(V4L2_PIX_FMT_H264, w, h, 4 * 1024 * 1024), "H264 format"); +#ifdef V4L2_CID_MPEG_VIDEO_CUDA_MEM_TYPE + // Thor's default device allocation cannot be written with host memcpy. + if (encoder->isGPUEnabled()) + check(encoder->setCudaMemType(V4L2_CUDA_MEM_TYPE_PINNED), "host-accessible input memory"); +#endif + check(encoder->setOutputPlaneFormat(V4L2_PIX_FMT_NV12M, w, h), "NV12 input"); + check(encoder->setProfile(V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE), "baseline profile"); + check(encoder->setRateControlMode(V4L2_MPEG_VIDEO_BITRATE_MODE_CBR), "CBR"); + set_bitrate(bitrate); + check(encoder->setFrameRate(fps, 1), "frame rate"); + check(encoder->setIDRInterval(fps), "IDR interval"); + check(encoder->setIFrameInterval(fps), "I frame interval"); + check(encoder->setNumBFrames(0), "disable frame reordering"); + check(encoder->setInsertSpsPpsAtIdrEnabled(true), "SPS/PPS"); + check(encoder->output_plane.setupPlane(V4L2_MEMORY_MMAP, 2, true, false), "input buffers"); + check(encoder->capture_plane.setupPlane(V4L2_MEMORY_MMAP, 2, true, false), "encoded buffers"); + check(encoder->output_plane.setStreamStatus(true), "start input"); + check(encoder->capture_plane.setStreamStatus(true), "start output"); + for (std::uint32_t i = 0; i < encoder->capture_plane.getNumBuffers(); ++i) + { + v4l2_buffer buffer{}; + v4l2_plane planes[MAX_PLANES]{}; + buffer.index = i; + buffer.m.planes = planes; + check(encoder->capture_plane.qBuffer(buffer, nullptr), "queue encoded buffer"); + } +} +JetsonEncoder::~JetsonEncoder() +{ + if (encoder) + encoder->abort(); +} +void JetsonEncoder::set_bitrate(std::uint32_t bitrate) +{ + check(encoder->setBitrate(bitrate), "bitrate"); +} +void JetsonEncoder::copy_input(const core::camera::ImageView& image) +{ + if (image.stream->on_gpu() || image.stream->pixel_format != core::camera::PixelFormat::NV12 || + image.stream->width != width || image.stream->height != height) + throw std::runtime_error("Initial native sender requires host NV12 at the negotiated dimensions"); + auto* input = encoder->output_plane.getNthBuffer(0); + if (!input || input->n_planes != 2) + throw std::runtime_error("Unexpected encoder input plane count"); + for (std::uint32_t p = 0; p < 2; ++p) + { + const auto source = image.plane(p); + const auto source_stride = image.stream->planes[p].stride_bytes; + auto& dest = input->planes[p]; + const auto rows = p == 0 ? height : height / 2; + if (!dest.data || source_stride < width || source.size() < (rows - 1) * source_stride + width || + dest.fmt.stride < width || dest.length < rows * dest.fmt.stride) + throw std::runtime_error("Invalid NV12 plane extent"); + std::memset(dest.data, 0, dest.length); + for (std::uint32_t y = 0; y < rows; ++y) + std::memcpy(dest.data + y * dest.fmt.stride, source.data() + y * source_stride, width); + dest.bytesused = rows * dest.fmt.stride; + } +} +std::vector JetsonEncoder::encode(std::uint64_t timestamp_us, bool force_keyframe) +{ + if (force_keyframe) + { +#ifdef V4L2_CID_MPEG_VIDEO_CUDA_MEM_TYPE + if (encoder->isGPUEnabled()) + { + v4l2_ext_control control{}; + control.id = V4L2_CID_MPEG_VIDEOENC_FORCE_IDR_FRAME; + control.value = 1; + v4l2_ext_controls controls{}; + controls.ctrl_class = V4L2_CTRL_CLASS_MPEG; + controls.count = 1; + controls.controls = &control; + check(encoder->setExtControls(controls), "force GPU IDR"); + } + else +#endif + check(encoder->forceIDR(), "force IDR"); + } + v4l2_buffer input{}; + v4l2_plane input_planes[MAX_PLANES]{}; + input.m.planes = input_planes; + input.timestamp.tv_sec = timestamp_us / 1000000; + input.timestamp.tv_usec = timestamp_us % 1000000; + input.flags = V4L2_BUF_FLAG_TIMESTAMP_COPY; + auto* owned = encoder->output_plane.getNthBuffer(0); + for (std::uint32_t p = 0; p < owned->n_planes; ++p) + input_planes[p].bytesused = owned->planes[p].bytesused; + check(encoder->output_plane.qBuffer(input, nullptr), "submit input"); + NvBuffer* returned = nullptr; + dequeue(encoder->output_plane, input, returned, "reclaim input"); + v4l2_buffer output{}; + v4l2_plane output_planes[MAX_PLANES]{}; + output.m.planes = output_planes; + output.length = encoder->capture_plane.getNumPlanes(); + dequeue(encoder->capture_plane, output, returned, "read encoded frame"); + if (!returned || !output_planes[0].bytesused || output_planes[0].bytesused > returned->planes[0].length) + throw std::runtime_error("Invalid encoded frame extent"); + std::vector bytes(returned->planes[0].data, returned->planes[0].data + output_planes[0].bytesused); + check(encoder->capture_plane.qBuffer(output, nullptr), "return encoded buffer"); + // Thor may omit repeated SPS/PPS despite the control; late joiners need them with IDRs. + bool idr = false, has_sps = false, has_pps = false; + std::size_t sps_end = 0; + auto start_code = [&bytes](std::size_t i) -> std::size_t + { + if (i + 3 <= bytes.size() && bytes[i] == 0 && bytes[i + 1] == 0) + { + if (bytes[i + 2] == 1) + return 3; + if (i + 4 <= bytes.size() && bytes[i + 2] == 0 && bytes[i + 3] == 1) + return 4; + } + return 0; + }; + for (std::size_t i = 0; i < bytes.size();) + { + const auto prefix = start_code(i); + if (!prefix || i + prefix == bytes.size()) + { + ++i; + continue; + } + auto end = i + prefix + 1; + while (end < bytes.size() && !start_code(end)) + ++end; + const auto type = bytes[i + prefix] & 31; + idr |= type == 5; + if (type == 7 || type == 8) + { + auto& saved = type == 7 ? sps : pps; + saved.assign(bytes.begin() + i, bytes.begin() + end); + if (type == 7) + sps_end = end; + has_sps |= type == 7; + has_pps |= type == 8; + } + i = end; + } + if (idr && (!has_sps || !has_pps)) + { + if (sps.empty() || pps.empty()) + throw std::runtime_error("IDR frame has no cached SPS/PPS"); + if (has_sps && !has_pps) + { + // A late joiner must receive the referenced SPS before the cached PPS. + bytes.insert(bytes.begin() + sps_end, pps.begin(), pps.end()); + return bytes; + } + std::vector complete; + if (!has_sps) + complete.insert(complete.end(), sps.begin(), sps.end()); + if (!has_pps) + complete.insert(complete.end(), pps.begin(), pps.end()); + complete.insert(complete.end(), bytes.begin(), bytes.end()); + return complete; + } + return bytes; +} diff --git a/examples/media_bridge/sender/jetson_encoder.hpp b/examples/media_bridge/sender/jetson_encoder.hpp new file mode 100644 index 0000000000..c1283461a4 --- /dev/null +++ b/examples/media_bridge/sender/jetson_encoder.hpp @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +#pragma once +#include + +#include +#include +#include +#include + +class JetsonEncoder +{ +public: + JetsonEncoder(std::uint32_t width, std::uint32_t height, std::uint32_t fps, std::uint32_t bitrate); + ~JetsonEncoder(); + void copy_input(const core::camera::ImageView& image); + std::vector encode(std::uint64_t timestamp_us, bool force_keyframe); + void set_bitrate(std::uint32_t bitrate); + +private: + std::unique_ptr encoder; + std::uint32_t width, height; + std::vector sps, pps; +}; diff --git a/examples/media_bridge/sender/main.cpp b/examples/media_bridge/sender/main.cpp new file mode 100644 index 0000000000..f00d2c8c4d --- /dev/null +++ b/examples/media_bridge/sender/main.cpp @@ -0,0 +1,240 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +#include "jetson_encoder.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace mt = isaaccapture::media_transport; +namespace +{ +static_assert(std::atomic::is_always_lock_free, "Signal stop flag must be lock-free"); +std::atomic stopped{ false }; +void stop(int) +{ + stopped.store(true, std::memory_order_relaxed); +} +std::uint64_t now_ns() +{ + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); +} +bool keyframe(const std::vector& bytes) +{ + for (std::size_t i = 0; i + 4 < bytes.size(); ++i) + if (bytes[i] == 0 && bytes[i + 1] == 0 && + ((bytes[i + 2] == 1 && (bytes[i + 3] & 31) == 5) || + (bytes[i + 2] == 0 && bytes[i + 3] == 1 && (bytes[i + 4] & 31) == 5))) + return true; + return false; +} + +} +int main(int argc, char** argv) +{ + try + { + std::string group, output, url, token_file, plugin_path, track_name = "cam"; + double seconds = 15; + std::uint32_t bitrate = 4000000; + bool list = false; + for (int i = 1; i < argc; ++i) + { + const std::string arg = argv[i]; + if (arg == "--help") + { + std::cout + << "media_bridge_sender --list\n" + "media_bridge_sender --group NAME [--seconds 15] [--bitrate 4000000]\n" + " [--transport-plugin /absolute/plugin.so] [--output FILE.h264] [--url wss://HOST:8443 --token-file FILE --track cam]\n" + "Initial path: one host-memory NV12 stream, Jetson H.264, no GStreamer.\n"; + return 0; + } + if (arg == "--list") + { + list = true; + continue; + } + if (++i == argc) + throw std::invalid_argument("Missing value for " + arg); + const std::string value = argv[i]; + if (arg == "--group") + group = value; + else if (arg == "--output") + output = value; + else if (arg == "--url") + url = value; + else if (arg == "--transport-plugin") + plugin_path = value; + else if (arg == "--token-file") + token_file = value; + else if (arg == "--track") + track_name = value; + else if (arg == "--seconds") + { + std::size_t used = 0; + seconds = std::stod(value, &used); + if (used != value.size() || !std::isfinite(seconds) || seconds <= 0 || seconds > 3600) + throw std::invalid_argument("seconds must be in (0, 3600]"); + } + else if (arg == "--bitrate") + { + std::size_t used = 0; + const auto parsed = std::stoull(value, &used); + if (used != value.size() || parsed < 100000 || parsed > 100000000) + throw std::invalid_argument("bitrate must be 100000..100000000 bits/s"); + bitrate = static_cast(parsed); + } + else + throw std::invalid_argument("Unknown option: " + arg); + } + if (list) + { + for (const auto& listing : core::camera::CameraReader::list()) + { + std::cout << listing.group.id << " endpoint=" << listing.endpoint << " " << listing.unsupported << '\n'; + for (const auto& stream : listing.group.streams) + std::cout << " " << stream.id << " " << stream.width << "x" << stream.height << " " + << stream.frame_rate << " fps\n"; + } + return 0; + } + if (group.empty() || (output.empty() && url.empty()) || (url.empty() != token_file.empty())) + throw std::invalid_argument("Supply --group and --output and/or --url with --token-file"); + auto reader = core::camera::CameraReader::open(group); + const auto& streams = reader.group().streams; + if (streams.size() != 1 || streams[0].on_gpu() || streams[0].pixel_format != core::camera::PixelFormat::NV12) + throw std::runtime_error("Select a camera plugin group with one host-memory NV12 stream"); + const auto& stream = streams[0]; + if (!std::isfinite(stream.frame_rate) || stream.frame_rate < 1 || stream.frame_rate > 120 || + std::abs(std::round(stream.frame_rate) - stream.frame_rate) > .01) + throw std::runtime_error("Initial sender requires integer camera fps in 1..120"); + const auto fps = static_cast(std::round(stream.frame_rate)); + JetsonEncoder encoder(stream.width, stream.height, fps, bitrate); + std::unique_ptr plugin; + std::shared_ptr source; + if (!url.empty()) + { + std::ifstream input(token_file); + if (!input) + throw std::runtime_error("Cannot open token file"); + std::string token((std::istreambuf_iterator(input)), {}); + while (!token.empty() && (token.back() == '\n' || token.back() == '\r')) + token.pop_back(); + if (token.empty()) + throw std::runtime_error("Empty token file"); + plugin = std::make_unique(plugin_path); + source = plugin->publisher({ url, token }, { track_name, stream.width, stream.height, fps, bitrate }); + } + const auto close_file = [](std::FILE* stream) { std::fclose(stream); }; + std::unique_ptr file(nullptr, close_file); + if (!output.empty()) + { + const int fd = ::open(output.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600); + if (fd < 0) + throw std::runtime_error("Cannot create encoded output; choose a new writable path"); + file.reset(::fdopen(fd, "wb")); + if (!file) + { + ::close(fd); + throw std::runtime_error("Cannot open encoded output stream"); + } + } + std::signal(SIGINT, stop); + std::signal(SIGTERM, stop); + const auto logger = isaaccapture::Logger::get("isaaccapture.media_bridge.sender"); + const auto start = now_ns(); + auto report = start; + auto last_frame = start; + std::uint64_t count = 0, skipped = 0, bytes = 0; + std::uint32_t generation = 0; + bool first = true, force = true; + while (!stopped && (now_ns() - start) / 1e9 < seconds) + { + auto frames = reader.next(std::chrono::milliseconds(100)); + if (!frames) + { + if (now_ns() - last_frame > 5000000000ULL) + throw std::runtime_error("Camera stalled for five seconds"); + continue; + } + last_frame = now_ns(); + skipped += frames->skipped(); + force = force || first || generation != frames->generation(); + generation = frames->generation(); + first = false; + const auto timeline = frames->timeline(); + if (timeline.sdk_ready_ns <= 0 || static_cast(timeline.sdk_ready_ns) > last_frame) + throw std::runtime_error("Invalid camera SDK-ready clock"); + const auto stamp = timeline.sdk_ready_ns / 1000; + encoder.copy_input(frames->image(0)); + // Encoder owns its copy: release the camera lease before encoding or networking. + frames->release(); + if (source) + { + const auto feedback = source->feedback(); + force = force || feedback.keyframe_requested; + if (feedback.target_bitrate_bps && *feedback.target_bitrate_bps > 0) + encoder.set_bitrate(static_cast( + std::clamp(*feedback.target_bitrate_bps, 100000, bitrate))); + } + auto payload = encoder.encode(stamp, force || count % fps == 0); + force = false; + if (file) + { + if (std::fwrite(payload.data(), 1, payload.size(), file.get()) != payload.size()) + throw std::runtime_error("Encoded output write failed"); + } + bytes += payload.size(); + if (source) + { + mt::EncodedFrame frame; + frame.keyframe = keyframe(payload); + frame.timestamp_us = stamp; + frame.frame_id = static_cast(count); + frame.data = std::move(payload); + if (!source->publish(std::move(frame))) + throw std::runtime_error("Transport rejected encoded frame"); + } + ++count; + const auto now = now_ns(); + if (now - report >= 5000000000ULL) + { + logger->info("frames={} skipped={} mean_fps={:.1f} payload_bytes={}", count, skipped, + count * 1e9 / (now - start), bytes); + report = now; + } + } + if (!count) + throw std::runtime_error("No frames encoded"); + source.reset(); + plugin.reset(); + if (file) + { + if (std::fclose(file.release()) != 0) + throw std::runtime_error("Encoded output close failed"); + } + logger->info("Finished: frames={} skipped={} payload_bytes={}", count, skipped, bytes); + return 0; + } + catch (const std::exception& error) + { + std::cerr << "Media bridge: " << error.what() << '\n'; + return 1; + } +}