/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2019, Google Inc. * * options.cpp - cam - Options parsing */ #include #include #include #include #include #include "options.h" /* ----------------------------------------------------------------------------- * Option */ const char *Option::typeName() const { switch (type) { case OptionNone: return "none"; case OptionInteger: return "integer"; case OptionString: return "string"; case OptionKeyValue: return "key=value"; } return "unknown"; } /* ----------------------------------------------------------------------------- * OptionBase */ template bool OptionsBase::empty() const { return values_.empty(); } template bool OptionsBase::valid() const { return valid_; } template bool OptionsBase::isSet(const T &opt) const { return values_.find(opt) != values_.end(); } template const OptionValue &OptionsBase::operator[](const T &opt) const { return values_.find(opt)->second; } template bool OptionsBase::parseValue(const T &opt, const Option &option, const char *optarg) { OptionValue value; switch (option.type) { case OptionNone: break; case OptionInteger: unsigned int integer; if (optarg) { char *endptr; integer = strtoul(optarg, &endptr, 10); if (*endptr != '\0') return false; } else { integer = 0; } value = OptionValue(integer); break; case OptionString: value = OptionValue(optarg ? optarg : ""); break; case OptionKeyValue: KeyValueParser *kvParser = option.keyValueParser; KeyValueParser::Options keyValues = kvParser->parse(optarg); if (!keyValues.valid()) return false; value = OptionValue(keyValues); break; } if (option.isArray) values_[opt].addValue(value); else values_[opt] = value; return true; } template class OptionsBase; template class OptionsBase; /* ----------------------------------------------------------------------------- * KeyValueParser */ bool KeyValueParser::addOption(const char *name, OptionType type, const char *help, OptionArgument argument) { if (!name) return false; if (!help || help[0] == '\0') return false; if (argument != ArgumentNone && type == OptionNone) return false; /* Reject duplicate options. */ if (optionsMap_.find(name) != optionsMap_.end()) return false; optionsMap_[name] = Option({ 0, type, name, argument, nullptr, help, nullptr, false }); return true; } KeyValueParser::Options KeyValueParser::parse(const char *arguments) { Options options; for (const char *pair = arguments; *arguments != '\0'; pair = arguments) { const char *comma = strchrnul(arguments, ','); size_t len = comma - pair; /* Skip over the comma. */ arguments = *comma == ',' ? comma + 1 : comma; /* Skip to the next pair if the pair is empty. */ if (!len) continue; std::string key; std::string value; const char *separator = static_cast(memchr(pair, '=', len)); if (!separator) { key = std::string(pair, len); value = ""; } else { key = std::string(pair, separator - pair); value = std::string(separator + 1, comma - separator - 1); } /* The key is mandatory, the value might be optional. */ if (key.empty()) continue; if (optionsMap_.find(key) == optionsMap_.end()) { std::cerr << "Invalid option " << key << std::endl; return options; } OptionArgument arg = optionsMap_[key].argument; if (value.empty() && arg == ArgumentRequired) { std::cerr << "Option " << key << " requires an argument" << std::endl; return options; } else if (!value.empty() && arg == ArgumentNone) { std::cerr << "Option " << key << " takes no argument" << std::endl; return options; } const Option &option = optionsMap_[key]; if (!options.parseValue(key, option, value.c_str())) { std::cerr << "Failed to parse '" << value << "' as " << option.typeName() << " for option " << key << std::endl; return options; } } options.valid_ = true; return options; } void KeyValueParser::usage(int indent) { unsigned int space = 0; for (auto const &iter : optionsMap_) { const Option &option = iter.second; unsigned int length = 14; if (option.argument != ArgumentNone) length += 1 + strlen(option.typeName()); if (option.argument == ArgumentOptional) length += 2; if (length > space) space = length; } space = (space + 7) / 8 * 8; for (auto const &iter : optionsMap_) { const Option &option = iter.second; std::string argument = option.name; if (option.argument != ArgumentNone) { if (option.argument == ArgumentOptional) argument += "[="; else argument += "="; argument += option.typeName(); if (option.argument == ArgumentOptional) argument += "]"; } std::cerr << std::setw(indent) << std::right << " " << std::setw(space) << std::left << argument; for (const char *help = option.help, *end = help; end;) { end = strchr(help, '\n'); if (end) { std::cerr << std::string(help, end - help + 1); std::cerr << std::setw(indent + space) << " "; help = end + 1; } else { std::cerr << help << std::endl; } } } } /* ----------------------------------------------------------------------------- * OptionValue */ OptionValue::OptionValue() : type_(ValueNone) { } OptionValue::OptionValue(int value) : type_(ValueInteger), integer_(value) { } OptionValue::OptionValue(const char *value) : type_(ValueString), string_(value) { } OptionValue::OptionValue(const std::string &value) : type_(ValueString), string_(value) { } OptionValue::OptionValue(const KeyValueParser::Options &value) : type_(ValueKeyValue), keyValues_(value) { } void OptionValue::addValue(const OptionValue &value) { assert(type_ == ValueNone || type_ == ValueArray); type_ = ValueArray; array_.push_back(value); } OptionValue::operator int() const { return toInteger(); } OptionValue::operator std::string() const { return toString(); } OptionValue::operator KeyValueParser::Options() const { return toKeyValues(); } OptionValue::operator std::vector() const { return toArray(); } int OptionValue::toInteger() const { if (type_ != ValueInteger) return 0; return integer_; } std::string OptionValue::toString() const { if (type_ != ValueString) return std::string(); return string_; } KeyValueParser::Options OptionValue::toKeyValues() const { if (type_ != ValueKeyValue) return KeyValueParser::Options(); return keyValues_; } std::vector OptionValue::toArray() const { if (type_ != ValueArray) return std::vector{}; return array_; } /* ----------------------------------------------------------------------------- * OptionsParser */ bool OptionsParser::addOption(int opt, OptionType type, const char *help, const char *name, OptionArgument argument, const char *argumentName, bool array) { /* * Options must have at least a short or long name, and a text message. * If an argument is accepted, it must be described by argumentName. */ if (!isalnum(opt) && !name) return false; if (!help || help[0] == '\0') return false; if (argument != ArgumentNone && !argumentName) return false; /* Reject duplicate options. */ if (optionsMap_.find(opt) != optionsMap_.end()) return false; options_.push_back(Option({ opt, type, name, argument, argumentName, help, nullptr, array })); optionsMap_[opt] = &options_.back(); return true; } bool OptionsParser::addOption(int opt, KeyValueParser *parser, const char *help, const char *name, bool array) { if (!addOption(opt, OptionKeyValue, help, name, ArgumentRequired, "key=value[,key=value,...]", array)) return false; options_.back().keyValueParser = parser; return true; } OptionsParser::Options OptionsParser::parse(int argc, char **argv) { OptionsParser::Options options; /* * Allocate short and long options arrays large enough to contain all * options. */ char shortOptions[options_.size() * 3 + 2] = {}; struct option longOptions[options_.size() + 1] = {}; unsigned int ids = 0; unsigned int idl = 0; shortOptions[ids++] = ':'; for (const Option &option : options_) { if (option.hasShortOption()) { shortOptions[ids++] = option.opt; if (option.argument != ArgumentNone) shortOptions[ids++] = ':'; if (option.argument == ArgumentOptional) shortOptions[ids++] = ':'; } if (option.hasLongOption()) { longOptions[idl].name = option.name; switch (option.argument) { case ArgumentNone: longOptions[idl].has_arg = no_argument; break; case ArgumentRequired: longOptions[idl].has_arg = required_argument; break; case ArgumentOptional: longOptions[idl].has_arg = optional_argument; break; } longOptions[idl].flag = 0; longOptions[idl].val = option.opt; idl++; } } opterr = 0; while (true) { int c = getopt_long(argc, argv, shortOptions, longOptions, nullptr); if (c == -1) break; if (c == '?' || c == ':') { if (c == '?') std::cerr << "Invalid option "; else std::cerr << "Missing argument for option "; std::cerr << argv[optind - 1] << std::endl; usage(); return options; } const Option &option = *optionsMap_[c]; if (!options.parseValue(c, option, optarg)) { parseValueError(option); usage(); return options; } } options.valid_ = true; return options; } void OptionsParser::usage() { std::cerr << "Options:" << std::endl; unsigned int indent = 0; for (const Option &option : options_) { unsigned int length = 14; if (option.hasLongOption()) length += 2 + strlen(option.name); if (option.argument != ArgumentNone) length += 1 + strlen(option.argumentName); if (option.argument == ArgumentOptional) length += 2; if (option.isArray) length += 4; if (length > indent) indent = length; } indent = (indent + 7) / 8 * 8; for (const Option &option : options_) { std::string argument; if (option.hasShortOption()) argument = std::string(" -") + static_cast(option.opt); else argument = " "; if (option.hasLongOption()) { if (option.hasShortOption()) argument += ", "; else argument += " "; argument += std::string("--") + option.name; }; if (option.argument != ArgumentNone) { if (option.argument == ArgumentOptional) argument += "[="; else argument += " "; argument += option.argumentName; if (option.argument == ArgumentOptional) argument += "]"; } if (option.isArray) argument += " ..."; std::cerr << std::setw(indent) << std::left << argument; for (const char *help = option.help, *end = help; end; ) { end = strchr(help, '\n'); if (end) { std::cerr << std::string(help, end - help + 1); std::cerr << std::setw(indent) << " "; help = end + 1; } else { std::cerr << help << std::endl; } } if (option.keyValueParser) option.keyValueParser->usage(indent); } } void OptionsParser::parseValueError(const Option &option) { std::string optionName; if (option.name) optionName = "--" + std::string(option.name); else optionName = "-" + static_cast(option.opt); std::cerr << "Can't parse " << option.typeName() << " argument for option " << optionName << std::endl; } 95 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
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2018, Google Inc.
 *
 * device_enumerator.cpp - Enumeration and matching
 */

#include "libcamera/internal/device_enumerator.h"
#include "libcamera/internal/device_enumerator_sysfs.h"
#include "libcamera/internal/device_enumerator_udev.h"

#include <string.h>

#include "libcamera/internal/log.h"
#include "libcamera/internal/media_device.h"

/**
 * \file device_enumerator.h
 * \brief Enumeration and matching of media devices
 *
 * The purpose of device enumeration and matching is to find media devices in
 * the system and map them to pipeline handlers.
 *
 * At the core of the enumeration is the DeviceEnumerator class, responsible
 * for enumerating all media devices in the system. It handles all interactions
 * with the operating system in a platform-specific way. For each media device
 * found an instance of MediaDevice is created to store information about the
 * device gathered from the kernel through the Media Controller API.
 *
 * The DeviceEnumerator can enumerate all or specific media devices in the
 * system. When a new media device is added the enumerator creates a
 * corresponding MediaDevice instance.
 *
 * The enumerator supports searching among enumerated devices based on criteria
 * expressed in a DeviceMatch object.
 */

namespace libcamera {

LOG_DEFINE_CATEGORY(DeviceEnumerator)

/**
 * \class DeviceMatch
 * \brief Description of a media device search pattern
 *
 * The DeviceMatch class describes a media device using properties from the
 * Media Controller struct media_device_info, entity names in the media graph
 * or other properties that can be used to identify a media device.
 *
 * The description is meant to be filled by pipeline managers and passed to a
 * device enumerator to find matching media devices.
 *
 * A DeviceMatch is created with a specific Linux device driver in mind,
 * therefore the name of the driver is a required property. One or more Entity
 * names can be added as match criteria.
 *
 * Pipeline handlers are recommended to add entities to DeviceMatch as
 * appropriare to ensure that the media device they need can be uniquely
 * identified. This is useful when the corresponding kernel driver can produce
 * different graphs, for instance as a result of different driver versions or
 * hardware configurations, and not all those graphs are suitable for a pipeline
 * handler.
 */

/**
 * \brief Construct a media device search pattern
 * \param[in] driver The Linux device driver name that created the media device
 */
DeviceMatch::DeviceMatch(const std::string &driver)
	: driver_(driver)
{
}

/**
 * \brief Add a media entity name to the search pattern
 * \param[in] entity The name of the entity in the media graph
 */
void DeviceMatch::add(const std::string &entity)
{
	entities_.push_back(entity);
}

/**
 * \brief Compare a search pattern with a media device
 * \param[in] device The media device
 *
 * Matching is performed on the Linux device driver name and entity names from
 * the media graph. A match is found if both the driver name matches and the
 * media device contains all the entities listed in the search pattern.
 *
 * \return true if the media device matches the search pattern, false otherwise
 */
bool DeviceMatch::match(const MediaDevice *device) const
{
	if (driver_ != device->driver())
		return false;

	for (const std::string &name : entities_) {
		bool found = false;

		for (const MediaEntity *entity : device->entities()) {
			if (name == entity->name()) {
				found = true;
				break;
			}
		}

		if (!found)
			return false;
	}

	return true;
}

/**
 * \class DeviceEnumerator
 * \brief Enumerate, store and search media devices
 *
 * The DeviceEnumerator class is responsible for all interactions with the
 * operating system related to media devices. It enumerates all media devices
 * in the system, and for each device found creates an instance of the
 * MediaDevice class and stores it internally. The list of media devices can
 * then be searched using DeviceMatch search patterns.
 *
 * The enumerator also associates media device entities with device node paths.
 */

/**
 * \brief Create a new device enumerator matching the systems capabilities
 *
 * Depending on how the operating system handles device detection, hot-plug
 * notification and device node lookup, different device enumerator
 * implementations may be needed. This function creates the best enumerator for
 * the operating system based on the available resources. Not all different
 * enumerator types are guaranteed to support all features.
 *
 * \return A pointer to the newly created device enumerator on success, or
 * nullptr if an error occurs
 */
std::unique_ptr<DeviceEnumerator> DeviceEnumerator::create()
{
	std::unique_ptr<DeviceEnumerator> enumerator;

#ifdef HAVE_LIBUDEV
	enumerator = std::make_unique<DeviceEnumeratorUdev>();
	if (!enumerator->init())
		return enumerator;
#endif

	/*
	 * Either udev is not available or udev initialization failed. Fall back
	 * on the sysfs enumerator.
	 */
	enumerator = std::make_unique<DeviceEnumeratorSysfs>();
	if (!enumerator->init())
		return enumerator;

	return nullptr;
}

DeviceEnumerator::~DeviceEnumerator()
{
	for (std::shared_ptr<MediaDevice> media : devices_) {
		if (media->busy())
			LOG(DeviceEnumerator, Error)
				<< "Removing media device " << media->deviceNode()
				<< " while still in use";
	}
}

/**
 * \fn DeviceEnumerator::init()
 * \brief Initialize the enumerator
 * \return 0 on success or a negative error code otherwise
 * \retval -EBUSY the enumerator has already been initialized
 * \retval -ENODEV the enumerator can't enumerate devices
 */

/**
 * \fn DeviceEnumerator::enumerate()
 * \brief Enumerate all media devices in the system
 *
 * This function finds and add all media devices in the system to the
 * enumerator. It shall be implemented by all subclasses of DeviceEnumerator
 * using system-specific methods.
 *
 * Individual media devices that can't be properly enumerated shall be skipped
 * with a warning message logged, without returning an error. Only errors that
 * prevent enumeration altogether shall be fatal.
 *
 * \context This function is \threadbound.
 *
 * \return 0 on success or a negative error code otherwise
 */

/**
 * \brief Create a media device instance
 * \param[in] deviceNode path to the media device to create
 *
 * Create a media device for the \a deviceNode, open it, and populate its
 * media graph. The device enumerator shall then populate the media device by
 * associating device nodes with entities using MediaEntity::setDeviceNode().
 * This process is specific to each device enumerator, and the device enumerator
 * shall ensure that device nodes are ready to be used (for instance, if
 * applicable, by waiting for device nodes to be created and access permissions
 * to be set by the system). Once done, it shall add the media device to the
 * system with addDevice().
 *
 * \return Created media device instance on success, or nullptr otherwise
 */
std::unique_ptr<MediaDevice> DeviceEnumerator::createDevice(const std::string &deviceNode)
{
	std::unique_ptr<MediaDevice> media = std::make_unique<MediaDevice>(deviceNode);

	int ret = media->populate();
	if (ret < 0) {
		LOG(DeviceEnumerator, Info)
			<< "Unable to populate media device " << deviceNode
			<< " (" << strerror(-ret) << "), skipping";
		return nullptr;
	}

	LOG(DeviceEnumerator, Debug)
		<< "New media device \"" << media->driver()
		<< "\" created from " << deviceNode;

	return media;
}

/**
 * \brief Add a media device to the enumerator
 * \param[in] media media device instance to add
 *
 * Store the media device in the internal list for later matching with
 * pipeline handlers. \a media shall be created with createDevice() first.
 * This method shall be called after all members of the entities of the
 * media graph have been confirmed to be initialized.
 */
void DeviceEnumerator::addDevice(std::unique_ptr<MediaDevice> &&media)
{
	LOG(DeviceEnumerator, Debug)
		<< "Added device " << media->deviceNode() << ": " << media->driver();

	devices_.push_back(std::move(media));
}

/**
 * \brief Remove a media device from the enumerator
 * \param[in] deviceNode Path to the media device to remove
 *
 * Remove the media device identified by \a deviceNode previously added to the
 * enumerator with addDevice(). The media device's MediaDevice::disconnected
 * signal is emitted.
 */
void DeviceEnumerator::removeDevice(const std::string &deviceNode)
{
	std::shared_ptr<MediaDevice> media;

	for (auto iter = devices_.begin(); iter != devices_.end(); ++iter) {
		if ((*iter)->deviceNode() == deviceNode) {
			media = std::move(*iter);
			devices_.erase(iter);
			break;
		}
	}

	if (!media) {
		LOG(DeviceEnumerator, Warning)
			<< "Media device for node " << deviceNode
			<< " not found";
		return;
	}

	LOG(DeviceEnumerator, Debug)
		<< "Media device for node " << deviceNode << " removed.";

	media->disconnected.emit(media.get());
}

/**
 * \brief Search available media devices for a pattern match
 * \param[in] dm Search pattern
 *
 * Search in the enumerated media devices that are not already in use for a
 * match described in \a dm. If a match is found and the caller intends to use
 * it the caller is responsible for acquiring the MediaDevice object and
 * releasing it when done with it.
 *
 * \return pointer to the matching MediaDevice, or nullptr if no match is found
 */
std::shared_ptr<MediaDevice> DeviceEnumerator::search(const DeviceMatch &dm)
{
	for (std::shared_ptr<MediaDevice> &media : devices_) {
		if (media->busy())
			continue;

		if (dm.match(media.get())) {