summaryrefslogtreecommitdiff
path: root/src/libcamera/device_enumerator.cpp
diff options
context:
space:
mode:
authorLaurent Pinchart <laurent.pinchart@ideasonboard.com>2018-12-31 09:29:47 +0200
committerLaurent Pinchart <laurent.pinchart@ideasonboard.com>2019-01-04 00:23:30 +0200
commit1e04362d6e1013bd95340fb01cdb68bd90387f25 (patch)
treeca4d74e48f59961b4becc938ae3018cbe9acfa22 /src/libcamera/device_enumerator.cpp
parenta87cb586e2f71a14e92326a7f85009bd8722ff98 (diff)
libcamera: device_enumerator: Improve documentation
Miscellaneous documentation improvements for the DeviceEnumerator and related classes. Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com> Reviewed-by: Jacopo Mondi <jacopo@jmondi.org> Reviewed-by: Niklas Söderlund <niklas.soderlund@ragnatech.se>
Diffstat (limited to 'src/libcamera/device_enumerator.cpp')
-rw-r--r--src/libcamera/device_enumerator.cpp166
1 files changed, 88 insertions, 78 deletions
diff --git a/src/libcamera/device_enumerator.cpp b/src/libcamera/device_enumerator.cpp
index a301420f..7ad1c501 100644
--- a/src/libcamera/device_enumerator.cpp
+++ b/src/libcamera/device_enumerator.cpp
@@ -17,27 +17,25 @@
/**
* \file device_enumerator.h
- * \brief Enumerating and matching of media devices
+ * \brief Enumeration and matching of media devices
*
- * The purpose of device enumeration and matching is to find media
- * devices in the system and map one or more media devices to a pipeline
- * handler. During enumeration information about each media device is
- * gathered, transformed and stored.
+ * The purpose of device enumeration and matching is to find media devices in
+ * the system and map them to pipeline handlers.
*
- * The core of the enumeration is DeviceEnumerator which is responsible
- * for all interactions with the operating system and the entry point
- * for other parts of libcamera.
+ * 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
+ * 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 last functionality provided is the ability to search among the
- * enumerate media devices for one matching information known to the
- * searcher. This is done by populating and passing a DeviceMatch object
- * to the DeviceEnumerator.
+ * The enumerator supports searching among enumerated devices based on criteria
+ * expressed in a DeviceMatch object.
*
- * \todo Add sysfs based device enumerator
+ * \todo Add sysfs based device enumerator.
* \todo Add support for hot-plug and hot-unplug.
*/
@@ -47,18 +45,17 @@ namespace libcamera {
* \class DeviceMatch
* \brief Description of a media device search pattern
*
- * The DeviceMatch class describes a media device using properties from
- * the v4l2 struct media_device_info, entity names in the media graph or
- * other properties which can be used to identify a media device.
+ * 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 of a media device can then be passed to an enumerator
- * to try and find a matching media device.
+ * The description is meant to be filled by pipeline managers and passed to a
+ * device enumerator to find matching media devices.
*/
/**
* \brief Construct a media device search pattern
- *
- * \param[in] driver The Linux device driver name who created the media device
+ * \param[in] driver The Linux device driver name that created the media device
*/
DeviceMatch::DeviceMatch(const std::string &driver)
: driver_(driver)
@@ -67,7 +64,6 @@ DeviceMatch::DeviceMatch(const std::string &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)
@@ -79,8 +75,9 @@ void DeviceMatch::add(const std::string &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.
+ * 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
*/
@@ -108,43 +105,44 @@ bool DeviceMatch::match(const MediaDevice *device) const
/**
* \class DeviceEnumerator
- * \brief Enumerate, interrogate, store and search media device information
- *
- * The DeviceEnumerator class is responsible for all interactions with
- * the operation system when searching and interrogating media devices.
+ * \brief Enumerate, store and search media devices
*
- * It is possible to automatically search and add all media devices in
- * the system or specify which media devices should be interrogated
- * in order for a specialized application to open as few resources
- * as possible to get hold of a specific camera.
- *
- * Once one or many media devices have been enumerated it is possible
- * to search among them to try and find a matching device using a
- * DeviceMatch object.
+ * 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
*
- * Create a enumerator based on resource available to the system. Not all
- * different enumerator types are guaranteed to support all features.
+ * 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.
*/
DeviceEnumerator *DeviceEnumerator::create()
{
DeviceEnumerator *enumerator;
- /* TODO: add compile time checks to only try udev enumerator if libudev is available */
+ /**
+ * \todo Add compile time checks to only try udev enumerator if libudev
+ * is available.
+ */
enumerator = new DeviceEnumeratorUdev();
if (!enumerator->init())
return enumerator;
/*
- * NOTE: Either udev is not available or initialization of it
- * failed, use/fallback on sysfs enumerator
+ * Either udev is not available or udev initialization failed. Fall back
+ * on the sysfs enumerator.
*/
- /* TODO: add a sysfs based enumerator */
+ /** \todo Add a sysfs-based enumerator. */
return nullptr;
}
@@ -160,13 +158,38 @@ DeviceEnumerator::~DeviceEnumerator()
}
/**
- * \brief Add a media device to the enumerator
+ * \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.
*
+ * \return 0 on success, or a negative error code on fatal errors.
+ */
+
+/**
+ * \brief Add a media device to the enumerator
* \param[in] devnode path to the media device to add
*
- * Opens the media device and quires its topology and other information.
+ * Create a media device for the \a devnode, open it, populate its media graph,
+ * and look up device nodes associated with all entities. Store the media device
+ * in the internal list for later matching with pipeline handlers.
*
- * \return 0 on success none zero otherwise
+ * \return 0 on success, or a negative error code if the media device can't be
+ * created or populated
*/
int DeviceEnumerator::addDevice(const std::string &devnode)
{
@@ -205,15 +228,14 @@ int DeviceEnumerator::addDevice(const std::string &devnode)
/**
* \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 to mark the MediaDevice
- * object as in use and to release it when it's done with it.
+ * 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, nullptr if no match is found
+ * \return pointer to the matching MediaDevice, or nullptr if no match is found
*/
MediaDevice *DeviceEnumerator::search(const DeviceMatch &dm) const
{
@@ -229,10 +251,21 @@ MediaDevice *DeviceEnumerator::search(const DeviceMatch &dm) const
}
/**
- * \class DeviceEnumeratorUdev
- * \brief Udev implementation of device enumeration
+ * \fn DeviceEnumerator::lookupDevnode(int major, int minor)
+ * \brief Lookup device node path from device number
+ * \param major The device major number
+ * \param minor The device minor number
*
- * Implementation of system enumeration functions using libudev.
+ * Translate a device number given as \a major and \a minor to a device node
+ * path.
+ *
+ * \return the device node path on success, or an empty string if the lookup
+ * fails
+ */
+
+/**
+ * \class DeviceEnumeratorUdev
+ * \brief Device enumerator based on libudev
*/
DeviceEnumeratorUdev::DeviceEnumeratorUdev()
@@ -246,13 +279,6 @@ DeviceEnumeratorUdev::~DeviceEnumeratorUdev()
udev_unref(udev_);
}
-/**
- * \brief Initialize the enumerator
- *
- * \retval 0 Initialized
- * \retval -EBUSY Busy (already initialized)
- * \retval -ENODEV Failed to talk to udev
- */
int DeviceEnumeratorUdev::init()
{
if (udev_)
@@ -265,14 +291,6 @@ int DeviceEnumeratorUdev::init()
return 0;
}
-/**
- * \brief Enumerate all media devices using udev
- *
- * Find, enumerate and add all media devices in the system to the
- * enumerator.
- *
- * \return 0 on success none zero otherwise
- */
int DeviceEnumeratorUdev::enumerate()
{
struct udev_enumerate *udev_enum = nullptr;
@@ -323,14 +341,6 @@ done:
return ret >= 0 ? 0 : ret;
}
-/**
- * \brief Lookup device node from device number using udev
- *
- * Translate a device number (major, minor) to a device node path.
- *
- * \return device node path or empty string if lookup fails.
- *
- */
std::string DeviceEnumeratorUdev::lookupDevnode(int major, int minor)
{
struct udev_device *device;
ef='#n653'>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 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
/* SPDX-License-Identifier: BSD-2-Clause */
/*
 * Copyright (C) 2019-2020, Raspberry Pi (Trading) Ltd.
 *
 * rpi.cpp - Raspberry Pi Image Processing Algorithms
 */

#include <algorithm>
#include <fcntl.h>
#include <math.h>
#include <stdint.h>
#include <string.h>
#include <sys/mman.h>

#include <libcamera/buffer.h>
#include <libcamera/control_ids.h>
#include <libcamera/controls.h>
#include <libcamera/ipa/ipa_interface.h>
#include <libcamera/ipa/ipa_module_info.h>
#include <libcamera/ipa/raspberrypi.h>
#include <libcamera/request.h>
#include <libcamera/span.h>

#include <libipa/ipa_interface_wrapper.h>

#include "libcamera/internal/camera_sensor.h"
#include "libcamera/internal/log.h"
#include "libcamera/internal/utils.h"

#include <linux/bcm2835-isp.h>

#include "agc_algorithm.hpp"
#include "agc_status.h"
#include "alsc_status.h"
#include "awb_algorithm.hpp"
#include "awb_status.h"
#include "black_level_status.h"
#include "cam_helper.hpp"
#include "ccm_algorithm.hpp"
#include "ccm_status.h"
#include "contrast_algorithm.hpp"
#include "contrast_status.h"
#include "controller.hpp"
#include "dpc_status.h"
#include "focus_status.h"
#include "geq_status.h"
#include "lux_status.h"
#include "metadata.hpp"
#include "noise_status.h"
#include "sdn_status.h"
#include "sharpen_algorithm.hpp"
#include "sharpen_status.h"

namespace libcamera {

/* Configure the sensor with these values initially. */
#define DEFAULT_ANALOGUE_GAIN 1.0
#define DEFAULT_EXPOSURE_TIME 20000

LOG_DEFINE_CATEGORY(IPARPI)

class IPARPi : public IPAInterface
{
public:
	IPARPi()
		: lastMode_({}), controller_(), controllerInit_(false),
		  frame_count_(0), check_count_(0), hide_count_(0),
		  mistrust_count_(0), lsTableHandle_(0), lsTable_(nullptr)
	{
	}

	~IPARPi()
	{
	}

	int init(const IPASettings &settings) override;
	int start() override { return 0; }
	void stop() override {}

	void configure(const CameraSensorInfo &sensorInfo,
		       const std::map<unsigned int, IPAStream> &streamConfig,
		       const std::map<unsigned int, const ControlInfoMap &> &entityControls) override;
	void mapBuffers(const std::vector<IPABuffer> &buffers) override;
	void unmapBuffers(const std::vector<unsigned int> &ids) override;
	void processEvent(const IPAOperationData &event) override;

private:
	void setMode(const CameraSensorInfo &sensorInfo);
	void queueRequest(const ControlList &controls);
	void returnEmbeddedBuffer(unsigned int bufferId);
	void prepareISP(unsigned int bufferId);
	void reportMetadata();
	bool parseEmbeddedData(unsigned int bufferId, struct DeviceStatus &deviceStatus);
	void processStats(unsigned int bufferId);
	void applyAGC(const struct AgcStatus *agcStatus);
	void applyAWB(const struct AwbStatus *awbStatus, ControlList &ctrls);
	void applyDG(const struct AgcStatus *dgStatus, ControlList &ctrls);
	void applyCCM(const struct CcmStatus *ccmStatus, ControlList &ctrls);
	void applyBlackLevel(const struct BlackLevelStatus *blackLevelStatus, ControlList &ctrls);
	void applyGamma(const struct ContrastStatus *contrastStatus, ControlList &ctrls);
	void applyGEQ(const struct GeqStatus *geqStatus, ControlList &ctrls);
	void applyDenoise(const struct SdnStatus *denoiseStatus, ControlList &ctrls);
	void applySharpen(const struct SharpenStatus *sharpenStatus, ControlList &ctrls);
	void applyDPC(const struct DpcStatus *dpcStatus, ControlList &ctrls);
	void applyLS(const struct AlscStatus *lsStatus, ControlList &ctrls);
	void resampleTable(uint16_t dest[], double const src[12][16], int dest_w, int dest_h);

	std::map<unsigned int, FrameBuffer> buffers_;
	std::map<unsigned int, void *> buffersMemory_;

	ControlInfoMap unicam_ctrls_;
	ControlInfoMap isp_ctrls_;
	ControlList libcameraMetadata_;

	/* IPA configuration. */
	std::string tuningFile_;

	/* Camera sensor params. */
	CameraMode mode_;
	CameraMode lastMode_;

	/* Raspberry Pi controller specific defines. */
	std::unique_ptr<RPi::CamHelper> helper_;
	RPi::Controller controller_;
	bool controllerInit_;
	RPi::Metadata rpiMetadata_;

	/*
	 * We count frames to decide if the frame must be hidden (e.g. from
	 * display) or mistrusted (i.e. not given to the control algos).
	 */
	uint64_t frame_count_;
	/* For checking the sequencing of Prepare/Process calls. */
	uint64_t check_count_;
	/* How many frames the pipeline handler should hide, or "drop". */
	unsigned int hide_count_;
	/* How many frames we should avoid running control algos on. */
	unsigned int mistrust_count_;
	/* LS table allocation passed in from the pipeline handler. */
	uint32_t lsTableHandle_;
	void *lsTable_;
};

int IPARPi::init(const IPASettings &settings)
{
	tuningFile_ = settings.configurationFile;
	return 0;
}

void IPARPi::setMode(const CameraSensorInfo &sensorInfo)
{
	mode_.bitdepth = sensorInfo.bitsPerPixel;
	mode_.width = sensorInfo.outputSize.width;
	mode_.height = sensorInfo.outputSize.height;
	mode_.sensor_width = sensorInfo.activeAreaSize.width;
	mode_.sensor_height = sensorInfo.activeAreaSize.height;
	mode_.crop_x = sensorInfo.analogCrop.x;
	mode_.crop_y = sensorInfo.analogCrop.y;

	/*
	 * Calculate scaling parameters. The scale_[xy] factors are determined
	 * by the ratio between the crop rectangle size and the output size.
	 */
	mode_.scale_x = sensorInfo.analogCrop.width / sensorInfo.outputSize.width;
	mode_.scale_y = sensorInfo.analogCrop.height / sensorInfo.outputSize.height;

	/*
	 * We're not told by the pipeline handler how scaling is split between
	 * binning and digital scaling. For now, as a heuristic, assume that
	 * downscaling up to 2 is achieved through binning, and that any
	 * additional scaling is achieved through digital scaling.
	 *
	 * \todo Get the pipeline handle to provide the full data
	 */
	mode_.bin_y = std::min(2, static_cast<int>(mode_.scale_x));
	mode_.bin_y = std::min(2, static_cast<int>(mode_.scale_y));

	/* The noise factor is the square root of the total binning factor. */
	mode_.noise_factor = sqrt(mode_.bin_x * mode_.bin_y);

	/*
	 * Calculate the line length in nanoseconds as the ratio between
	 * the line length in pixels and the pixel rate.
	 */
	mode_.line_length = 1e9 * sensorInfo.lineLength / sensorInfo.pixelRate;
}

void IPARPi::configure(const CameraSensorInfo &sensorInfo,
		       const std::map<unsigned int, IPAStream> &streamConfig,
		       const std::map<unsigned int, const ControlInfoMap &> &entityControls)
{
	if (entityControls.empty())
		return;

	unicam_ctrls_ = entityControls.at(0);
	isp_ctrls_ = entityControls.at(1);
	/* Setup a metadata ControlList to output metadata. */
	libcameraMetadata_ = ControlList(controls::controls);

	/*
	 * Load the "helper" for this sensor. This tells us all the device specific stuff
	 * that the kernel driver doesn't. We only do this the first time; we don't need
	 * to re-parse the metadata after a simple mode-switch for no reason.
	 */
	std::string cameraName(sensorInfo.model);
	if (!helper_) {
		helper_ = std::unique_ptr<RPi::CamHelper>(RPi::CamHelper::Create(cameraName));
		/*
		 * Pass out the sensor config to the pipeline handler in order
		 * to setup the staggered writer class.
		 */
		int gainDelay, exposureDelay, sensorMetadata;
		helper_->GetDelays(exposureDelay, gainDelay);
		sensorMetadata = helper_->SensorEmbeddedDataPresent();
		RPi::CamTransform orientation = helper_->GetOrientation();

		IPAOperationData op;
		op.operation = RPI_IPA_ACTION_SET_SENSOR_CONFIG;
		op.data.push_back(gainDelay);
		op.data.push_back(exposureDelay);
		op.data.push_back(sensorMetadata);

		ControlList ctrls(unicam_ctrls_);
		ctrls.set(V4L2_CID_HFLIP, (int32_t) !!(orientation & RPi::CamTransform_HFLIP));
		ctrls.set(V4L2_CID_VFLIP, (int32_t) !!(orientation & RPi::CamTransform_VFLIP));
		op.controls.push_back(ctrls);

		queueFrameAction.emit(0, op);
	}

	/* Re-assemble camera mode using the sensor info. */
	setMode(sensorInfo);

	/* Pass the camera mode to the CamHelper to setup algorithms. */
	helper_->SetCameraMode(mode_);

	/*
	 * Initialise frame counts, and decide how many frames must be hidden or
	 *"mistrusted", which depends on whether this is a startup from cold,
	 * or merely a mode switch in a running system.
	 */
	frame_count_ = 0;
	check_count_ = 0;
	if (controllerInit_) {
		hide_count_ = helper_->HideFramesModeSwitch();
		mistrust_count_ = helper_->MistrustFramesModeSwitch();
	} else {
		hide_count_ = helper_->HideFramesStartup();
		mistrust_count_ = helper_->MistrustFramesStartup();
	}

	struct AgcStatus agcStatus;
	/* These zero values mean not program anything (unless overwritten). */
	agcStatus.shutter_time = 0.0;
	agcStatus.analogue_gain = 0.0;

	if (!controllerInit_) {
		/* Load the tuning file for this sensor. */
		controller_.Read(tuningFile_.c_str());
		controller_.Initialise();
		controllerInit_ = true;

		/* Supply initial values for gain and exposure. */
		agcStatus.shutter_time = DEFAULT_EXPOSURE_TIME;
		agcStatus.analogue_gain = DEFAULT_ANALOGUE_GAIN;
	}

	RPi::Metadata metadata;
	controller_.SwitchMode(mode_, &metadata);

	/* SwitchMode may supply updated exposure/gain values to use. */
	metadata.Get("agc.status", agcStatus);
	if (agcStatus.shutter_time != 0.0 && agcStatus.analogue_gain != 0.0)
		applyAGC(&agcStatus);

	lastMode_ = mode_;
}

void IPARPi::mapBuffers(const std::vector<IPABuffer> &buffers)
{
	for (const IPABuffer &buffer : buffers) {
		auto elem = buffers_.emplace(std::piecewise_construct,
					     std::forward_as_tuple(buffer.id),
					     std::forward_as_tuple(buffer.planes));
		const FrameBuffer &fb = elem.first->second;

		buffersMemory_[buffer.id] = mmap(nullptr, fb.planes()[0].length,
						 PROT_READ | PROT_WRITE, MAP_SHARED,
						 fb.planes()[0].fd.fd(), 0);

		if (buffersMemory_[buffer.id] == MAP_FAILED) {
			int ret = -errno;
			LOG(IPARPI, Fatal) << "Failed to mmap buffer: " << strerror(-ret);
		}
	}
}

void IPARPi::unmapBuffers(const std::vector<unsigned int> &ids)
{
	for (unsigned int id : ids) {
		const auto fb = buffers_.find(id);
		if (fb == buffers_.end())
			continue;

		munmap(buffersMemory_[id], fb->second.planes()[0].length);
		buffersMemory_.erase(id);
		buffers_.erase(id);
	}
}

void IPARPi::processEvent(const IPAOperationData &event)
{
	switch (event.operation) {
	case RPI_IPA_EVENT_SIGNAL_STAT_READY: {
		unsigned int bufferId = event.data[0];

		if (++check_count_ != frame_count_) /* assert here? */
			LOG(IPARPI, Error) << "WARNING: Prepare/Process mismatch!!!";
		if (frame_count_ > mistrust_count_)
			processStats(bufferId);

		reportMetadata();

		IPAOperationData op;
		op.operation = RPI_IPA_ACTION_STATS_METADATA_COMPLETE;
		op.data = { bufferId & RPiIpaMask::ID };
		op.controls = { libcameraMetadata_ };
		queueFrameAction.emit(0, op);
		break;
	}

	case RPI_IPA_EVENT_SIGNAL_ISP_PREPARE: {
		unsigned int embeddedbufferId = event.data[0];
		unsigned int bayerbufferId = event.data[1];

		/*
		 * At start-up, or after a mode-switch, we may want to
		 * avoid running the control algos for a few frames in case
		 * they are "unreliable".
		 */
		prepareISP(embeddedbufferId);

		/* Ready to push the input buffer into the ISP. */
		IPAOperationData op;
		if (++frame_count_ > hide_count_)
			op.operation = RPI_IPA_ACTION_RUN_ISP;
		else
			op.operation = RPI_IPA_ACTION_RUN_ISP_AND_DROP_FRAME;
		op.data = { bayerbufferId & RPiIpaMask::ID };
		queueFrameAction.emit(0, op);
		break;
	}

	case RPI_IPA_EVENT_QUEUE_REQUEST: {
		queueRequest(event.controls[0]);
		break;
	}

	case RPI_IPA_EVENT_LS_TABLE_ALLOCATION: {
		lsTable_ = reinterpret_cast<void *>(event.data[0]);
		lsTableHandle_ = event.data[1];
		break;
	}

	default:
		LOG(IPARPI, Error) << "Unknown event " << event.operation;
		break;
	}
}

void IPARPi::reportMetadata()
{
	std::unique_lock<RPi::Metadata> lock(rpiMetadata_);

	/*
	 * Certain information about the current frame and how it will be
	 * processed can be extracted and placed into the libcamera metadata
	 * buffer, where an application could query it.
	 */

	DeviceStatus *deviceStatus = rpiMetadata_.GetLocked<DeviceStatus>("device.status");
	if (deviceStatus) {
		libcameraMetadata_.set(controls::ExposureTime, deviceStatus->shutter_speed);
		libcameraMetadata_.set(controls::AnalogueGain, deviceStatus->analogue_gain);
	}

	AgcStatus *agcStatus = rpiMetadata_.GetLocked<AgcStatus>("agc.status");
	if (agcStatus)
		libcameraMetadata_.set(controls::AeLocked, agcStatus->locked);

	LuxStatus *luxStatus = rpiMetadata_.GetLocked<LuxStatus>("lux.status");
	if (luxStatus)
		libcameraMetadata_.set(controls::Lux, luxStatus->lux);

	AwbStatus *awbStatus = rpiMetadata_.GetLocked<AwbStatus>("awb.status");
	if (awbStatus) {
		libcameraMetadata_.set(controls::ColourGains, { static_cast<float>(awbStatus->gain_r),
								static_cast<float>(awbStatus->gain_b) });
		libcameraMetadata_.set(controls::ColourTemperature, awbStatus->temperature_K);
	}

	BlackLevelStatus *blackLevelStatus = rpiMetadata_.GetLocked<BlackLevelStatus>("black_level.status");
	if (blackLevelStatus)
		libcameraMetadata_.set(controls::SensorBlackLevels,
				       { static_cast<int32_t>(blackLevelStatus->black_level_r),
					 static_cast<int32_t>(blackLevelStatus->black_level_g),
					 static_cast<int32_t>(blackLevelStatus->black_level_g),
					 static_cast<int32_t>(blackLevelStatus->black_level_b) });

	FocusStatus *focusStatus = rpiMetadata_.GetLocked<FocusStatus>("focus.status");
	if (focusStatus && focusStatus->num == 12) {
		/*
		 * We get a 4x3 grid of regions by default. Calculate the average
		 * FoM over the central two positions to give an overall scene FoM.
		 * This can change later if it is not deemed suitable.
		 */
		int32_t focusFoM = (focusStatus->focus_measures[5] + focusStatus->focus_measures[6]) / 2;
		libcameraMetadata_.set(controls::FocusFoM, focusFoM);
	}
}

/*
 * Converting between enums (used in the libcamera API) and the names that
 * we use to identify different modes. Unfortunately, the conversion tables
 * must be kept up-to-date by hand.
 */

static const std::map<int32_t, std::string> MeteringModeTable = {
	{ controls::MeteringCentreWeighted, "centre-weighted" },
	{ controls::MeteringSpot, "spot" },
	{ controls::MeteringMatrix, "matrix" },
	{ controls::MeteringCustom, "custom" },
};

static const std::map<int32_t, std::string> ConstraintModeTable = {
	{ controls::ConstraintNormal, "normal" },
	{ controls::ConstraintHighlight, "highlight" },
	{ controls::ConstraintCustom, "custom" },
};

static const std::map<int32_t, std::string> ExposureModeTable = {
	{ controls::ExposureNormal, "normal" },
	{ controls::ExposureShort, "short" },
	{ controls::ExposureLong, "long" },
	{ controls::ExposureCustom, "custom" },
};

static const std::map<int32_t, std::string> AwbModeTable = {
	{ controls::AwbAuto, "normal" },
	{ controls::AwbIncandescent, "incandescent" },
	{ controls::AwbTungsten, "tungsten" },
	{ controls::AwbFluorescent, "fluorescent" },
	{ controls::AwbIndoor, "indoor" },
	{ controls::AwbDaylight, "daylight" },
	{ controls::AwbCustom, "custom" },
};

void IPARPi::queueRequest(const ControlList &controls)
{
	/* Clear the return metadata buffer. */
	libcameraMetadata_.clear();

	for (auto const &ctrl : controls) {
		LOG(IPARPI, Info) << "Request ctrl: "
				  << controls::controls.at(ctrl.first)->name()
				  << " = " << ctrl.second.toString();

		switch (ctrl.first) {
		case controls::AE_ENABLE: {
			RPi::Algorithm *agc = controller_.GetAlgorithm("agc");
			ASSERT(agc);
			if (ctrl.second.get<bool>() == false)
				agc->Pause();
			else
				agc->Resume();

			libcameraMetadata_.set(controls::AeEnable, ctrl.second.get<bool>());
			break;
		}

		case controls::EXPOSURE_TIME: {
			RPi::AgcAlgorithm *agc = dynamic_cast<RPi::AgcAlgorithm *>(
				controller_.GetAlgorithm("agc"));
			ASSERT(agc);
			/* This expects units of micro-seconds. */
			agc->SetFixedShutter(ctrl.second.get<int32_t>());
			/* For the manual values to take effect, AGC must be unpaused. */
			if (agc->IsPaused())
				agc->Resume();