/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * ipa_manager.cpp - Image Processing Algorithm module manager */ #include "ipa_manager.h" #include #include #include #include #include "ipa_module.h" #include "ipa_proxy.h" #include "log.h" #include "pipeline_handler.h" #include "utils.h" /** * \file ipa_manager.h * \brief Image Processing Algorithm module manager */ namespace libcamera { LOG_DEFINE_CATEGORY(IPAManager) /** * \class IPAManager * \brief Manager for IPA modules * * The IPA module manager discovers IPA modules from disk, queries and loads * them, and creates IPA contexts. It supports isolation of the modules in a * separate process with IPC communication and offers a unified IPAInterface * view of the IPA contexts to pipeline handlers regardless of whether the * modules are isolated or loaded in the same process. * * Module isolation is based on the module licence. Open-source modules are * loaded without isolation, while closed-source module are forcefully isolated. * The isolation mechanism ensures that no code from a closed-source module is * ever run in the libcamera process. * * To create an IPA context, pipeline handlers call the IPAManager::ipaCreate() * method. For a directly loaded module, the manager calls the module's * ipaCreate() function directly and wraps the returned context in an * IPAContextWrapper that exposes an IPAInterface. * * ~~~~ * +---------------+ * | Pipeline | * | Handler | * +---------------+ * | * v * +---------------+ +---------------+ * | IPA | | Open Source | * | Interface | | IPA Module | * | - - - - - - - | | - - - - - - - | * | IPA Context | ipa_context_ops | ipa_context | * | Wrapper | ----------------> | | * +---------------+ +---------------+ * ~~~~ * * For an isolated module, the manager instantiates an IPAProxy which spawns a * new process for an IPA proxy worker. The worker loads the IPA module and * creates the IPA context. The IPAProxy alse exposes an IPAInterface. * * ~~~~ * +---------------+ +---------------+ * | Pipeline | | Closed Source | * | Handler | | IPA Module | * +---------------+ | - - - - - - - | * | | ipa_context | * v | | * +---------------+ +---------------+ * | IPA | ipa_context_ops ^ * | Interface | | * | - - - - - - - | +---------------+ * | IPA Proxy | operations | IPA Proxy | * | | ----------------> | Worker | * +---------------+ over IPC +---------------+ * ~~~~ * * The IPAInterface implemented by the IPAContextWrapper or IPAProxy is * returned to the pipeline handler, and all interactions with the IPA context * go the same interface regardless of process isolation. * * In all cases the data passed to the IPAInterface methods is serialized to * Plain Old Data, either for the purpose of passing it to the IPA context * plain C API, or to transmit the data to the isolated process through IPC. */ IPAManager::IPAManager() { unsigned int ipaCount = 0; /* User-specified paths take precedence. */ const char *modulePaths = utils::secure_getenv("LIBCAMERA_IPA_MODULE_PATH"); if (modulePaths) { for (const auto &dir : utils::split(modulePaths, ":")) { if (dir.empty()) continue; ipaCount += addDir(dir.c_str()); } if (!ipaCount) LOG(IPAManager, Warning) << "No IPA found in '" << modulePaths << "'"; } /* * When libcamera is used before it is installed, load IPAs from the * same build directory as the libcamera library itself. This requires * identifying the path of the libcamera.so, and referencing a relative * path for the IPA from that point. We need to recurse one level of * sub-directories to match the build tree. */ std::string root = utils::libcameraBuildPath(); if (!root.empty()) { std::string ipaBuildPath = root + "src/ipa"; constexpr int maxDepth = 1; LOG(IPAManager, Info) << "libcamera is not installed. Adding '" << ipaBuildPath << "' to the IPA search path"; ipaCount += addDir(ipaBuildPath.c_str(), maxDepth); } /* Finally try to load IPAs from the installed system path. */ ipaCount += addDir(IPA_MODULE_DIR); if (!ipaCount) LOG(IPAManager, Warning) << "No IPA found in '" IPA_MODULE_DIR "'"; } IPAManager::~IPAManager() { for (IPAModule *module : modules_) delete module; } /** * \brief Retrieve the IPA manager instance * * The IPAManager is a singleton and can't be constructed manually. This * function shall instead be used to retrieve the single global instance of the * manager. * * \return The IPA manager instance */ IPAManager *IPAManager::instance() { static IPAManager ipaManager; return &ipaManager; } /** * \brief Identify shared library objects within a directory * \param[in] libDir The directory to search for shared objects * \param[in] maxDepth The maximum depth of sub-directories to parse * \param[out] files A vector of paths to shared object library files * * Search a directory for .so files, allowing recursion down to sub-directories * no further than the depth specified by \a maxDepth. * * Discovered shared objects are added to the \a files vector. */ void IPAManager::parseDir(const char *libDir, unsigned int maxDepth, std::vector &files) { struct dirent *ent; DIR *dir; dir = opendir(libDir); if (!dir) return; while ((ent = readdir(dir)) != nullptr) { if (ent->d_type == DT_DIR && maxDepth) { if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; std::string subdir = std::string(libDir) + "/" + ent->d_name; /* Recursion is limited to maxDepth. */ parseDir(subdir.c_str(), maxDepth - 1, files); continue; } int offset = strlen(ent->d_name) - 3; if (offset < 0) continue; if (strcmp(&ent->d_name[offset], ".so")) continue; files.push_back(std::string(libDir) + "/" + ent->d_name); } closedir(dir); } /** * \brief Load IPA modules from a directory * \param[in] libDir The directory to search for IPA modules * \param[in] maxDepth The maximum depth of sub-directories to search * * This method tries to create an IPAModule instance for every shared object * found in \a libDir, and skips invalid IPA modules. * * Sub-directories are searched up to a depth of \a maxDepth. A \a maxDepth * value of 0 only searches the directory specified in \a libDir. * * \return Number of modules loaded by this call */ unsigned int IPAManager::addDir(const char *libDir, unsigned int maxDepth) { std::vector files; parseDir(libDir, maxDepth, files); /* Ensure a stable ordering of modules. */ std::sort(files.begin(), files.end()); unsigned int count = 0; for (const std::string &file : files) { IPAModule *ipaModule = new IPAModule(file); if (!ipaModule->isValid()) { delete ipaModule; continue; } LOG(IPAManager, Debug) << "Loaded IPA module '" << file << "'"; modules_.push_back(ipaModule); count++; } return count; } /** * \brief Create an IPA interface that matches a given pipeline handler * \param[in] pipe The pipeline handler that wants a matching IPA interface * \param[in] minVersion Minimum acceptable version of IPA module * \param[in] maxVersion Maximum acceptable version of IPA module * * \return A newly created IPA interface, or nullptr if no matching * IPA module is found or if the IPA interface fails to initialize */ std::unique_ptr IPAManager::createIPA(PipelineHandler *pipe, uint32_t maxVersion, uint32_t minVersion) { IPAModule *m = nullptr; for (IPAModule *module : modules_) { if (module->match(pipe, minVersion, maxVersion)) { m = module; break; } } if (!m) return nullptr; /* * Load and run the IPA module in a thread if it is open-source, or * isolate it in a separate process otherwise. * * \todo Implement a better proxy selection */ const char *proxyName = m->isOpenSource() ? "IPAProxyThread" : "IPAProxyLinux"; IPAProxyFactory *pf = nullptr; for (IPAProxyFactory *factory : IPAProxyFactory::factories()) { if (!strcmp(factory->name().c_str(), proxyName)) { pf = factory; break; } } if (!pf) { LOG(IPAManager, Error) << "Failed to get proxy factory"; return nullptr; } std::unique_ptr proxy = pf->create(m); if (!proxy->isValid()) { LOG(IPAManager, Error) << "Failed to load proxy"; return nullptr; } return proxy; } } /* namespace libcamera */ 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
 * Copyright (C) 2019, Google Inc.
 *
 * ipa_wrappers_test.cpp - Test the IPA interface and context wrappers
 */

#include <fcntl.h>
#include <iostream>
#include <memory>
#include <linux/videodev2.h>
#include <sys/stat.h>
#include <unistd.h>

#include <libcamera/controls.h>
#include <libipa/ipa_interface_wrapper.h>

#include "libcamera/internal/camera_sensor.h"
#include "libcamera/internal/device_enumerator.h"
#include "libcamera/internal/ipa_context_wrapper.h"
#include "libcamera/internal/media_device.h"
#include "libcamera/internal/v4l2_subdevice.h"

#include "test.h"

using namespace libcamera;
using namespace std;

enum Operation {
	Op_init,
	Op_start,
	Op_stop,
	Op_configure,
	Op_mapBuffers,
	Op_unmapBuffers,
	Op_processEvent,
};

class TestIPAInterface : public IPAInterface
{
public:
	TestIPAInterface()
		: sequence_(0)
	{
	}

	int init(const IPASettings &settings) override
	{
		if (settings.configurationFile != "/ipa/configuration/file") {
			cerr << "init(): Invalid configuration file" << endl;
			report(Op_init, TestFail);
			return 0;
		}

		report(Op_init, TestPass);
		return 0;
	}

	int start() override
	{
		report(Op_start, TestPass);
		return 0;
	}

	void stop() override
	{
		report(Op_stop, TestPass);
	}

	void configure(const CameraSensorInfo &sensorInfo,
		       const std::map<unsigned int, IPAStream> &streamConfig,
		       const std::map<unsigned int, const ControlInfoMap &> &entityControls,
		       [[maybe_unused]] const IPAOperationData &ipaConfig,
		       [[maybe_unused]] IPAOperationData *result) override
	{
		/* Verify sensorInfo. */
		if (sensorInfo.outputSize.width != 2560 ||
		    sensorInfo.outputSize.height != 1940) {
			cerr << "configure(): Invalid sensor info size "
			     << sensorInfo.outputSize.toString();
		}

		/* Verify streamConfig. */
		if (streamConfig.size() != 2) {
			cerr << "configure(): Invalid number of streams "
			     << streamConfig.size() << endl;
			return report(Op_configure, TestFail);
		}

		auto iter = streamConfig.find(1);
		if (iter == streamConfig.end()) {
			cerr << "configure(): No configuration for stream 1" << endl;
			return report(Op_configure, TestFail);
		}
		const IPAStream *stream = &iter->second;
		if (stream->pixelFormat != V4L2_PIX_FMT_YUYV ||
		    stream->size != Size{ 1024, 768 }) {
			cerr << "configure(): Invalid configuration for stream 1" << endl;
			return report(Op_configure, TestFail);
		}

		iter = streamConfig.find(2);
		if (iter == streamConfig.end()) {
			cerr << "configure(): No configuration for stream 2" << endl;
			return report(Op_configure, TestFail);
		}
		stream = &iter->second;
		if (stream->pixelFormat != V4L2_PIX_FMT_NV12 ||
		    stream->size != Size{ 800, 600 }) {
			cerr << "configure(): Invalid configuration for stream 2" << endl;
			return report(Op_configure, TestFail);
		}

		/* Verify entityControls. */
		auto ctrlIter = entityControls.find(42);
		if (ctrlIter == entityControls.end()) {
			cerr << "configure(): Controls not found" << endl;
			return report(Op_configure, TestFail);
		}

		const ControlInfoMap &infoMap = ctrlIter->second;

		if (infoMap.count(V4L2_CID_BRIGHTNESS) != 1 ||
		    infoMap.count(V4L2_CID_CONTRAST) != 1 ||
		    infoMap.count(V4L2_CID_SATURATION) != 1) {
			cerr << "configure(): Invalid control IDs" << endl;
			return report(Op_configure, TestFail);
		}

		report(Op_configure, TestPass);
	}

	void mapBuffers(const std::vector<IPABuffer> &buffers) override
	{
		if (buffers.size() != 2) {
			cerr << "mapBuffers(): Invalid number of buffers "
			     << buffers.size() << endl;
			return report(Op_mapBuffers, TestFail);
		}

		if (buffers[0].id != 10 ||
		    buffers[1].id != 11) {
			cerr << "mapBuffers(): Invalid buffer IDs" << endl;
			return report(Op_mapBuffers, TestFail);
		}

		if (buffers[0].planes.size() != 3 ||
		    buffers[1].planes.size() != 3) {
			cerr << "mapBuffers(): Invalid number of planes" << endl;
			return report(Op_mapBuffers, TestFail);
		}

		if (buffers[0].planes[0].length != 4096 ||
		    buffers[0].planes[1].length != 0 ||
		    buffers[0].planes[2].length != 0 ||
		    buffers[0].planes[0].length != 4096 ||
		    buffers[1].planes[1].length != 4096 ||
		    buffers[1].planes[2].length != 0) {
			cerr << "mapBuffers(): Invalid length" << endl;
			return report(Op_mapBuffers, TestFail);
		}

		if (buffers[0].planes[0].fd.fd() == -1 ||
		    buffers[0].planes[1].fd.fd() != -1 ||
		    buffers[0].planes[2].fd.fd() != -1 ||
		    buffers[0].planes[0].fd.fd() == -1 ||
		    buffers[1].planes[1].fd.fd() == -1 ||
		    buffers[1].planes[2].fd.fd() != -1) {
			cerr << "mapBuffers(): Invalid dmabuf" << endl;
			return report(Op_mapBuffers, TestFail);
		}

		report(Op_mapBuffers, TestPass);
	}

	void unmapBuffers(const std::vector<unsigned int> &ids) override
	{
		if (ids.size() != 2) {
			cerr << "unmapBuffers(): Invalid number of ids "
			     << ids.size() << endl;
			return report(Op_unmapBuffers, TestFail);
		}

		if (ids[0] != 10 || ids[1] != 11) {
			cerr << "unmapBuffers(): Invalid buffer IDs" << endl;
			return report(Op_unmapBuffers, TestFail);
		}

		report(Op_unmapBuffers, TestPass);
	}

	void processEvent(const IPAOperationData &data) override
	{
		/* Verify operation and data. */
		if (data.operation != Op_processEvent) {
			cerr << "processEvent(): Invalid operation "
			     << data.operation << endl;
			return report(Op_processEvent, TestFail);
		}

		if (data.data != std::vector<unsigned int>{ 1, 2, 3, 4 }) {
			cerr << "processEvent(): Invalid data" << endl;
			return report(Op_processEvent, TestFail);
		}

		/* Verify controls. */
		if (data.controls.size() != 1) {
			cerr << "processEvent(): Controls not found" << endl;
			return report(Op_processEvent, TestFail);
		}

		const ControlList &controls = data.controls[0];
		if (controls.get(V4L2_CID_BRIGHTNESS).get<int32_t>() != 10 ||
		    controls.get(V4L2_CID_CONTRAST).get<int32_t>() != 20 ||
		    controls.get(V4L2_CID_SATURATION).get<int32_t>() != 30) {
			cerr << "processEvent(): Invalid controls" << endl;
			return report(Op_processEvent, TestFail);
		}

		report(Op_processEvent, TestPass);
	}

private:
	void report(Operation op, int status)
	{
		IPAOperationData data;
		data.operation = op;
		data.data.resize(1);
		data.data[0] = status;
		queueFrameAction.emit(sequence_++, data);
	}

	unsigned int sequence_;
};

#define INVOKE(method, ...) \
	invoke(&IPAInterface::method, Op_##method, #method, ##__VA_ARGS__)

class IPAWrappersTest : public Test
{
public:
	IPAWrappersTest()
		: subdev_(nullptr), wrapper_(nullptr), sequence_(0), fd_(-1)
	{
	}

protected:
	int init() override
	{
		/* Locate the VIMC Sensor B subdevice. */
		enumerator_ = unique_ptr<DeviceEnumerator>(DeviceEnumerator::create());
		if (!enumerator_) {
			cerr << "Failed to create device enumerator" << endl;
			return TestFail;
		}

		if (enumerator_->enumerate()) {
			cerr << "Failed to enumerate media devices" << endl;
			return TestFail;
		}

		DeviceMatch dm("vimc");
		media_ = enumerator_->search(dm);
		if (!media_) {
			cerr << "No VIMC media device found: skip test" << endl;
			return TestSkip;
		}

		MediaEntity *entity = media_->getEntityByName("Sensor A");
		if (!entity) {
			cerr << "Unable to find media entity 'Sensor A'" << endl;
			return TestFail;
		}

		subdev_ = new V4L2Subdevice(entity);
		if (subdev_->open() < 0) {
			cerr << "Unable to open 'Sensor A' subdevice" << endl;
			return TestFail;
		}

		/* Force usage of the C API as that's what we want to test. */
		int ret = setenv("LIBCAMERA_IPA_FORCE_C_API", "", 1);
		if (ret)
			return TestFail;

		std::unique_ptr<IPAInterface> intf = std::make_unique<TestIPAInterface>();
		wrapper_ = new IPAContextWrapper(new IPAInterfaceWrapper(std::move(intf)));
		wrapper_->queueFrameAction.connect(this, &IPAWrappersTest::queueFrameAction);

		/* Create a file descriptor for the buffer-related operations. */
		fd_ = open("/tmp", O_TMPFILE | O_RDWR, 0600);
		if (fd_ == -1)
			return TestFail;

		ret = ftruncate(fd_, 4096);
		if (ret < 0)
			return TestFail;

		return TestPass;
	}

	int run() override
	{
		int ret;

		/* Test configure(). */
		CameraSensorInfo sensorInfo{
			.model = "sensor",
			.bitsPerPixel = 8,
			.activeAreaSize = { 2576, 1956 },
			.analogCrop = { 8, 8, 2560, 1940 },
			.outputSize = { 2560, 1940 },
			.pixelRate = 96000000,
			.lineLength = 2918,
		};
		std::map<unsigned int, IPAStream> config{
			{ 1, { V4L2_PIX_FMT_YUYV, { 1024, 768 } } },
			{ 2, { V4L2_PIX_FMT_NV12, { 800, 600 } } },
		};
		std::map<unsigned int, const ControlInfoMap &> controlInfo;
		controlInfo.emplace(42, subdev_->controls());
		IPAOperationData ipaConfig;
		ret = INVOKE(configure, sensorInfo, config, controlInfo,
			     ipaConfig, nullptr);
		if (ret == TestFail)
			return TestFail;

		/* Test mapBuffers(). */
		std::vector<IPABuffer> buffers(2);
		buffers[0].planes.resize(3);
		buffers[0].id = 10;
		buffers[0].planes[0].fd = FileDescriptor(fd_);
		buffers[0].planes[0].length = 4096;
		buffers[1].id = 11;
		buffers[1].planes.resize(3);
		buffers[1].planes[0].fd = FileDescriptor(fd_);
		buffers[1].planes[0].length = 4096;
		buffers[1].planes[1].fd = FileDescriptor(fd_);
		buffers[1].planes[1].length = 4096;

		ret = INVOKE(mapBuffers, buffers);
		if (ret == TestFail)
			return TestFail;

		/* Test unmapBuffers(). */
		std::vector<unsigned int> bufferIds = { 10, 11 };
		ret = INVOKE(unmapBuffers, bufferIds);
		if (ret == TestFail)
			return TestFail;

		/* Test processEvent(). */
		IPAOperationData data;
		data.operation = Op_processEvent;
		data.data = { 1, 2, 3, 4 };
		data.controls.emplace_back(subdev_->controls());

		ControlList &controls = data.controls.back();
		controls.set(V4L2_CID_BRIGHTNESS, static_cast<int32_t>(10));
		controls.set(V4L2_CID_CONTRAST, static_cast<int32_t>(20));
		controls.set(V4L2_CID_SATURATION, static_cast<int32_t>(30));

		ret = INVOKE(processEvent, data);
		if (ret == TestFail)
			return TestFail;

		/*
		 * Test init(), start() and stop() last to ensure nothing in the
		 * wrappers or serializer depends on them being called first.
		 */
		IPASettings settings{
			.configurationFile = "/ipa/configuration/file"
		};
		ret = INVOKE(init, settings);
		if (ret == TestFail) {
			cerr << "Failed to run init()";
			return TestFail;
		}

		ret = INVOKE(start);
		if (ret == TestFail) {
			cerr << "Failed to run start()";
			return TestFail;
		}

		ret = INVOKE(stop);
		if (ret == TestFail) {
			cerr << "Failed to run stop()";
			return TestFail;
		}

		return TestPass;
	}

	void cleanup() override
	{
		delete wrapper_;
		delete subdev_;

		if (fd_ != -1)
			close(fd_);
	}

private:
	template<typename T, typename... Args1, typename... Args2>
	int invoke(T (IPAInterface::*func)(Args1...), Operation op,
		   const char *name, Args2... args)
	{
		data_ = IPAOperationData();
		(wrapper_->*func)(args...);

		if (frame_ != sequence_) {
			cerr << "IPAInterface::" << name
			     << "(): invalid frame number " << frame_
			     << ", expected " << sequence_;
			return TestFail;
		}

		sequence_++;

		if (data_.operation != op) {
			cerr << "IPAInterface::" << name
			     << "(): failed to propagate" << endl;
			return TestFail;
		}

		if (data_.data[0] != TestPass) {
			cerr << "IPAInterface::" << name
			     << "(): reported an error" << endl;
			return TestFail;
		}

		return TestPass;
	}

	void queueFrameAction(unsigned int frame, const IPAOperationData &data)
	{
		frame_ = frame;
		data_ = data;
	}

	std::shared_ptr<MediaDevice> media_;
	std::unique_ptr<DeviceEnumerator> enumerator_;
	V4L2Subdevice *subdev_;

	IPAContextWrapper *wrapper_;
	IPAOperationData data_;
	unsigned int sequence_;
	unsigned int frame_;
	int fd_;
};

TEST_REGISTER(IPAWrappersTest)