diff --git a/src/core/camera_ipc/README.md b/src/core/camera_ipc/README.md index f0a20e551f..215f21b51b 100644 --- a/src/core/camera_ipc/README.md +++ b/src/core/camera_ipc/README.md @@ -65,6 +65,14 @@ HostPoolView view(std::move(message.descriptors[0]), slot_count, slot_bytes); file left by a crashed process is replaced safely. Anything else found at the path is left alone. The lock file stays behind, empty. +## Where the plugin listens + +`default_endpoint_path()` is the socket path a camera plugin and its readers agree on without +being told: `$XDG_RUNTIME_DIR/isaaccapture/camera.sock`, or under `/tmp/isaaccapture-/` +when that variable is not set. A second plugin on the same machine is a named instance and +listens on `camera-.sock` beside it. The plugin makes the directory for its owner +alone and refuses one that others can enter. + ## Why a socket and shared memory, and not a messaging library Three things have to cross between the processes: the frame memory, a small event per frame diff --git a/src/core/camera_ipc/cpp/CMakeLists.txt b/src/core/camera_ipc/cpp/CMakeLists.txt index 69db298406..f3ff4e078d 100644 --- a/src/core/camera_ipc/cpp/CMakeLists.txt +++ b/src/core/camera_ipc/cpp/CMakeLists.txt @@ -7,6 +7,7 @@ cmake_minimum_required(VERSION 3.20) # memory that readers can only map read-only, and a socket that carries whole messages with # file descriptors. Linux only. add_library(camera_ipc STATIC + endpoint_path.cpp host_pool.cpp message_socket.cpp ) diff --git a/src/core/camera_ipc/cpp/endpoint_path.cpp b/src/core/camera_ipc/cpp/endpoint_path.cpp new file mode 100644 index 0000000000..d496e5e1ab --- /dev/null +++ b/src/core/camera_ipc/cpp/endpoint_path.cpp @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include "inc/camera_ipc/endpoint_path.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::camera +{ + +std::string default_endpoint_path(std::string_view instance) +{ + const auto allowed = [](unsigned char c) { return std::isalnum(c) != 0 || c == '-' || c == '_'; }; + if (!std::all_of(instance.begin(), instance.end(), allowed)) + { + throw std::invalid_argument("camera plugin instance '" + std::string(instance) + + "' may only have letters, digits, '-' and '_' in its name"); + } + const char* runtime_directory = std::getenv("XDG_RUNTIME_DIR"); + std::string path = runtime_directory != nullptr && runtime_directory[0] != '\0' ? + std::string(runtime_directory) + "/isaaccapture" : + "/tmp/isaaccapture-" + std::to_string(::geteuid()); + path += "/camera"; + if (!instance.empty()) + { + path += "-" + std::string(instance); + } + return path + ".sock"; +} + +void prepare_endpoint_directory(const std::string& endpoint_path) +{ + const std::size_t slash = endpoint_path.rfind('/'); + if (slash == std::string::npos || slash == 0) + { + return; // the current directory or the root: nothing to prepare + } + const std::string directory = endpoint_path.substr(0, slash); + if (::mkdir(directory.c_str(), S_IRWXU) != 0 && errno != EEXIST) + { + throw std::system_error(errno, std::generic_category(), "creating '" + directory + "'"); + } + // A directory somebody else made in a shared place could be used to watch or replace the + // socket file, so only one that is this user's alone will do. + struct stat entry = {}; + if (::lstat(directory.c_str(), &entry) != 0) + { + throw std::system_error(errno, std::generic_category(), "inspecting '" + directory + "'"); + } + if (!S_ISDIR(entry.st_mode) || entry.st_uid != ::geteuid() || (entry.st_mode & (S_IRWXG | S_IRWXO)) != 0) + { + throw std::system_error( + EACCES, std::generic_category(), "'" + directory + "' is not a directory that belongs to this user alone"); + } +} + +} // namespace core::camera diff --git a/src/core/camera_ipc/cpp/inc/camera_ipc/endpoint_path.hpp b/src/core/camera_ipc/cpp/inc/camera_ipc/endpoint_path.hpp new file mode 100644 index 0000000000..8788130d97 --- /dev/null +++ b/src/core/camera_ipc/cpp/inc/camera_ipc/endpoint_path.hpp @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include + +namespace core::camera +{ + +/** + * @brief Where this user's camera plugin listens when nobody says otherwise. + * + * `$XDG_RUNTIME_DIR/isaaccapture/camera.sock`, or under `/tmp/isaaccapture-/` when that + * variable is not set. A named instance, for a second plugin on the same machine, listens on + * `camera-.sock` next to it. + * + * @throws std::invalid_argument for an instance name with anything but letters, digits, '-' and '_'. + */ +std::string default_endpoint_path(std::string_view instance = {}); + +/** + * @brief Make sure the directory of an endpoint path exists and belongs to this user alone. + * Creates it with mode 0700 when it is missing. + * @throws std::system_error if it cannot be created, or exists and is not a directory this + * user owns with no access for anyone else. + */ +void prepare_endpoint_directory(const std::string& endpoint_path); + +} // namespace core::camera diff --git a/src/core/camera_reader/README.md b/src/core/camera_reader/README.md index 605857a925..6c3763e75c 100644 --- a/src/core/camera_reader/README.md +++ b/src/core/camera_reader/README.md @@ -12,7 +12,7 @@ buffers, mapped read-only; nothing is copied. ```cpp #include -CameraReader reader = CameraReader::open(endpoint, "head"); +CameraReader reader = CameraReader::open("head"); while (auto frames = reader.next(std::chrono::seconds(1))) { const ImageView left = frames->image(0); @@ -29,6 +29,8 @@ while (auto frames = reader.next(std::chrono::seconds(1))) - **`next` returns nothing on timeout** and throws `CameraDisconnected` when the plugin is gone. Opening fails with a `CameraReaderError` that says why: nothing listens on the endpoint, the group does not exist, or the subscription does not fit the pool. +- **Which plugin.** By default the reader looks for this user's plugin on its default + endpoint. A `PluginLocation` names another instance of the plugin, or a socket path. - **One reader reads one group.** For two groups, open two readers; `descriptor()` lets an application wait on several at once. - A `FrameSet` may be given back from another thread than the one that calls `next`, and diff --git a/src/core/camera_reader/cpp/camera_reader.cpp b/src/core/camera_reader/cpp/camera_reader.cpp index a09a445916..fc904c0bca 100644 --- a/src/core/camera_reader/cpp/camera_reader.cpp +++ b/src/core/camera_reader/cpp/camera_reader.cpp @@ -3,6 +3,7 @@ #include "inc/camera_reader/camera_reader.hpp" +#include #include #include #include @@ -54,16 +55,29 @@ std::optional receive(MessageSocket& socket, std::span buff } } -MessageSocket connect_to(const std::string& endpoint) +MessageSocket connect_to(const PluginLocation& plugin) { + if (!plugin.endpoint.empty() && !plugin.instance.empty()) + { + throw CameraReaderError("a camera plugin is named by its endpoint or by its instance, not both"); + } + std::string endpoint = plugin.endpoint; try { + if (endpoint.empty()) + { + endpoint = default_endpoint_path(plugin.instance); + } return MessageSocket::connect(endpoint); } catch (const std::system_error& error) { throw CameraReaderError("no camera plugin answers on '" + endpoint + "': " + error.code().message()); } + catch (const std::invalid_argument& error) + { + throw CameraReaderError(error.what()); + } } // Says hello and returns what the plugin publishes. @@ -246,17 +260,17 @@ void FrameSet::release() noexcept } } -std::vector CameraReader::list(const std::string& endpoint) +std::vector CameraReader::list(const PluginLocation& plugin) { - MessageSocket socket = connect_to(endpoint); + MessageSocket socket = connect_to(plugin); WireEncoder encoder; std::vector buffer(MAX_WIRE_MESSAGE_BYTES); return greet(socket, encoder, buffer); } -CameraReader CameraReader::open(const std::string& endpoint, const std::string& group, const ReaderOptions& options) +CameraReader CameraReader::open(const std::string& group, const ReaderOptions& options, const PluginLocation& plugin) { - auto state = std::make_shared(connect_to(endpoint)); + auto state = std::make_shared(connect_to(plugin)); WireEncoder encoder; greet(state->socket, encoder, state->buffer); diff --git a/src/core/camera_reader/cpp/inc/camera_reader/camera_reader.hpp b/src/core/camera_reader/cpp/inc/camera_reader/camera_reader.hpp index 0920638a28..d05ef16de4 100644 --- a/src/core/camera_reader/cpp/inc/camera_reader/camera_reader.hpp +++ b/src/core/camera_reader/cpp/inc/camera_reader/camera_reader.hpp @@ -42,6 +42,13 @@ class CameraDisconnected : public CameraReaderError using CameraReaderError::CameraReaderError; }; +// Which camera plugin to read from. Left empty, it is this user's plugin on this machine. +struct PluginLocation +{ + std::string endpoint; // a socket path; empty for the default endpoint of `instance` + std::string instance; // a named plugin instance; empty for the default one +}; + /** * @brief One image of a frame set. The memory is the plugin's pool, mapped read-only, and * stays as it is for as long as the FrameSet the view came from is held. @@ -122,7 +129,7 @@ class FrameSet * @brief Reads one group of cameras from the camera plugin. * * @code - * CameraReader reader = CameraReader::open(endpoint, "head"); + * CameraReader reader = CameraReader::open("head"); * while (auto frames = reader.next(std::chrono::seconds(1))) * { * std::span left = frames->image(0).data; @@ -133,17 +140,19 @@ class CameraReader { public: /** - * @brief What the plugin behind `endpoint` publishes. - * @throws CameraReaderError if nothing listens there or the plugin refuses this reader. + * @brief What a camera plugin publishes. + * @throws CameraReaderError if no plugin answers or the plugin refuses this reader. */ - static std::vector list(const std::string& endpoint); + static std::vector list(const PluginLocation& plugin = {}); /** * @brief Subscribe to one group. A reader for a second group is a second CameraReader. - * @throws CameraReaderError if nothing listens on the endpoint or the plugin refuses the - * subscription; the message says why. + * @throws CameraReaderError if no plugin answers or the plugin refuses the subscription; + * the message says why. */ - static CameraReader open(const std::string& endpoint, const std::string& group, const ReaderOptions& options = {}); + static CameraReader open(const std::string& group, + const ReaderOptions& options = {}, + const PluginLocation& plugin = {}); CameraReader(CameraReader&& other) noexcept; CameraReader& operator=(CameraReader&& other) noexcept; diff --git a/src/plugins/camera/README.md b/src/plugins/camera/README.md index 64a5ef8514..798b617f49 100644 --- a/src/plugins/camera/README.md +++ b/src/plugins/camera/README.md @@ -9,29 +9,53 @@ One process that owns the cameras and serves their frames to any number of reade processes. Viewers, encoders and recorders read the plugin's buffers in place through [`camera_reader`](../../core/camera_reader); none of them links a camera SDK. +```yaml +# ~/.config/isaaccapture/cameras.yaml +cameras: + head: + backend: synthetic +``` + ```bash -camera_plugin --endpoint=/tmp/cameras.sock --camera=head:synthetic +camera_plugin ``` ```cpp -CameraReader reader = CameraReader::open("/tmp/cameras.sock", "head"); +CameraReader reader = CameraReader::open("head"); while (auto frames = reader.next(std::chrono::seconds(1))) { const ImageView left = frames->image(0); } ``` +Neither side is told where the other is: the plugin listens on this user's default endpoint +and readers look there. + ## Running it -| Argument | Meaning | -|---|---| -| `--endpoint=PATH` | The socket file readers connect to. Only one plugin serves a path at a time. | -| `--camera=ID:BACKEND[:KEY=VALUE,...]` | One camera: the id readers ask for, the backend that opens it, and that backend's options. Repeat it for each camera. | -| `--slots=N` | Frames kept per stream, 8 by default. A pool holds the newest frame set, one slot for the camera to write ahead, and the windows of all readers; a reader that does not fit is refused with the numbers. | -| `--list-backends` | Print the backends this build has. | +**Which cameras.** A camera has an id that readers ask for, a backend that opens it, and that +backend's options. The plugin takes them from, in this order: + +1. `--camera=ID:BACKEND[:KEY=VALUE,...]` on the command line, once per camera; +2. `--config=FILE`, or without it `$XDG_CONFIG_HOME/isaaccapture/cameras.yaml` + (`~/.config/isaaccapture/cameras.yaml`) when that file exists. A camera takes three lines: + its id, `backend:`, and any option of that backend as `name: value`. `slots:` at the top + level sets the pool size; +3. otherwise, or with `--auto`, every camera the backends of this build find plugged in. + +**Where it listens.** By default on `$XDG_RUNTIME_DIR/isaaccapture/camera.sock`. A second +plugin on the same machine runs as a named instance, `--instance=NAME`, on its own endpoint, +and readers name the same instance. `--endpoint=PATH` sets the socket file outright. Only one +plugin serves an endpoint at a time. + +**Pool size.** `--slots=N`, 8 by default, is the number of frames kept per stream. A pool +holds the newest frame set, one slot for the camera to write ahead, and the windows of all +readers; a reader that does not fit is refused with the numbers. A reader that wants every +frame in order counts its window twice, because the frames waiting for it are kept as well. -A misspelt argument or option is an error, not something ignored. `SIGINT` and `SIGTERM` stop -the plugin cleanly; readers see their connection close. +A misspelt argument, option or setting is an error, not something ignored. `SIGINT` and +`SIGTERM` stop the plugin cleanly; readers see their connection close. `--list-backends` +prints the backends of the build. Every ten seconds the plugin logs, per camera, how many frame sets it published. It warns when a camera had to drop frame sets because its pool was full, or when a reader did not take @@ -43,7 +67,7 @@ Every frame set carries the times it passed each step, on the host's monotonic c `camera_bench` reads a group like any other reader and prints them: ```text -$ camera_bench --endpoint=/tmp/cameras.sock --group=head --frames=600 +$ camera_bench --group=head --frames=600 head: 2 stream(s) head/left 1280x720 bgra8, 60.00 fps, 8 slots of 3686400 bytes head/right 1280x720 bgra8, 60.00 fps, 8 slots of 3686400 bytes diff --git a/src/plugins/camera/app/CMakeLists.txt b/src/plugins/camera/app/CMakeLists.txt index cb767f7074..c46ec1d5e6 100644 --- a/src/plugins/camera/app/CMakeLists.txt +++ b/src/plugins/camera/app/CMakeLists.txt @@ -10,6 +10,7 @@ add_executable(camera_plugin target_link_libraries(camera_plugin PRIVATE camera::plugin_core camera::plugin_backends + camera::camera_ipc log_bridge::log_bridge_core Threads::Threads ) diff --git a/src/plugins/camera/app/main.cpp b/src/plugins/camera/app/main.cpp index 353369730c..3eec4de0fb 100644 --- a/src/plugins/camera/app/main.cpp +++ b/src/plugins/camera/app/main.cpp @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +#include #include +#include #include #include #include @@ -12,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -25,14 +28,20 @@ namespace { constexpr std::string_view USAGE = - "Usage: camera_plugin --endpoint=PATH --camera=ID:BACKEND[:KEY=VALUE[,KEY=VALUE]...] [--camera=...]\n" - " [--slots=N]\n" + "Usage: camera_plugin [--config=FILE | --camera=ID:BACKEND[:KEY=VALUE,...] ... | --auto]\n" + " [--endpoint=PATH | --instance=NAME] [--slots=N]\n" " camera_plugin --list-backends\n" "\n" - "Owns the cameras it is given and serves their frames to readers that connect to PATH.\n" - " --endpoint=PATH the socket file readers connect to\n" + "Owns cameras and serves their frames to readers in other processes. Without arguments it\n" + "serves the cameras of its configuration file on this user's default endpoint; when there is\n" + "no such file, every camera its backends find plugged in.\n" + " --config=FILE the cameras to serve (default: $XDG_CONFIG_HOME/isaaccapture/cameras.yaml,\n" + " or ~/.config/isaaccapture/cameras.yaml)\n" " --camera=... one camera: the id readers ask for, the backend that opens it, and the\n" " backend's options; give it once per camera\n" + " --auto serve every camera the backends find plugged in, whatever a file says\n" + " --instance=NAME run as a named instance beside the default one, on its own endpoint\n" + " --endpoint=PATH the socket file readers connect to, instead of a default endpoint\n" " --slots=N frames kept per stream (default 8); a reader with a larger window needs more\n" " --list-backends print the backends this build has and exit\n"; @@ -52,8 +61,11 @@ std::optional flag_value(std::string_view arg, std::string_vie struct Arguments { std::string endpoint; + std::string instance; + std::string config_file; std::vector cameras; - std::uint32_t slots = DEFAULT_SLOT_COUNT; + std::optional slots; + bool automatic = false; bool list_backends = false; bool help = false; }; @@ -72,21 +84,35 @@ Arguments parse(int argc, char** argv) { arguments.list_backends = true; } + else if (arg == "--auto") + { + arguments.automatic = true; + } else if (const auto endpoint = flag_value(arg, "--endpoint")) { arguments.endpoint = *endpoint; } + else if (const auto instance = flag_value(arg, "--instance")) + { + arguments.instance = *instance; + } + else if (const auto config = flag_value(arg, "--config")) + { + arguments.config_file = *config; + } else if (const auto camera = flag_value(arg, "--camera")) { arguments.cameras.push_back(parse_camera_argument(*camera)); } else if (const auto slots = flag_value(arg, "--slots")) { - const auto [end, error] = std::from_chars(slots->data(), slots->data() + slots->size(), arguments.slots); + std::uint32_t count = 0; + const auto [end, error] = std::from_chars(slots->data(), slots->data() + slots->size(), count); if (error != std::errc() || end != slots->data() + slots->size()) { throw std::invalid_argument("--slots takes a whole number, not '" + std::string(*slots) + "'"); } + arguments.slots = count; } else if (flag_value(arg, "--plugin-root-id")) { @@ -97,20 +123,52 @@ Arguments parse(int argc, char** argv) throw std::invalid_argument("unknown argument '" + std::string(arg) + "'"); } } - if (!arguments.help && !arguments.list_backends) + if (!arguments.endpoint.empty() && !arguments.instance.empty()) { - if (arguments.endpoint.empty()) - { - throw std::invalid_argument("--endpoint is required"); - } - if (arguments.cameras.empty()) - { - throw std::invalid_argument("at least one --camera is required"); - } + throw std::invalid_argument("--endpoint and --instance both say where to listen; give one"); + } + const int sources = + (arguments.config_file.empty() ? 0 : 1) + (arguments.cameras.empty() ? 0 : 1) + (arguments.automatic ? 1 : 0); + if (sources > 1) + { + throw std::invalid_argument("--config, --camera and --auto each say which cameras to serve; give one kind"); } return arguments; } +// The cameras to serve: from the command line, a file, or what is plugged in. +PluginConfig cameras_to_serve(const Arguments& arguments, const std::vector& backends, spdlog::logger& logger) +{ + PluginConfig config; + std::string source = "the command line"; + const std::string default_file = default_config_path(); + if (!arguments.cameras.empty()) + { + config.cameras = arguments.cameras; + } + else if (!arguments.config_file.empty() || (!arguments.automatic && std::filesystem::exists(default_file))) + { + source = arguments.config_file.empty() ? default_file : arguments.config_file; + config = load_config_file(source); + } + else + { + source = "the cameras found plugged in"; + config.cameras = discover_cameras(backends); + } + if (arguments.slots) + { + config.slot_count = *arguments.slots; + } + if (config.cameras.empty()) + { + throw std::invalid_argument("there is no camera to serve in " + source + ". Name cameras in '" + default_file + + "' or with --camera, or plug in a camera one of this build's backends can find"); + } + logger.info("serving {} camera(s) from {}", config.cameras.size(), source); + return config; +} + } // namespace int main(int argc, char** argv) @@ -144,20 +202,28 @@ int main(int argc, char** argv) const auto logger = isaaccapture::Logger::get("isaaccapture.plugins.camera.main"); try { - // Every thread started below inherits this mask, so the signals wait for sigwait() here. + // Every thread started below inherits this mask, so the signals wait for the loop here. sigset_t stop_signals; sigemptyset(&stop_signals); sigaddset(&stop_signals, SIGINT); sigaddset(&stop_signals, SIGTERM); pthread_sigmask(SIG_BLOCK, &stop_signals, nullptr); - CameraHost host(arguments.endpoint); - for (const CameraConfig& camera : arguments.cameras) + const PluginConfig config = cameras_to_serve(arguments, backends, *logger); + std::string endpoint = arguments.endpoint; + if (endpoint.empty()) + { + endpoint = core::camera::default_endpoint_path(arguments.instance); + core::camera::prepare_endpoint_directory(endpoint); + } + + CameraHost host(endpoint); + for (const CameraConfig& camera : config.cameras) { - host.add_camera(find_backend(backends, camera.backend).open(camera), arguments.slots); + host.add_camera(find_backend(backends, camera.backend).open(camera), config.slot_count); } host.start(); - logger->info("camera plugin serves {} camera(s) on '{}'", host.camera_count(), arguments.endpoint); + logger->info("camera plugin serves {} camera(s) on '{}'", host.camera_count(), endpoint); // Sleeps until a signal says stop, waking now and then to log what the cameras did. const timespec activity_interval = { ACTIVITY_LOG_SECONDS, 0 }; diff --git a/src/plugins/camera/bench/main.cpp b/src/plugins/camera/bench/main.cpp index 211d0c76d8..460801382a 100644 --- a/src/plugins/camera/bench/main.cpp +++ b/src/plugins/camera/bench/main.cpp @@ -24,11 +24,13 @@ namespace { constexpr std::string_view USAGE = - "Usage: camera_bench --endpoint=PATH [--group=ID] [--frames=N] [--window=N] [--order=newest|in_order]\n" - " [--check-synthetic]\n" + "Usage: camera_bench [--group=ID] [--frames=N] [--window=N] [--order=newest|in_order] [--check-synthetic]\n" + " [--endpoint=PATH | --instance=NAME]\n" "\n" "Reads one group from a running camera plugin and prints where each frame set spent its time.\n" "Without --group it lists what the plugin publishes.\n" + " --endpoint=PATH the plugin's socket file, instead of this user's default endpoint\n" + " --instance=NAME a named plugin instance, instead of the default one\n" " --frames=N frame sets to read (default 300)\n" " --window=N frame sets held for this reader at a time (default 1)\n" " --order=... newest skips to the latest frame set, in_order reads every one\n" @@ -60,7 +62,7 @@ std::uint32_t number_of(std::string_view flag, std::string_view text) struct Arguments { - std::string endpoint; + PluginLocation plugin; std::string group; std::uint32_t frames = 300; ReaderOptions options; @@ -84,7 +86,11 @@ Arguments parse(int argc, char** argv) } else if (const auto endpoint = flag_value(arg, "--endpoint")) { - arguments.endpoint = *endpoint; + arguments.plugin.endpoint = *endpoint; + } + else if (const auto instance = flag_value(arg, "--instance")) + { + arguments.plugin.instance = *instance; } else if (const auto group = flag_value(arg, "--group")) { @@ -111,9 +117,9 @@ Arguments parse(int argc, char** argv) throw std::invalid_argument("unknown argument '" + std::string(arg) + "'"); } } - if (!arguments.help && arguments.endpoint.empty()) + if (!arguments.plugin.endpoint.empty() && !arguments.plugin.instance.empty()) { - throw std::invalid_argument("--endpoint is required"); + throw std::invalid_argument("--endpoint and --instance both say which plugin to read from; give one"); } return arguments; } @@ -202,14 +208,14 @@ int run(const Arguments& arguments) { if (arguments.group.empty()) { - for (const GroupDescription& group : CameraReader::list(arguments.endpoint)) + for (const GroupDescription& group : CameraReader::list(arguments.plugin)) { print_group(group); } return 0; } - CameraReader reader = CameraReader::open(arguments.endpoint, arguments.group, arguments.options); + CameraReader reader = CameraReader::open(arguments.group, arguments.options, arguments.plugin); print_group(reader.group()); std::array stages = { { { "capture -> sdk ready", {} }, diff --git a/src/plugins/camera/core/CMakeLists.txt b/src/plugins/camera/core/CMakeLists.txt index c84fda947e..51faedf95a 100644 --- a/src/plugins/camera/core/CMakeLists.txt +++ b/src/plugins/camera/core/CMakeLists.txt @@ -7,6 +7,7 @@ find_package(Threads REQUIRED) # them all behind one endpoint. add_library(camera_plugin_core STATIC camera_host.cpp + config.cpp options.cpp ) @@ -21,6 +22,7 @@ target_link_libraries(camera_plugin_core camera::camera_endpoint camera::camera_ipc log_bridge::log_bridge_core + yaml-cpp::yaml-cpp Threads::Threads ) diff --git a/src/plugins/camera/core/config.cpp b/src/plugins/camera/core/config.cpp new file mode 100644 index 0000000000..68700914ac --- /dev/null +++ b/src/plugins/camera/core/config.cpp @@ -0,0 +1,141 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include "inc/camera_plugin/config.hpp" + +#include +#include + +#include + +namespace plugins::camera +{ + +namespace +{ + +[[noreturn]] void fail(const std::string& path, const YAML::Mark& mark, const std::string& what) +{ + const std::string line = mark.is_null() ? "" : ":" + std::to_string(mark.line + 1); + throw std::invalid_argument(path + line + ": " + what); +} + +CameraConfig read_camera(const std::string& path, const YAML::Node& id, const YAML::Node& settings) +{ + if (!id.IsScalar() || id.Scalar().empty()) + { + fail(path, id.Mark(), "a camera needs an id"); + } + CameraConfig camera; + camera.id = id.Scalar(); + if (!settings.IsMap()) + { + fail(path, settings.Mark(), "camera '" + camera.id + "' needs a backend, as in `backend: synthetic`"); + } + for (const auto& setting : settings) + { + if (!setting.first.IsScalar() || !setting.second.IsScalar()) + { + fail(path, setting.first.Mark(), "camera '" + camera.id + "' takes settings of the form `name: value`"); + } + if (setting.first.Scalar() == "backend") + { + camera.backend = setting.second.Scalar(); + } + else + { + camera.options[setting.first.Scalar()] = setting.second.Scalar(); + } + } + if (camera.backend.empty()) + { + fail(path, settings.Mark(), "camera '" + camera.id + "' needs a backend, as in `backend: synthetic`"); + } + return camera; +} + +} // namespace + +PluginConfig load_config_file(const std::string& path) +{ + YAML::Node root; + try + { + root = YAML::LoadFile(path); + } + catch (const YAML::BadFile&) + { + throw std::invalid_argument(path + ": the configuration file cannot be read"); + } + catch (const YAML::ParserException& error) + { + fail(path, error.mark, "not valid YAML: " + error.msg); + } + if (!root.IsMap()) + { + fail(path, root.Mark(), "a configuration starts with `cameras:`"); + } + + PluginConfig config; + for (const auto& entry : root) + { + const std::string key = entry.first.IsScalar() ? entry.first.Scalar() : ""; + if (key == "cameras") + { + if (!entry.second.IsMap()) + { + fail(path, entry.second.Mark(), "`cameras:` lists cameras by id, each with a backend"); + } + for (const auto& camera : entry.second) + { + config.cameras.push_back(read_camera(path, camera.first, camera.second)); + } + } + else if (key == "slots") + { + try + { + config.slot_count = entry.second.as(); + } + catch (const YAML::Exception&) + { + fail(path, entry.second.Mark(), "`slots:` takes a whole number"); + } + } + else + { + fail(path, entry.first.Mark(), + "there is no setting '" + key + "'; a configuration has `cameras:` and `slots:`"); + } + } + return config; +} + +std::string default_config_path() +{ + const char* config_home = std::getenv("XDG_CONFIG_HOME"); + if (config_home != nullptr && config_home[0] != '\0') + { + return std::string(config_home) + "/isaaccapture/cameras.yaml"; + } + const char* home = std::getenv("HOME"); + return std::string(home != nullptr ? home : "") + "/.config/isaaccapture/cameras.yaml"; +} + +std::vector discover_cameras(std::span backends) +{ + std::vector cameras; + for (const Backend& backend : backends) + { + if (backend.discover) + { + for (CameraConfig& camera : backend.discover()) + { + cameras.push_back(std::move(camera)); + } + } + } + return cameras; +} + +} // namespace plugins::camera diff --git a/src/plugins/camera/core/inc/camera_plugin/camera_source.hpp b/src/plugins/camera/core/inc/camera_plugin/camera_source.hpp index 8ea82cf085..9c728884f2 100644 --- a/src/plugins/camera/core/inc/camera_plugin/camera_source.hpp +++ b/src/plugins/camera/core/inc/camera_plugin/camera_source.hpp @@ -13,6 +13,7 @@ #include #include #include +#include namespace plugins::camera { @@ -90,6 +91,10 @@ struct Backend // Opens one camera. Throws std::invalid_argument for options the backend does not accept. std::function(const CameraConfig&)> open; + + // The cameras of this backend that are plugged in, each ready to be opened. Left empty by + // a backend that has nothing to look for. + std::function()> discover = {}; }; } // namespace plugins::camera diff --git a/src/plugins/camera/core/inc/camera_plugin/config.hpp b/src/plugins/camera/core/inc/camera_plugin/config.hpp new file mode 100644 index 0000000000..6897e15c4d --- /dev/null +++ b/src/plugins/camera/core/inc/camera_plugin/config.hpp @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "camera_host.hpp" +#include "camera_source.hpp" + +#include +#include +#include +#include + +namespace plugins::camera +{ + +// The cameras a plugin is to serve and the size of their pools. +struct PluginConfig +{ + std::vector cameras; + std::uint32_t slot_count = DEFAULT_SLOT_COUNT; +}; + +/** + * @brief Read a configuration file. A camera takes three lines: + * + * @code{.yaml} + * cameras: + * head: + * backend: synthetic + * width: 1920 # anything but `backend` is an option of that backend + * slots: 8 # optional + * @endcode + * + * @throws std::invalid_argument naming the file and the line that cannot be used. + */ +PluginConfig load_config_file(const std::string& path); + +// Where a plugin looks for its configuration when it is not told: +// $XDG_CONFIG_HOME/isaaccapture/cameras.yaml, or ~/.config/isaaccapture/cameras.yaml. +std::string default_config_path(); + +// Every camera that the backends able to look for cameras find plugged in. +std::vector discover_cameras(std::span backends); + +} // namespace plugins::camera diff --git a/tests/cpp/core/camera_ipc/CMakeLists.txt b/tests/cpp/core/camera_ipc/CMakeLists.txt index ea7c1cacd4..20a10da0d7 100644 --- a/tests/cpp/core/camera_ipc/CMakeLists.txt +++ b/tests/cpp/core/camera_ipc/CMakeLists.txt @@ -6,6 +6,7 @@ cmake_minimum_required(VERSION 3.20) find_package(Threads REQUIRED) add_executable(camera_ipc_tests + test_endpoint_path.cpp test_host_pool.cpp test_message_socket.cpp ) diff --git a/tests/cpp/core/camera_ipc/test_endpoint_path.cpp b/tests/cpp/core/camera_ipc/test_endpoint_path.cpp new file mode 100644 index 0000000000..b14a475e9a --- /dev/null +++ b/tests/cpp/core/camera_ipc/test_endpoint_path.cpp @@ -0,0 +1,121 @@ +// 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 + +using namespace core::camera; + +namespace +{ + +// Sets an environment variable for one test and puts back what was there. +class ScopedEnvironment +{ +public: + ScopedEnvironment(const char* name, const char* value) : m_name(name) + { + if (const char* previous = std::getenv(name)) + { + m_previous = previous; + } + if (value != nullptr) + { + ::setenv(name, value, 1); + } + else + { + ::unsetenv(name); + } + } + + ~ScopedEnvironment() + { + if (m_previous) + { + ::setenv(m_name, m_previous->c_str(), 1); + } + else + { + ::unsetenv(m_name); + } + } + +private: + const char* m_name; + std::optional m_previous; +}; + +class TemporaryDirectory +{ +public: + TemporaryDirectory() + { + std::string pattern = (std::filesystem::temp_directory_path() / "camera_path_XXXXXX").string(); + REQUIRE(::mkdtemp(pattern.data()) != nullptr); + path = pattern; + } + + ~TemporaryDirectory() + { + std::error_code ignored; + std::filesystem::remove_all(path, ignored); + } + + std::filesystem::path path; +}; + +} // namespace + +TEST_CASE("the default endpoint is in the user's runtime directory", "[unit][camera_ipc][endpoint_path]") +{ + { + const ScopedEnvironment runtime("XDG_RUNTIME_DIR", "/run/user/1234"); + REQUIRE(default_endpoint_path() == "/run/user/1234/isaaccapture/camera.sock"); + REQUIRE(default_endpoint_path("wrist_2") == "/run/user/1234/isaaccapture/camera-wrist_2.sock"); + } + { + const ScopedEnvironment runtime("XDG_RUNTIME_DIR", nullptr); + const std::string user = std::to_string(::geteuid()); + REQUIRE(default_endpoint_path() == "/tmp/isaaccapture-" + user + "/camera.sock"); + REQUIRE(default_endpoint_path("b") == "/tmp/isaaccapture-" + user + "/camera-b.sock"); + } + // An instance name becomes part of a file name, so it cannot carry a path. + REQUIRE_THROWS_AS(default_endpoint_path("../other"), std::invalid_argument); + REQUIRE_THROWS_AS(default_endpoint_path("a b"), std::invalid_argument); +} + +TEST_CASE("an endpoint's directory is made for its owner alone", "[unit][camera_ipc][endpoint_path]") +{ + TemporaryDirectory directory; + const std::filesystem::path made = directory.path / "isaaccapture"; + const std::string endpoint = (made / "camera.sock").string(); + + prepare_endpoint_directory(endpoint); + REQUIRE(std::filesystem::is_directory(made)); + REQUIRE(std::filesystem::status(made).permissions() == std::filesystem::perms::owner_all); + prepare_endpoint_directory(endpoint); // already there and fine + + // One that others can enter is refused rather than used. + REQUIRE(::chmod(made.c_str(), 0755) == 0); + REQUIRE_THROWS_AS(prepare_endpoint_directory(endpoint), std::system_error); + + // So is something that is not a directory, and a directory that cannot be made. + std::filesystem::remove(made); + REQUIRE(::symlink(directory.path.c_str(), made.c_str()) == 0); + REQUIRE_THROWS_AS(prepare_endpoint_directory(endpoint), std::system_error); + REQUIRE_THROWS_AS(prepare_endpoint_directory((directory.path / "missing" / "deeper" / "camera.sock").string()), + std::system_error); + + // A bare file name is in the current directory, which is left as it is. + REQUIRE_NOTHROW(prepare_endpoint_directory("camera.sock")); +} diff --git a/tests/cpp/core/camera_reader/test_camera_reader.cpp b/tests/cpp/core/camera_reader/test_camera_reader.cpp index 34965d34e6..e8b541e8ac 100644 --- a/tests/cpp/core/camera_reader/test_camera_reader.cpp +++ b/tests/cpp/core/camera_reader/test_camera_reader.cpp @@ -130,7 +130,7 @@ std::byte first_pixel(const FrameSet& frames, std::size_t stream) TEST_CASE("a reader lists what a plugin publishes", "[unit][camera_reader]") { Served served; - const std::vector groups = CameraReader::list(served.endpoint_path); + const std::vector groups = CameraReader::list({ .endpoint = served.endpoint_path }); REQUIRE(groups.size() == 1); REQUIRE(groups[0].id == "head"); REQUIRE(groups[0].streams.size() == 2); @@ -140,7 +140,7 @@ TEST_CASE("a reader lists what a plugin publishes", "[unit][camera_reader]") TEST_CASE("a reader gets each frame set with its pixels and what is known about it", "[unit][camera_reader]") { Served served; - CameraReader reader = CameraReader::open(served.endpoint_path, "head"); + CameraReader reader = CameraReader::open("head", {}, { .endpoint = served.endpoint_path }); REQUIRE(reader.group().id == "head"); REQUIRE(reader.group().streams.size() == 2); REQUIRE(reader.descriptor() >= 0); @@ -175,7 +175,7 @@ TEST_CASE("a reader gets each frame set with its pixels and what is known about TEST_CASE("a held frame set is not rewritten and the next one is the newest", "[unit][camera_reader]") { Served served; - CameraReader reader = CameraReader::open(served.endpoint_path, "head"); + CameraReader reader = CameraReader::open("head", {}, { .endpoint = served.endpoint_path }); served.publish(1); std::optional held = reader.next(2s); @@ -207,7 +207,7 @@ TEST_CASE("a held frame set is not rewritten and the next one is the newest", "[ TEST_CASE("an in-order reader gets every frame set", "[unit][camera_reader]") { Served served; - CameraReader reader = CameraReader::open(served.endpoint_path, "head", { .window = 3 }); + CameraReader reader = CameraReader::open("head", { .window = 3 }, { .endpoint = served.endpoint_path }); served.publish(1); served.publish(2); @@ -234,8 +234,8 @@ TEST_CASE("an in-order reader gets every frame set", "[unit][camera_reader]") TEST_CASE("a newest-order reader with a larger window skips to the newest waiting frame set", "[unit][camera_reader]") { Served served; - CameraReader reader = - CameraReader::open(served.endpoint_path, "head", { .window = 3, .order = DeliveryOrder::NEWEST }); + CameraReader reader = CameraReader::open( + "head", { .window = 3, .order = DeliveryOrder::NEWEST }, { .endpoint = served.endpoint_path }); served.publish(1); served.publish(2); @@ -264,7 +264,7 @@ TEST_CASE("a frame set can be given back after its reader is gone", "[unit][came Served served; std::optional frames; { - CameraReader reader = CameraReader::open(served.endpoint_path, "head"); + CameraReader reader = CameraReader::open("head", {}, { .endpoint = served.endpoint_path }); served.publish(5); frames = reader.next(2s); REQUIRE(frames.has_value()); @@ -279,23 +279,24 @@ TEST_CASE("a frame set can be given back after its reader is gone", "[unit][came TEST_CASE("a reader says why it could not be opened", "[unit][camera_reader]") { TemporaryDirectory directory; - REQUIRE_THROWS_WITH( - CameraReader::open(directory.socket_path(), "head"), ContainsSubstring("no camera plugin answers on")); - REQUIRE_THROWS_AS(CameraReader::list(directory.socket_path()), CameraReaderError); + REQUIRE_THROWS_WITH(CameraReader::open("head", {}, { .endpoint = directory.socket_path() }), + ContainsSubstring("no camera plugin answers on")); + REQUIRE_THROWS_AS(CameraReader::list({ .endpoint = directory.socket_path() }), CameraReaderError); Served served; - REQUIRE_THROWS_WITH(CameraReader::open(served.endpoint_path, "chest"), ContainsSubstring("no group 'chest'")); - REQUIRE_THROWS_WITH(CameraReader::open(served.endpoint_path, "head", { .window = SLOTS }), + REQUIRE_THROWS_WITH( + CameraReader::open("chest", {}, { .endpoint = served.endpoint_path }), ContainsSubstring("no group 'chest'")); + REQUIRE_THROWS_WITH(CameraReader::open("head", { .window = SLOTS }, { .endpoint = served.endpoint_path }), ContainsSubstring("does not fit the pool")); // A refusal leaves nothing behind: the pool still has room for a reader that fits. - REQUIRE_NOTHROW(CameraReader::open(served.endpoint_path, "head", { .window = 2 })); + REQUIRE_NOTHROW(CameraReader::open("head", { .window = 2 }, { .endpoint = served.endpoint_path })); } TEST_CASE("a reader is told when the plugin is gone", "[unit][camera_reader]") { Served served; - CameraReader reader = CameraReader::open(served.endpoint_path, "head"); + CameraReader reader = CameraReader::open("head", {}, { .endpoint = served.endpoint_path }); served.publish(1); std::optional frames = reader.next(2s); REQUIRE(frames.has_value()); @@ -364,7 +365,7 @@ TEST_CASE("a reader copes with what a plugin may send", "[unit][camera_reader]") } }); - CameraReader reader = CameraReader::open(directory.socket_path(), "head"); + CameraReader reader = CameraReader::open("head", {}, { .endpoint = directory.socket_path() }); std::optional frames = reader.next(2s); REQUIRE(frames.has_value()); REQUIRE(frames->sequence() == 1); diff --git a/tests/cpp/plugins/camera/CMakeLists.txt b/tests/cpp/plugins/camera/CMakeLists.txt index 3c6c5f9816..b737591533 100644 --- a/tests/cpp/plugins/camera/CMakeLists.txt +++ b/tests/cpp/plugins/camera/CMakeLists.txt @@ -7,6 +7,7 @@ find_package(Threads REQUIRED) add_executable(camera_plugin_tests test_camera_bench.cpp + test_camera_config.cpp test_camera_host.cpp test_camera_plugin.cpp ) diff --git a/tests/cpp/plugins/camera/test_camera_bench.cpp b/tests/cpp/plugins/camera/test_camera_bench.cpp index e6d65f6214..ad049cd24e 100644 --- a/tests/cpp/plugins/camera/test_camera_bench.cpp +++ b/tests/cpp/plugins/camera/test_camera_bench.cpp @@ -126,7 +126,7 @@ TEST_CASE("the bench reads a camera from another process and reports each step", REQUIRE(unknown.exit_code == 1); REQUIRE_THAT(unknown.output, ContainsSubstring("no group 'chest'")); - REQUIRE(run_bench(directory, { "--group=head" }).exit_code == 2); + REQUIRE(run_bench(directory, { "--endpoint=" + endpoint, "--instance=other" }).exit_code == 2); REQUIRE(run_bench(directory, { "--endpoint=" + endpoint, "--order=backwards" }).exit_code == 2); REQUIRE(run_bench(directory, { "--help" }).exit_code == 0); diff --git a/tests/cpp/plugins/camera/test_camera_config.cpp b/tests/cpp/plugins/camera/test_camera_config.cpp new file mode 100644 index 0000000000..df87f9a3d5 --- /dev/null +++ b/tests/cpp/plugins/camera/test_camera_config.cpp @@ -0,0 +1,178 @@ +// 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 + +using namespace plugins::camera; +using Catch::Matchers::ContainsSubstring; + +namespace +{ + +class TemporaryDirectory +{ +public: + TemporaryDirectory() + { + std::string pattern = (std::filesystem::temp_directory_path() / "camera_config_XXXXXX").string(); + REQUIRE(::mkdtemp(pattern.data()) != nullptr); + m_path = pattern; + } + + ~TemporaryDirectory() + { + std::error_code ignored; + std::filesystem::remove_all(m_path, ignored); + } + + // Writes a configuration file and returns its path. + std::string write(const std::string& text) const + { + const std::string path = (m_path / "cameras.yaml").string(); + std::ofstream(path) << text; + return path; + } + +private: + std::filesystem::path m_path; +}; + +// Sets an environment variable for one test and puts back what was there. +class ScopedEnvironment +{ +public: + ScopedEnvironment(const char* name, const char* value) : m_name(name) + { + if (const char* previous = std::getenv(name)) + { + m_previous = previous; + } + if (value != nullptr) + { + ::setenv(name, value, 1); + } + else + { + ::unsetenv(name); + } + } + + ~ScopedEnvironment() + { + if (m_previous) + { + ::setenv(m_name, m_previous->c_str(), 1); + } + else + { + ::unsetenv(m_name); + } + } + +private: + const char* m_name; + std::optional m_previous; +}; + +} // namespace + +TEST_CASE("a configuration file names cameras, three lines each", "[unit][camera_plugin][config]") +{ + TemporaryDirectory directory; + const PluginConfig config = + load_config_file(directory.write("cameras:\n" + " head:\n" + " backend: synthetic\n" + " wrist:\n" + " backend: synthetic\n" + " width: 640\n" + " format: gray8\n" + "slots: 12\n")); + REQUIRE(config.slot_count == 12); + REQUIRE(config.cameras.size() == 2); + REQUIRE(config.cameras[0].id == "head"); // in the order of the file + REQUIRE(config.cameras[0].backend == "synthetic"); + REQUIRE(config.cameras[0].options.empty()); + REQUIRE(config.cameras[1].id == "wrist"); + REQUIRE(config.cameras[1].options.size() == 2); + REQUIRE(config.cameras[1].options.at("width") == "640"); + REQUIRE(config.cameras[1].options.at("format") == "gray8"); + + // Without `slots:` the pools have the default size; a file may also name no camera yet. + REQUIRE(load_config_file(directory.write("cameras:\n head:\n backend: synthetic\n")).slot_count == + DEFAULT_SLOT_COUNT); + REQUIRE(load_config_file(directory.write("cameras: {}\n")).cameras.empty()); +} + +TEST_CASE("a configuration file that cannot be used says where and why", "[unit][camera_plugin][config]") +{ + TemporaryDirectory directory; + const auto error_of = [&](const std::string& text) + { + try + { + (void)load_config_file(directory.write(text)); + } + catch (const std::invalid_argument& error) + { + return std::string(error.what()); + } + return std::string("no error"); + }; + + REQUIRE_THAT(error_of("cameras:\n head:\n width: 640\n"), + ContainsSubstring("cameras.yaml:3: camera 'head' needs a backend")); + REQUIRE_THAT(error_of("cameras:\n head: synthetic\n"), ContainsSubstring("camera 'head' needs a backend")); + REQUIRE_THAT(error_of("cameras:\n head:\n backend: synthetic\n modes: [a, b]\n"), + ContainsSubstring("cameras.yaml:4: camera 'head' takes settings of the form `name: value`")); + REQUIRE_THAT(error_of("camera:\n head:\n backend: synthetic\n"), + ContainsSubstring("cameras.yaml:1: there is no setting 'camera'")); + REQUIRE_THAT(error_of("cameras:\n - head\n"), ContainsSubstring("lists cameras by id")); + REQUIRE_THAT( + error_of("cameras: {}\nslots: many\n"), ContainsSubstring("cameras.yaml:2: `slots:` takes a whole number")); + REQUIRE_THAT(error_of("- just\n- a list\n"), ContainsSubstring("starts with `cameras:`")); + REQUIRE_THAT(error_of("cameras:\n head: [unclosed\n"), ContainsSubstring("not valid YAML")); + + REQUIRE_THROWS_WITH(load_config_file("/nonexistent/cameras.yaml"), ContainsSubstring("cannot be read")); +} + +TEST_CASE("the default configuration file is in the user's configuration directory", "[unit][camera_plugin][config]") +{ + { + const ScopedEnvironment config_home("XDG_CONFIG_HOME", "/etc/xdg-test"); + REQUIRE(default_config_path() == "/etc/xdg-test/isaaccapture/cameras.yaml"); + } + const ScopedEnvironment config_home("XDG_CONFIG_HOME", nullptr); + const ScopedEnvironment home("HOME", "/home/somebody"); + REQUIRE(default_config_path() == "/home/somebody/.config/isaaccapture/cameras.yaml"); +} + +TEST_CASE("the backends that can look for cameras are asked what is plugged in", "[unit][camera_plugin][config]") +{ + const auto found = [](std::vector cameras) { return [cameras] { return cameras; }; }; + const std::vector backends = { + { "synthetic", "", {} }, // cannot look: no hardware behind it + { "zed", "", {}, found({ { "zed-1234", "zed", { { "serial", "1234" } } } }) }, + { "oak", "", {}, found({}) }, + { "argus", "", {}, found({ { "argus-0", "argus", {} }, { "argus-1", "argus", {} } }) }, + }; + const std::vector cameras = discover_cameras(backends); + REQUIRE(cameras.size() == 3); + REQUIRE(cameras[0].id == "zed-1234"); + REQUIRE(cameras[0].options.at("serial") == "1234"); + REQUIRE(cameras[2].id == "argus-1"); + + REQUIRE(discover_cameras(std::vector{ { "synthetic", "", {} } }).empty()); +} diff --git a/tests/cpp/plugins/camera/test_camera_host.cpp b/tests/cpp/plugins/camera/test_camera_host.cpp index 6b5983c828..fae9872527 100644 --- a/tests/cpp/plugins/camera/test_camera_host.cpp +++ b/tests/cpp/plugins/camera/test_camera_host.cpp @@ -205,15 +205,15 @@ TEST_CASE("a host gives each camera its pools and serves them all on one endpoin REQUIRE(head.output != nullptr); REQUIRE_THROWS_AS(host.add_camera(std::make_unique("late", 1, unused)), std::logic_error); - const std::vector groups = CameraReader::list(directory.socket_path()); + const std::vector groups = CameraReader::list({ .endpoint = directory.socket_path() }); REQUIRE(groups.size() == 2); REQUIRE(groups[0].id == "head"); REQUIRE(groups[0].streams[0].slot_count == DEFAULT_SLOT_COUNT); REQUIRE(groups[1].id == "wrist"); REQUIRE(groups[1].streams[0].slot_count == 4); - CameraReader head_reader = CameraReader::open(directory.socket_path(), "head"); - CameraReader wrist_reader = CameraReader::open(directory.socket_path(), "wrist"); + CameraReader head_reader = CameraReader::open("head", {}, { .endpoint = directory.socket_path() }); + CameraReader wrist_reader = CameraReader::open("wrist", {}, { .endpoint = directory.socket_path() }); REQUIRE(host.reader_count() == 2); REQUIRE(head.publish(0x21)); @@ -242,7 +242,7 @@ TEST_CASE("a camera drops a frame set when its pool is full, and never overwrite host.start(); // A window of one in a pool of three: the newest, the reader's, and one to write ahead. - CameraReader reader = CameraReader::open(directory.socket_path(), "head"); + CameraReader reader = CameraReader::open("head", {}, { .endpoint = directory.socket_path() }); REQUIRE(camera.publish(1)); const std::optional held = reader.next(2s); REQUIRE(held.has_value()); diff --git a/tests/cpp/plugins/camera/test_camera_plugin.cpp b/tests/cpp/plugins/camera/test_camera_plugin.cpp index e566ae6884..0b138ea150 100644 --- a/tests/cpp/plugins/camera/test_camera_plugin.cpp +++ b/tests/cpp/plugins/camera/test_camera_plugin.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -59,10 +60,46 @@ class TemporaryDirectory return (m_path / "cameras.sock").string(); } + const std::filesystem::path& path() const + { + return m_path; + } + private: std::filesystem::path m_path; }; +// Sets an environment variable for one test, and for the processes it starts, and puts back +// what was there. +class ScopedEnvironment +{ +public: + ScopedEnvironment(const char* name, const std::string& value) : m_name(name) + { + if (const char* previous = std::getenv(name)) + { + m_previous = previous; + } + ::setenv(name, value.c_str(), 1); + } + + ~ScopedEnvironment() + { + if (m_previous) + { + ::setenv(m_name, m_previous->c_str(), 1); + } + else + { + ::unsetenv(m_name); + } + } + +private: + const char* m_name; + std::optional m_previous; +}; + std::unique_ptr open_synthetic(const std::string& argument) { const CameraConfig config = parse_camera_argument(argument); @@ -132,7 +169,7 @@ class PluginProcess }; // A plugin that was just started needs a moment before it listens. -std::optional open_when_ready(const std::string& endpoint, +std::optional open_when_ready(const core::camera::PluginLocation& plugin, const std::string& group, const core::camera::ReaderOptions& options = {}) { @@ -141,7 +178,7 @@ std::optional open_when_ready(const std::string& endpoint, { try { - return CameraReader::open(endpoint, group, options); + return CameraReader::open(group, options, plugin); } catch (const CameraReaderError&) { @@ -205,14 +242,14 @@ TEST_CASE("synthetic cameras reach readers whole and in step", "[unit][camera_pl host.start(); REQUIRE_THROWS_AS(host.add_camera(open_synthetic("late:synthetic")), std::logic_error); - const auto groups = CameraReader::list(directory.socket_path()); + const auto groups = CameraReader::list({ .endpoint = directory.socket_path() }); REQUIRE(groups.size() == 2); REQUIRE(groups[0].streams[0].slot_count == DEFAULT_SLOT_COUNT); REQUIRE(groups[1].streams[0].slot_count == 6); // A pair arrives as one frame set: the same frame number in both eyes, each with its own fill. - CameraReader head = CameraReader::open(directory.socket_path(), "head"); - CameraReader wrist = CameraReader::open(directory.socket_path(), "wrist", { .window = 2 }); + CameraReader head = CameraReader::open("head", {}, { .endpoint = directory.socket_path() }); + CameraReader wrist = CameraReader::open("wrist", { .window = 2 }, { .endpoint = directory.socket_path() }); std::uint64_t previous = 0; for (int i = 0; i < 20; ++i) { @@ -256,7 +293,7 @@ TEST_CASE("a reader in another process gets frames from the plugin", "[unit][cam PluginProcess plugin({ "--endpoint=" + endpoint, "--camera=head:synthetic:width=320,height=240,fps=120", "--plugin-root-id=ignored" }); - std::optional reader = open_when_ready(endpoint, "head"); + std::optional reader = open_when_ready({ .endpoint = endpoint }, "head"); REQUIRE(reader.has_value()); std::uint64_t previous = 0; for (int i = 0; i < 30; ++i) @@ -281,24 +318,68 @@ TEST_CASE("a reader in another process gets frames from the plugin", "[unit][cam // A plugin that was killed leaves a socket file behind; the next one replaces it. { PluginProcess killed({ "--endpoint=" + endpoint, "--camera=head:synthetic:width=64,height=48" }); - REQUIRE(open_when_ready(endpoint, "head").has_value()); + REQUIRE(open_when_ready({ .endpoint = endpoint }, "head").has_value()); REQUIRE(killed.stop(SIGKILL) == -1); } REQUIRE(std::filesystem::exists(endpoint)); PluginProcess next({ "--endpoint=" + endpoint, "--camera=head:synthetic:width=64,height=48" }); - std::optional again = open_when_ready(endpoint, "head"); + std::optional again = open_when_ready({ .endpoint = endpoint }, "head"); REQUIRE(again.has_value()); REQUIRE(again->next(2s).has_value()); } +TEST_CASE("a plugin without arguments serves its configuration file where readers look", "[unit][camera_plugin][process]") +{ + // A user's runtime and configuration directories, for this test and the plugins it starts. + TemporaryDirectory directory; + const std::filesystem::path config_directory = directory.path() / "config" / "isaaccapture"; + std::filesystem::create_directories(config_directory); + std::filesystem::create_directories(directory.path() / "run"); + const ScopedEnvironment runtime("XDG_RUNTIME_DIR", (directory.path() / "run").string()); + const ScopedEnvironment config_home("XDG_CONFIG_HOME", (directory.path() / "config").string()); + std::ofstream(config_directory / "cameras.yaml") << "cameras:\n" + " head:\n" + " backend: synthetic\n" + " width: 160\n" + " height: 120\n" + " fps: 120\n"; + + // Neither side is told where the other is. + PluginProcess plugin({}); + std::optional reader = open_when_ready({}, "head"); + REQUIRE(reader.has_value()); + const std::optional frames = reader->next(2s); + REQUIRE(frames.has_value()); + REQUIRE(frames->image(0).stream->width == 160); + require_synthetic(frames->image(0), 0); + REQUIRE(std::filesystem::is_socket(directory.path() / "run" / "isaaccapture" / "camera.sock")); + + // A second plugin runs beside it as a named instance, with cameras of its own. + PluginProcess second({ "--instance=bench", "--camera=wrist:synthetic:width=64,height=48,streams=1" }); + std::optional wrist = open_when_ready({ .instance = "bench" }, "wrist"); + REQUIRE(wrist.has_value()); + REQUIRE(wrist->next(2s).has_value()); + REQUIRE_THROWS_WITH(CameraReader::open("wrist"), ContainsSubstring("no group 'wrist'")); + REQUIRE_THROWS_WITH( + CameraReader::open("head", {}, { .instance = "nobody" }), ContainsSubstring("camera-nobody.sock")); + + // Another file can be named; --auto sets the file aside, and this build finds no camera. + const std::string other = (directory.path() / "other.yaml").string(); + std::ofstream(other) << "cameras:\n chest:\n backend: synthetic\n width: 64\n height: 48\n"; + PluginProcess third({ "--instance=third", "--config=" + other }); + REQUIRE(open_when_ready({ .instance = "third" }, "chest").has_value()); + REQUIRE(PluginProcess({ "--instance=fourth", "--auto" }).wait() == 1); + REQUIRE(PluginProcess({ "--instance=fifth", "--config=" + (directory.path() / "missing.yaml").string() }).wait() == 1); +} + TEST_CASE("the plugin refuses arguments it cannot use", "[unit][camera_plugin][process]") { TemporaryDirectory directory; const std::string endpoint = "--endpoint=" + directory.socket_path(); REQUIRE(PluginProcess({ "--list-backends" }).wait() == 0); REQUIRE(PluginProcess({ "--help" }).wait() == 0); - REQUIRE(PluginProcess({}).wait() == 2); - REQUIRE(PluginProcess({ endpoint }).wait() == 2); + REQUIRE(PluginProcess({ endpoint, "--instance=other" }).wait() == 2); + REQUIRE(PluginProcess({ endpoint, "--auto", "--camera=head:synthetic" }).wait() == 2); REQUIRE(PluginProcess({ endpoint, "--camera=head:synthetic", "--frobnicate" }).wait() == 2); REQUIRE(PluginProcess({ endpoint, "--camera=head" }).wait() == 2); // Arguments that parse but cannot be honoured end the plugin with an error in its log.