.. SPDX-License-Identifier: CC-BY-SA-4.0 Using libcamera in a C++ application ==================================== This tutorial shows how to create a C++ application that uses libcamera to interface with a camera on a system, capture frames from it for 3 seconds, and write metadata about the frames to standard out. Application skeleton -------------------- Most of the code in this tutorial runs in the ``int main()`` function with a separate global function to handle events. The two functions need to share data, which are stored in global variables for simplicity. A production-ready application would organize the various objects created in classes, and the event handler would be a class member function to provide context data without requiring global variables. Use the following code snippets as the initial application skeleton. It already lists all the necessary includes directives and instructs the compiler to use the libcamera namespace, which gives access to the libcamera defined names and types without the need of prefixing them. .. code:: cpp #include #include #include #include #include using namespace libcamera; using namespace std::chrono_literals; int main() { // Code to follow return 0; } Camera Manager -------------- Every libcamera-based application needs an instance of a `CameraManager`_ that runs for the life of the application. When the Camera Manager starts, it enumerates all the cameras detected in the system. Behind the scenes, libcamera abstracts and manages the complex pipelines that kernel drivers expose through the `Linux Media Controller`_ and `Video for Linux`_ (V4L2) APIs, meaning that an application doesn't need to handle device or driver specific details. .. _CameraManager: https://libcamera.org/api-html/classlibcamera_1_1CameraManager.html .. _Linux Media Controller: https://www.kernel.org/doc/html/latest/media/uapi/mediactl/media-controller-intro.html .. _Video for Linux: https://www.linuxtv.org/docs.php Before the ``int main()`` function, create a global shared pointer variable for the camera to support the event call back later: .. code:: cpp static std::shared_ptr camera; Create a Camera Manager instance at the beginning of the main function, and then start it. An application must only create a single Camera Manager instance. The CameraManager can be stored in a unique_ptr to automate deleting the instance when it is no longer used, but care must be taken to ensure all cameras are released explicitly before this happens. .. code:: cpp std::unique_ptr cm = std::make_unique(); cm->start(); During the application initialization, the Camera Manager is started to enumerate all the supported devices and create cameras that the application can interact with. Once the camera manager is started, we can use it to iterate the available cameras in the system: .. code:: cpp for (auto const &camera : cm->cameras()) std::cout << camera->id() << std::endl; Printing the camera id lists the machine-readable unique identifiers, so for example, the output on a Linux machine with a connected USB webcam is ``\_SB_.PCI0.XHC_.RHUB.HS08-8:1.0-5986:2115``. What libcamera considers a camera ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The libcamera library considers any unique source of video frames, which usually correspond to a camera sensor, as a single camera device. Camera devices expose streams, which are obtained by processing data from the single image source and all share some basic properties such as the frame duration and the image exposure time, as they only depend by the image source configuration. Applications select one or multiple Camera devices they wish to operate on, and require frames from at least one of their Streams. Create and acquire a camera --------------------------- This example application uses a single camera (the first enumerated one) that the Camera Manager reports as available to applications. Camera devices are stored by the CameraManager in a list accessible by index, or can be retrieved by name through the ``CameraManager::get()`` function. The code below retrieves the name of the first available camera and gets the camera by name from the Camera Manager, after making sure that at least one camera is available. .. code:: cpp if (cm->cameras().empty()) { std::cout << "No cameras were identified on the system." << std::endl; cm->stop(); return EXIT_FAILURE; } std::string cameraId = cm->cameras()[0]->id(); camera = cm->get(cameraId); /* * Note that is equivalent to: * camera = cm->cameras()[0]; */ Once a camera has been selected an application needs to acquire an exclusive lock to it so no other application can use it. .. code:: cpp camera->acquire(); Configure the camera -------------------- Before the application can do anything with the camera, it needs to configure the image format and sizes of the streams it wants to capture frames from. Stream configurations are represented by instances of the ``StreamConfiguration`` class, which are grouped together in a ``CameraConfiguration`` object. Before an application can start setting its desired configuration, a ``CameraConfiguration`` instance needs to be generated from the ``Camera`` device using the ``Camera::generateConfiguration()`` function. The libcamera library uses the ``StreamRole`` enumeration to define predefined ways an application intends to use a camera. The ``Camera::generateConfiguration()`` function accepts a list of desired roles and generates a ``CameraConfiguration`` with the best stream parameters configuration for each of the requested roles. If the camera can handle the requested roles, it returns an initialized ``CameraConfiguration`` and a null pointer if it can't. It is possible for applications to generate an empty ``CameraConfiguration`` instance by not providing any role. The desired configuration will have to be filled-in manually and manually validated. In the example application, create a new configuration variable and use the ``Camera::generateConfiguration`` function to produce a ``CameraConfiguration`` for the single ``StreamRole::Viewfinder`` role. .. code:: cpp std::unique_ptr config = camera->generateConfiguration( { StreamRole::Viewfinder } ); The generated ``CameraConfiguration`` has a ``StreamConfiguration`` instance for each ``StreamRole`` the application requested. Each of these has a default size and format that the camera assigned, and a list of supported pixel formats and sizes. The code below accesses the first and only ``StreamConfiguration`` item in the ``CameraConfiguration`` and outputs its parameters to standard output. .. code:: cpp StreamConfiguration &streamConfig = config->at(0); std::cout << "Default viewfinder configuration is: " << streamConfig.toString() << std::endl; This is expected to output something like: ``Default viewfinder configuration is: 1280x720-MJPEG`` Change and validate the configuration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With an initialized ``CameraConfiguration``, an application can make changes to the parameters it contains, for example, to change the width and height, use the following code: .. code:: cpp streamConfig.size.width = 640; streamConfig.size.height = 480; If an application changes any parameters, it must validate the configuration before applying it to the camera using the ``CameraConfiguration::validate()`` function. If the new values are not supported by the ``Camera`` device, the validation process adjusts the parameters to what it considers to be the closest supported values. The ``validate`` function returns a `Status`_ which applications shall check to see if the Pipeline Handler adjusted the configuration. .. _Status: https://libcamera.org/api-html/classlibcamera_1_1CameraConfiguration.html#a64163f21db2fe1ce0a6af5a6f6847744 For example, the code above set the width and height to 640x480, but if the camera cannot produce an image that large, it might adjust the configuration to the supported size of 320x240 and return ``Adjusted`` as validation status result. If the configuration to validate cannot be adjusted to a set of supported values, the validation procedure fails and returns the ``Invalid`` status. For this example application, the code below prints the adjusted values to standard out. .. code:: cpp config->validate(); std::cout << "Validated viewfinder configuration is: " << streamConfig.toString() << std::endl; For example, the output might be something like ``Validated viewfinder configuration is: 320x240-MJPEG`` A validated ``CameraConfiguration`` can bet given to the ``Camera`` device to be applied to the system. .. code:: cpp camera->configure(config.get()); If an application doesn't first validate the configuration before calling ``Camera::configure()``, there's a chance that calling the function can fail, if the given configuration would have to be adjusted. Allocate FrameBuffers --------------------- An application needs to reserve the memory that libcamera can write incoming frames and data to, and that the application can then read. The libcamera library uses ``FrameBuffer`` instances to represent memory buffers allocated in memory. An application should reserve enough memory for the frame size the streams need based on the configured image sizes and formats. The libcamera library consumes buffers provided by applications as ``FrameBuffer`` instances, which makes libcamera a consumer of buffers exported by other devices (such as displays or video encoders), or allocated from an external allocator (such as ION on Android). In some situations, applications do not have any means to allocate or get hold of suitable buffers, for instance, when no other device is involved, or on Linux platforms that lack a centralized allocator. The ``FrameBufferAllocator`` class provides a buffer allocator an application can use in these situations. An application doesn't have to use the default ``FrameBufferAllocator`` that libcamera provides. It can instead allocate memory manually and pass the buffers in ``Request``\s (read more about ``Request`` in `the frame capture section <#frame-capture>`_ of this guide). The example in this guide covers using the ``FrameBufferAllocator`` that libcamera provides. Using the libcamera ``FrameBufferAllocator`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Applications create a ``FrameBufferAllocator`` for a Camera and use it to allocate buffers for streams of a ``CameraConfiguration`` with the ``allocate()`` function. The list of allocated buffers can be retrieved using the ``Stream`` instance as the parameter of the ``FrameBufferAllocator::buffers()`` function. .. code:: cpp FrameBufferAllocator *allocator = new FrameBufferAllocator(camera); for (StreamConfiguration &cfg : *config) { int ret = allocator->allocate(cfg.stream()); if (ret < 0) { std::cerr << "Can't allocate buffers" << std::endl; return -ENOMEM; } size_t allocated = allocator->buffers(cfg.stream()).size(); std::cout << "Allocated " << allocated << " buffers for stream" << std::endl; } Frame Capture ~~~~~~~~~~~~~ The libcamera library implements a streaming model based on per-frame requests. For each frame an application wants to capture it must queue a request for it to the camera. With libcamera, a ``Request`` is at least one ``Stream`` associated with a ``FrameBuffer`` representing the memory location where frames have to be stored. First, by using the ``Stream`` instance associated to each ``StreamConfiguration``, retrieve the list of ``FrameBuffer``\s created for it using the frame allocator. Then create a vector of requests to be submitted to the camera. .. code:: cpp Stream *stream = streamConfig.stream(); const std::vector> &buffers = allocator->buffers(stream); std::vector> requests; Proceed to fill the request vector by creating ``Request`` instances from the camera device, and associate a buffer for each of them for the ``Stream``. .. code:: cpp for (unsigned int i = 0; i < buffers.size(); ++i) { std::unique_ptr request = camera->createRequest(); if (!request) { std::cerr << "Can't create request" << std::endl; return -ENOMEM; } const std::unique_ptr &buffer = buffers[i]; int ret = request->addBuffer(stream, buffer.get()); if (ret < 0) { std::cerr << "Can't set buffer for request" << std::endl; return ret; } requests.push_back(std::move(request)); } .. TODO: Controls .. TODO: A request can also have controls or parameters that you can apply to the image. Event handling and callbacks ---------------------------- The libcamera library uses the concept of `signals and slots` (similar to `Qt Signals and Slots`_) to connect events with callbacks to handle them. .. _signals and slots: https://libcamera.org/api-html/classlibcamera_1_1Signal.html#details .. _Qt Signals and Slots: https://doc.qt.io/qt-5/signalsandslots.html The ``Camera`` device emits two signals that applications can connect to in order to execute callbacks on frame completion events. The ``Camera::bufferCompleted`` signal notifies applications that a buffer with image data is available. Receiving notifications about the single buffer completion event allows applications to implement partial request completion support, and to inspect the buffer content before the request it is part of has fully completed. The ``Camera::requestCompleted`` signal notifies applications that a request has completed, which means all the buffers the request contains have now completed. Request completion notifications are always emitted in the same order as the requests have been queued to the camera. To receive the signals emission notifications, connect a slot function to the signal to handle it in the application code. .. code:: cpp camera->requestCompleted.connect(requestComplete); For this example application, only the ``Camera::requestCompleted`` signal gets handled and the matching ``requestComplete`` slot function outputs information about the FrameBuffer to standard output. This callback is typically where an application accesses the image data from the camera and does something with it. Signals operate in the libcamera ``CameraManager`` thread context, so it is important not to block the thread for a long time, as this blocks internal processing of the camera pipelines, and can affect realtime performance. Handle request completion events ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Create the ``requestComplete`` function by matching the slot signature: .. code:: cpp static void requestComplete(Request *request) { // Code to follow } Request completion events can be emitted for requests which have been canceled, for example, by unexpected application shutdown. To avoid an application processing invalid image data, it's worth checking that the request has completed successfully. The list of request completion statuses is available in the `Request::Status`_ class enum documentation. .. _Request::Status: https://www.libcamera.org/api-html/classlibcamera_1_1Request.html#a2209ba8d51af8167b25f6e3e94d5c45b .. code:: cpp if (request->status() == Request::RequestCancelled) return; If the ``Request`` has completed successfully, applications can access the completed buffers using the ``Request::buffers()`` function, which returns a map of ``FrameBuffer`` instances associated with the ``Stream`` that produced the images. .. code:: cpp const std::map &buffers = request->buffers(); Iterating through the map allows applications to inspect each completed buffer in this request, and access the metadata associated to each frame. The metadata buffer contains information such the capture status, a timestamp, and the bytes used, as described in the `FrameMetadata`_ documentation. .. _FrameMetaData: https://libcamera.org/api-html/structlibcamera_1_1FrameMetadata.html .. code:: cpp for (auto bufferPair : buffers) { FrameBuffer *buffer = bufferPair.second; const FrameMetadata &metadata = buffer->metadata(); } For this example application, inside the ``for`` loop from above, we can print the Frame sequence number and details of the planes. .. code:: cpp std::cout << " seq: " << std::setw(6) << std::setfill('0') << metadata.sequence << " bytesused: "; unsigned int nplane = 0; for (const FrameMetadata::Plane &plane : metadata.planes()) { std::cout << plane.bytesused; if (++nplane < metadata.planes().size()) std::cout << "/"; } std::cout << std::endl; The expected output shows each monotonically increasing frame sequence number and the bytes used by planes. .. code:: text seq: 000000 bytesused: 1843200 seq: 000002 bytesused: 1843200 seq: 000004 bytesused: 1843200 seq: 000006 bytesused: 1843200 seq: 000008 bytesused: 1843200 seq: 000010 bytesused: 1843200 seq: 000012 bytesused: 1843200 seq: 000014 bytesused: 1843200 seq: 000016 bytesused: 1843200 seq: 000018 bytesused: 1843200 seq: 000020 bytesused: 1843200 seq: 000022 bytesused: 1843200 seq: 000024 bytesused: 1843200 seq: 000026 bytesused: 1843200 seq: 000028 bytesused: 1843200 seq: 000030 bytesused: 1843200 seq: 000032 bytesused: 1843200 seq: 000034 bytesused: 1843200 seq: 000036 bytesused: 1843200 seq: 000038 bytesused: 1843200 seq: 000040 bytesused: 1843200 seq: 000042 bytesused: 1843200 A completed buffer contains of course image data which can be accessed through the per-plane dma-buf file descriptor transported by the ``FrameBuffer`` instance. An example of how to write image data to disk is available in the `FileSink class`_ which is a part of the ``cam`` utility application in the libcamera repository. .. _FileSink class: https://git.libcamera.org/libcamera/libcamera.git/tree/src/cam/file_sink.cpp With the handling of this request completed, it is possible to re-use the request and the associated buffers and re-queue it to the camera device: .. code:: cpp request->reuse(Request::ReuseBuffers); camera->queueRequest(request); Request queueing ---------------- The ``Camera`` device is now ready to receive frame capture requests and actually start delivering frames. In order to prepare for that, an application needs to first start the camera, and queue requests to it for them to be processed. In the main() function, just after having connected the ``Camera::requestCompleted`` signal to the callback handler, start the camera and queue all the previously created requests. .. code:: cpp camera->start(); for (std::unique_ptr &request : requests) camera->queueRequest(request.get()); Event processing ~~~~~~~~~~~~~~~~ libcamera creates an internal execution thread at `CameraManager::start()`_ time to decouple its own event processing from the application's main thread. Applications are thus free to manage their own execution opportunely, and only need to respond to events generated by libcamera emitted through signals. .. _CameraManager::start(): https://libcamera.org/api-html/classlibcamera_1_1CameraManager.html#a49e322880a2a26013bb0076788b298c5 Real-world applications will likely either integrate with the event loop of the framework they use, or create their own event loop to respond to user events. For the simple application presented in this example, it is enough to prevent immediate termination by pausing for 3 seconds. During that time, the libcamera thread will generate request completion events that the application will handle in the ``requestComplete()`` slot connected to the ``Camera::requestCompleted`` signal. .. code:: cpp std::this_thread::sleep_for(3000ms); Clean up and stop the application --------------------------------- The application is now finished with the camera and the resources the camera uses, so needs to do the following: - stop the camera - free the buffers in the FrameBufferAllocator and delete it - release the lock on the camera and reset the pointer to it - stop the camera manager .. code:: cpp camera->stop(); allocator->free(stream); delete allocator; camera->release(); camera.reset(); cm->stop(); return 0; In this instance the CameraManager will automatically be deleted by the unique_ptr implementation when it goes out of scope. Build and run instructions -------------------------- To build the application, we recommend that you use the `Meson build system`_ which is also the official build system of the libcamera library. Make sure both ``meson`` and ``libcamera`` are installed in your system. Please refer to your distribution documentation to install meson and install the most recent version of libcamera from the `git repository`_. You would also need to install the ``pkg-config`` tool to correctly identify the libcamera.so object install location in the system. .. _Meson build system: https://mesonbuild.com/ .. _git repository: https://git.libcamera.org/libcamera/libcamera.git/ Dependencies ~~~~~~~~~~~~ The test application presented here depends on the libcamera library to be available in a path that meson can identify. The libcamera install procedure performed using the ``ninja install`` command may by default deploy the libcamera components in the ``/usr/local/lib`` path, or a package manager may install it to ``/usr/lib`` depending on your distribution. If meson is unable to find the location of the libcamera installation, you may need to instruct meson to look into a specific path when searching for ``libcamera.so`` by setting the ``PKG_CONFIG_PATH`` environment variable to the right location. Adjust the following command to use the ``pkgconfig`` directory where libcamera has been installed in your system. .. code:: shell export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig/ Verify that ``pkg-config`` can identify the ``libcamera`` library with .. code:: shell $ pkg-config --libs --cflags libcamera -I/usr/local/include/libcamera -L/usr/local/lib -lcamera -lcamera-base ``meson`` can alternatively use ``cmake`` to locate packages, please refer to the ``meson`` documentation if you prefer to use it in place of ``pkgconfig`` Build file ~~~~~~~~~~ With the dependencies correctly identified, prepare a ``meson.build`` build file to be placed in the same directory where the application lives. You can name your application as you like, but be sure to update the following snippet accordingly. In this example, the application file has been named ``simple-cam.cpp``. .. code:: project('simple-cam', 'cpp') simple_cam = executable('simple-cam', 'simple-cam.cpp', dependencies: dependency('libcamera', required : true)) The ``dependencies`` line instructs meson to ask ``pkgconfig`` (or ``cmake``) to locate the ``libcamera`` library, which the test application will be dynamically linked against. With the build file in place, compile and run the application with: .. code:: shell $ meson build $ cd build $ ninja $ ./simple-cam It is possible to increase the library debug output by using environment variables which control the library log filtering system: .. code:: shell $ LIBCAMERA_LOG_LEVELS=0 ./simple-cam 2' href='#n562'>562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2019, Google Inc.
 *
 * controls.cpp - Control handling
 */

#include <libcamera/controls.h>

#include <iomanip>
#include <sstream>
#include <string>

#include "control_validator.h"
#include "log.h"
#include "utils.h"

/**
 * \file controls.h
 * \brief Framework to manage controls related to an object
 *
 * A control is a mean to govern or influence the operation of an object, and in
 * particular of a camera. Every control is defined by a unique numerical ID, a
 * name string and the data type of the value it stores. The libcamera API
 * defines a set of standard controls in the libcamera::controls namespace, as
 * a set of instances of the Control class.
 *
 * The main way for applications to interact with controls is through the
 * ControlList stored in the Request class:
 *
 * \code{.cpp}
 * Request *req = ...;
 * ControlList &controls = req->controls();
 * controls->set(controls::AwbEnable, false);
 * controls->set(controls::ManualExposure, 1000);
 *
 * ...
 *
 * int32_t exposure = controls->get(controls::ManualExposure);
 * \endcode
 *
 * The ControlList::get() and ControlList::set() methods automatically deduce
 * the data type based on the control.
 */

namespace libcamera {

LOG_DEFINE_CATEGORY(Controls)

/**
 * \enum ControlType
 * \brief Define the data type of a Control
 * \var ControlTypeNone
 * Invalid type, for empty values
 * \var ControlTypeBool
 * The control stores a boolean value
 * \var ControlTypeInteger32
 * The control stores a 32-bit integer value
 * \var ControlTypeInteger64
 * The control stores a 64-bit integer value
 */

/**
 * \class ControlValue
 * \brief Abstract type representing the value of a control
 */

/**
 * \brief Construct an empty ControlValue.
 */
ControlValue::ControlValue()
	: type_(ControlTypeNone)
{
}

/**
 * \brief Construct a Boolean ControlValue
 * \param[in] value Boolean value to store
 */
ControlValue::ControlValue(bool value)
	: type_(ControlTypeBool), bool_(value)
{
}

/**
 * \brief Construct an integer ControlValue
 * \param[in] value Integer value to store
 */
ControlValue::ControlValue(int32_t value)
	: type_(ControlTypeInteger32), integer32_(value)
{
}

/**
 * \brief Construct a 64 bit integer ControlValue
 * \param[in] value Integer value to store
 */
ControlValue::ControlValue(int64_t value)
	: type_(ControlTypeInteger64), integer64_(value)
{
}

/**
 * \fn ControlValue::type()
 * \brief Retrieve the data type of the value
 * \return The value data type
 */

/**
 * \fn ControlValue::isNone()
 * \brief Determine if the value is not initialised
 * \return True if the value type is ControlTypeNone, false otherwise
 */

/**
 * \fn template<typename T> const T &ControlValue::get() const
 * \brief Get the control value
 *
 * The control value type shall match the type T, otherwise the behaviour is
 * undefined.
 *
 * \return The control value
 */

/**
 * \fn template<typename T> void ControlValue::set(const T &value)
 * \brief Set the control value to \a value
 * \param[in] value The control value
 */

#ifndef __DOXYGEN__
template<>
const bool &ControlValue::get<bool>() const
{
	ASSERT(type_ == ControlTypeBool);

	return bool_;
}

template<>
const int32_t &ControlValue::get<int32_t>() const
{
	ASSERT(type_ == ControlTypeInteger32 || type_ == ControlTypeInteger64);

	return integer32_;
}

template<>
const int64_t &ControlValue::get<int64_t>() const
{
	ASSERT(type_ == ControlTypeInteger32 || type_ == ControlTypeInteger64);

	return integer64_;
}

template<>
void ControlValue::set<bool>(const bool &value)
{
	type_ = ControlTypeBool;
	bool_ = value;
}

template<>
void ControlValue::set<int32_t>(const int32_t &value)
{
	type_ = ControlTypeInteger32;
	integer32_ = value;
}

template<>
void ControlValue::set<int64_t>(const int64_t &value)
{
	type_ = ControlTypeInteger64;
	integer64_ = value;
}
#endif /* __DOXYGEN__ */

/**
 * \brief Assemble and return a string describing the value
 * \return A string describing the ControlValue
 */
std::string ControlValue::toString() const
{
	switch (type_) {
	case ControlTypeNone:
		return "<None>";
	case ControlTypeBool:
		return bool_ ? "True" : "False";
	case ControlTypeInteger32:
		return std::to_string(integer32_);
	case ControlTypeInteger64:
		return std::to_string(integer64_);
	}

	return "<ValueType Error>";
}

/**
 * \brief Compare ControlValue instances for equality
 * \return True if the values have identical types and values, false otherwise
 */
bool ControlValue::operator==(const ControlValue &other) const
{
	if (type_ != other.type_)
		return false;

	switch (type_) {
	case ControlTypeBool:
		return bool_ == other.bool_;
	case ControlTypeInteger32:
		return integer32_ == other.integer32_;
	case ControlTypeInteger64:
		return integer64_ == other.integer64_;
	default:
		return false;
	}
}

/**
 * \fn bool ControlValue::operator!=()
 * \brief Compare ControlValue instances for non equality
 * \return False if the values have identical types and values, true otherwise
 */

/**
 * \class ControlId
 * \brief Control static metadata
 *
 * The ControlId class stores a control ID, name and data type. It provides
 * unique identification of a control, but without support for compile-time
 * type deduction that the derived template Control class supports. See the
 * Control class for more information.
 */

/**
 * \fn ControlId::ControlId(unsigned int id, const std::string &name, ControlType type)
 * \brief Construct a ControlId instance
 * \param[in] id The control numerical ID
 * \param[in] name The control name
 * \param[in] type The control data type
 */

/**
 * \fn unsigned int ControlId::id() const
 * \brief Retrieve the control numerical ID
 * \return The control numerical ID
 */

/**
 * \fn const char *ControlId::name() const
 * \brief Retrieve the control name
 * \return The control name
 */

/**
 * \fn ControlType ControlId::type() const
 * \brief Retrieve the control data type
 * \return The control data type
 */

/**
 * \fn bool operator==(const ControlId &lhs, const ControlId &rhs)
 * \brief Compare two ControlId instances for equality
 * \param[in] lhs Left-hand side ControlId
 * \param[in] rhs Right-hand side ControlId
 *
 * ControlId instances are compared based on the numerical ControlId::id()
 * only, as an object may not have two separate controls with the same
 * numerical ID.
 *
 * \return True if \a lhs and \a rhs have equal control IDs, false otherwise
 */

/**
 * \class Control
 * \brief Describe a control and its intrinsic properties
 *
 * The Control class models a control exposed by an object. Its template type
 * name T refers to the control data type, and allows methods that operate on
 * control values to be defined as template methods using the same type T for
 * the control value. See for instance how the ControlList::get() method
 * returns a value corresponding to the type of the requested control.
 *
 * While this class is the main mean to refer to a control, the control
 * identifying information are stored in the non-template base ControlId class.
 * This allows code that operates on a set of controls of different types to
 * reference those controls through a ControlId instead of a Control. For
 * instance, the list of controls supported by a camera is exposed as ControlId
 * instead of Control.
 *
 * Controls of any type can be defined through template specialisation, but
 * libcamera only supports the bool, int32_t and int64_t types natively (this
 * includes types that are equivalent to the supported types, such as int and
 * long int).
 *
 * Controls IDs shall be unique. While nothing prevents multiple instances of
 * the Control class to be created with the same ID for the same object, doing
 * so may cause undefined behaviour.
 */

/**
 * \fn Control::Control(unsigned int id, const char *name)
 * \brief Construct a Control instance
 * \param[in] id The control numerical ID
 * \param[in] name The control name
 *
 * The control data type is automatically deduced from the template type T.
 */

/**
 * \typedef Control::type
 * \brief The Control template type T
 */

#ifndef __DOXYGEN__
template<>
Control<void>::Control(unsigned int id, const char *name)
	: ControlId(id, name, ControlTypeNone)
{
}

template<>
Control<bool>::Control(unsigned int id, const char *name)
	: ControlId(id, name, ControlTypeBool)
{
}

template<>
Control<int32_t>::Control(unsigned int id, const char *name)
	: ControlId(id, name, ControlTypeInteger32)
{
}

template<>
Control<int64_t>::Control(unsigned int id, const char *name)
	: ControlId(id, name, ControlTypeInteger64)
{
}
#endif /* __DOXYGEN__ */

/**
 * \class ControlRange
 * \brief Describe the limits of valid values for a Control
 *
 * The ControlRange expresses the constraints on valid values for a control.
 * The constraints depend on the object the control applies to, and are
 * constant for the lifetime of that object. They are typically constructed by
 * pipeline handlers to describe the controls they support.
 */

/**
 * \brief Construct a ControlRange with minimum and maximum range parameters
 * \param[in] min The control minimum value
 * \param[in] max The control maximum value
 */
ControlRange::ControlRange(const ControlValue &min,
			   const ControlValue &max)
	: min_(min), max_(max)
{
}

/**
 * \fn ControlRange::min()
 * \brief Retrieve the minimum value of the control
 * \return A ControlValue with the minimum value for the control
 */

/**
 * \fn ControlRange::max()
 * \brief Retrieve the maximum value of the control
 * \return A ControlValue with the maximum value for the control
 */

/**
 * \brief Provide a string representation of the ControlRange
 */
std::string ControlRange::toString() const
{
	std::stringstream ss;

	ss << "[" << min_.toString() << ".." << max_.toString() << "]";

	return ss.str();
}

/**
 * \typedef ControlIdMap
 * \brief A map of numerical control ID to ControlId
 *
 * The map is used by ControlList instances to access controls by numerical
 * IDs. A global map of all libcamera controls is provided by
 * controls::controls.
 */

/**
 * \class ControlInfoMap
 * \brief A map of ControlId to ControlRange
 *
 * The ControlInfoMap class describes controls supported by an object as an
 * unsorted map of ControlId pointers to ControlRange instances. Unlike the
 * standard std::unsorted_map<> class, it is designed the be immutable once
 * constructed, and thus only exposes the read accessors of the
 * std::unsorted_map<> base class.
 *
 * In addition to the features of the standard unsorted map, this class also
 * provides access to the mapped elements using numerical ID keys. It maintains
 * an internal map of numerical ID to ControlId for this purpose, and exposes it
 * through the idmap() method to help construction of ControlList instances.
 */

/**
 * \typedef ControlInfoMap::Map
 * \brief The base std::unsorted_map<> container
 */

/**
 * \fn ControlInfoMap::ControlInfoMap(const ControlInfoMap &other)
 * \brief Copy constructor, construct a ControlInfoMap from a copy of \a other
 * \param[in] other The other ControlInfoMap
 */

/**
 * \brief Construct a ControlInfoMap from an initializer list
 * \param[in] init The initializer list
 */
ControlInfoMap::ControlInfoMap(std::initializer_list<Map::value_type> init)
	: Map(init)
{
	generateIdmap();
}

/**
 * \fn ControlInfoMap &ControlInfoMap::operator=(const ControlInfoMap &other)
 * \brief Copy assignment operator, replace the contents with a copy of \a other
 * \param[in] other The other ControlInfoMap
 * \return A reference to the ControlInfoMap
 */

/**
 * \brief Replace the contents with those from the initializer list
 * \param[in] init The initializer list
 * \return A reference to the ControlInfoMap
 */
ControlInfoMap &ControlInfoMap::operator=(std::initializer_list<Map::value_type> init)
{
	Map::operator=(init);
	generateIdmap();
	return *this;
}

/**
 * \brief Move assignment operator from a plain map
 * \param[in] info The control info plain map
 *
 * Populate the map by replacing its contents with those of \a info using move
 * semantics. Upon return the \a info map will be empty.
 *
 * \return A reference to the populated ControlInfoMap
 */
ControlInfoMap &ControlInfoMap::operator=(Map &&info)
{
	Map::operator=(std::move(info));
	generateIdmap();
	return *this;
}

/**
 * \brief Access specified element by numerical ID
 * \param[in] id The numerical ID
 * \return A reference to the element whose ID is equal to \a id
 */
ControlInfoMap::mapped_type &ControlInfoMap::at(unsigned int id)
{
	return at(idmap_.at(id));
}

/**
 * \brief Access specified element by numerical ID
 * \param[in] id The numerical ID
 * \return A const reference to the element whose ID is equal to \a id
 */
const ControlInfoMap::mapped_type &ControlInfoMap::at(unsigned int id) const
{
	return at(idmap_.at(id));
}

/**
 * \brief Count the number of elements matching a numerical ID
 * \param[in] id The numerical ID
 * \return The number of elements matching the numerical \a id
 */
ControlInfoMap::size_type ControlInfoMap::count(unsigned int id) const
{
	return count(idmap_.at(id));
}

/**
 * \brief Find the element matching a numerical ID
 * \param[in] id The numerical ID
 * \return An iterator pointing to the element matching the numerical \a id, or
 * end() if no such element exists
 */
ControlInfoMap::iterator ControlInfoMap::find(unsigned int id)
{
	return find(idmap_.at(id));
}

/**
 * \brief Find the element matching a numerical ID
 * \param[in] id The numerical ID
 * \return A const iterator pointing to the element matching the numerical
 * \a id, or end() if no such element exists
 */
ControlInfoMap::const_iterator ControlInfoMap::find(unsigned int id) const
{
	return find(idmap_.at(id));
}

/**
 * \fn const ControlIdMap &ControlInfoMap::idmap() const
 * \brief Retrieve the ControlId map
 *
 * Constructing ControlList instances for V4L2 controls requires a ControlIdMap
 * for the V4L2 device that the control list targets. This helper method
 * returns a suitable idmap for that purpose.
 *
 * \return The ControlId map
 */

void ControlInfoMap::generateIdmap()
{
	idmap_.clear();
	for (const auto &ctrl : *this)
		idmap_[ctrl.first->id()] = ctrl.first;
}

/**
 * \class ControlList
 * \brief Associate a list of ControlId with their values for an object
 *
 * The ControlList class stores values of controls exposed by an object. The
 * lists returned by the Request::controls() and Request::metadata() methods
 * refer to the camera that the request belongs to.
 *
 * Control lists are constructed with a map of all the controls supported by
 * their object, and an optional ControlValidator to further validate the
 * controls.
 */

/**
 * \brief Construct a ControlList with an optional control validator
 * \param[in] idmap The ControlId map for the control list target object
 * \param[in] validator The validator (may be null)
 *
 * For ControlList containing libcamera controls, a global map of all libcamera
 * controls is provided by controls::controls and can be used as the \a idmap
 * argument.
 */
ControlList::ControlList(const ControlIdMap &idmap, ControlValidator *validator)
	: validator_(validator), idmap_(&idmap)
{
}

/**
 * \brief Construct a ControlList with the idmap of a control info map
 * \param[in] info The ControlInfoMap for the control list target object
 * \param[in] validator The validator (may be null)
 */
ControlList::ControlList(const ControlInfoMap &info, ControlValidator *validator)
	: validator_(validator), idmap_(&info.idmap())
{
}

/**
 * \typedef ControlList::iterator
 * \brief Iterator for the controls contained within the list
 */

/**
 * \typedef ControlList::const_iterator
 * \brief Const iterator for the controls contained within the list
 */

/**
 * \fn iterator ControlList::begin()
 * \brief Retrieve an iterator to the first Control in the list
 * \return An iterator to the first Control in the list
 */

/**
 * \fn const_iterator ControlList::begin() const
 * \brief Retrieve a const_iterator to the first Control in the list
 * \return A const_iterator to the first Control in the list
 */

/**
 * \fn iterator ControlList::end()
 * \brief Retrieve an iterator pointing to the past-the-end control in the list
 * \return An iterator to the element following the last control in the list
 */

/**
 * \fn const_iterator ControlList::end() const
 * \brief Retrieve a const iterator pointing to the past-the-end control in the
 * list
 * \return A const iterator to the element following the last control in the
 * list
 */

/**
 * \fn ControlList::empty()
 * \brief Identify if the list is empty
 * \return True if the list does not contain any control, false otherwise
 */

/**
 * \fn ControlList::size()
 * \brief Retrieve the number of controls in the list
 * \return The number of Control entries stored in the list
 */

/**
 * \fn ControlList::clear()
 * \brief Removes all controls from the list
 */

/**
 * \brief Check if the list contains a control with the specified \a id
 * \param[in] id The control ID
 *
 * \return True if the list contains a matching control, false otherwise
 */
bool ControlList::contains(const ControlId &id) const
{
	return controls_.find(&id) != controls_.end();
}

/**
 * \brief Check if the list contains a control with the specified \a id
 * \param[in] id The control numerical ID
 *
 * \return True if the list contains a matching control, false otherwise
 */
bool ControlList::contains(unsigned int id) const
{
	const auto iter = idmap_->find(id);
	if (iter == idmap_->end())
		return false;

	return contains(*iter->second);
}

/**
 * \fn template<typename T> const T &ControlList::get(const Control<T> &ctrl) const
 * \brief Get the value of control \a ctrl
 * \param[in] ctrl The control
 *
 * The behaviour is undefined if the control \a ctrl is not present in the
 * list. Use ControlList::contains() to test for the presence of a control in
 * the list before retrieving its value.
 *
 * The control value type shall match the type T, otherwise the behaviour is
 * undefined.
 *
 * \return The control value
 */

/**
 * \fn template<typename T> void ControlList::set(const Control<T> &ctrl, const T &value)
 * \brief Set the control \a ctrl value to \a value
 * \param[in] ctrl The control
 * \param[in] value The control value
 *
 * This method sets the value of a control in the control list. If the control
 * is already present in the list, its value is updated, otherwise it is added
 * to the list.
 *
 * The behaviour is undefined if the control \a ctrl is not supported by the
 * object that the list refers to.
 */

/**
 * \brief Get the value of control \a id
 * \param[in] id The control numerical ID
 *
 * The behaviour is undefined if the control \a id is not present in the list.
 * Use ControlList::contains() to test for the presence of a control in the
 * list before retrieving its value.
 *
 * \return The control value
 */
const ControlValue &ControlList::get(unsigned int id) const
{
	static ControlValue zero;

	const auto ctrl = idmap_->find(id);
	if (ctrl == idmap_->end()) {
		LOG(Controls, Error)
			<< "Control " << utils::hex(id)
			<< " is not supported";
		return zero;
	}

	const ControlValue *val = find(*ctrl->second);
	if (!val)
		return zero;

	return *val;
}

/**
 * \brief Set the value of control \a id to \a value
 * \param[in] id The control ID
 * \param[in] value The control value
 *
 * This method sets the value of a control in the control list. If the control
 * is already present in the list, its value is updated, otherwise it is added
 * to the list.
 *
 * The behaviour is undefined if the control \a id is not supported by the
 * object that the list refers to.
 */
void ControlList::set(unsigned int id, const ControlValue &value)
{
	const auto ctrl = idmap_->find(id);
	if (ctrl == idmap_->end()) {
		LOG(Controls, Error)
			<< "Control 0x" << utils::hex(id)
			<< " is not supported";
		return;
	}

	ControlValue *val = find(*ctrl->second);
	if (!val)
		return;

	*val = value;
}

const ControlValue *ControlList::find(const ControlId &id) const
{
	const auto iter = controls_.find(&id);
	if (iter == controls_.end()) {
		LOG(Controls, Error)
			<< "Control " << id.name() << " not found";

		return nullptr;
	}

	return &iter->second;
}

ControlValue *ControlList::find(const ControlId &id)
{
	if (validator_ && !validator_->validate(id)) {
		LOG(Controls, Error)
			<< "Control " << id.name()
			<< " is not valid for " << validator_->name();
		return nullptr;
	}

	return &controls_[&id];
}

} /* namespace libcamera */