/* SPDX-License-Identifier: BSD-2-Clause */ /* * Copyright (C) 2019, Raspberry Pi (Trading) Limited * * cam_helper.cpp - helper information for different sensors */ #include #include #include #include #include "libcamera/internal/v4l2_videodevice.h" #include "cam_helper.hpp" #include "md_parser.hpp" using namespace RPiController; using namespace libcamera; using libcamera::utils::Duration; namespace libcamera { LOG_DECLARE_CATEGORY(IPARPI) } static std::map cam_helpers; CamHelper *CamHelper::Create(std::string const &cam_name) { /* * CamHelpers get registered by static RegisterCamHelper * initialisers. */ for (auto &p : cam_helpers) { if (cam_name.find(p.first) != std::string::npos) return p.second(); } return nullptr; } CamHelper::CamHelper(std::unique_ptr parser, unsigned int frameIntegrationDiff) : parser_(std::move(parser)), initialized_(false), frameIntegrationDiff_(frameIntegrationDiff) { } CamHelper::~CamHelper() { } void CamHelper::Prepare(Span buffer, Metadata &metadata) { parseEmbeddedData(buffer, metadata); } void CamHelper::Process([[maybe_unused]] StatisticsPtr &stats, [[maybe_unused]] Metadata &metadata) { } uint32_t CamHelper::ExposureLines(const Duration exposure) const { assert(initialized_); return exposure / mode_.line_length; } Duration CamHelper::Exposure(uint32_t exposure_lines) const { assert(initialized_); return exposure_lines * mode_.line_length; } uint32_t CamHelper::GetVBlanking(Duration &exposure, Duration minFrameDuration, Duration maxFrameDuration) const { uint32_t frameLengthMin, frameLengthMax, vblank; uint32_t exposureLines = ExposureLines(exposure); assert(initialized_); /* * minFrameDuration and maxFrameDuration are clamped by the caller * based on the limits for the active sensor mode. */ frameLengthMin = minFrameDuration / mode_.line_length; frameLengthMax = maxFrameDuration / mode_.line_length; /* * Limit the exposure to the maximum frame duration requested, and * re-calculate if it has been clipped. */ exposureLines = std::min(frameLengthMax - frameIntegrationDiff_, exposureLines); exposure = Exposure(exposureLines); /* Limit the vblank to the range allowed by the frame length limits. */ vblank = std::clamp(exposureLines + frameIntegrationDiff_, frameLengthMin, frameLengthMax) - mode_.height; return vblank; } void CamHelper::SetCameraMode(const CameraMode &mode) { mode_ = mode; if (parser_) { parser_->SetBitsPerPixel(mode.bitdepth); parser_->SetLineLengthBytes(0); /* We use SetBufferSize. */ } initialized_ = true; } void CamHelper::GetDelays(int &exposure_delay, int &gain_delay, int &vblank_delay) const { /* * These values are correct for many sensors. Other sensors will * need to over-ride this function. */ exposure_delay = 2; gain_delay = 1; vblank_delay = 2; } bool CamHelper::SensorEmbeddedDataPresent() const { return false; } double CamHelper::GetModeSensitivity([[maybe_unused]] const CameraMode &mode) const { /* * Most sensors have the same sensitivity in every mode, but this * function can be overridden for those that do not. Note that it is * called before mode_ is set, so it must return the sensitivity * of the mode that is passed in. */ return 1.0; } unsigned int CamHelper::HideFramesStartup() const { /* * The number of frames when a camera first starts that shouldn't be * displayed as they are invalid in some way. */ return 0; } unsigned int CamHelper::HideFramesModeSwitch() const { /* After a mode switch, many sensors return valid frames immediately. */ return 0; } unsigned int CamHelper::MistrustFramesStartup() const { /* Many sensors return a single bad frame on start-up. */ return 1; } unsigned int CamHelper::MistrustFramesModeSwitch() const { /* Many sensors return valid metadata immediately. */ return 0; } void CamHelper::parseEmbeddedData(Span buffer, Metadata &metadata) { MdParser::RegisterMap registers; Metadata parsedMetadata; if (buffer.empty()) return; if (parser_->Parse(buffer, registers) != MdParser::Status::OK) { LOG(IPARPI, Error) << "Embedded data buffer parsing failed"; return; } PopulateMetadata(registers, parsedMetadata); metadata.Merge(parsedMetadata); /* * Overwrite the exposure/gain values in the existing DeviceStatus with * values from the parsed embedded buffer. Fetch it first in case any * other fields were set meaningfully. */ DeviceStatus deviceStatus, parsedDeviceStatus; if (metadata.Get("device.status", deviceStatus) || parsedMetadata.Get("device.status", parsedDeviceStatus)) { LOG(IPARPI, Error) << "DeviceStatus not found"; return; } deviceStatus.shutter_speed = parsedDeviceStatus.shutter_speed; deviceStatus.analogue_gain = parsedDeviceStatus.analogue_gain; deviceStatus.frame_length = parsedDeviceStatus.frame_length; LOG(IPARPI, Debug) << "Metadata updated - " << deviceStatus; metadata.Set("device.status", deviceStatus); } void CamHelper::PopulateMetadata([[maybe_unused]] const MdParser::RegisterMap ®isters, [[maybe_unused]] Metadata &metadata) const { } RegisterCamHelper::RegisterCamHelper(char const *cam_name, CamHelperCreateFunc create_func) { cam_helpers[std::string(cam_name)] = create_func; } href='#n64'>64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2021-2022, Ideas On Board
 *
 * dpf.cpp - RkISP1 Denoise Pre-Filter control
 */

#include "dpf.h"

#include <cmath>

#include <libcamera/base/log.h>

#include <libcamera/control_ids.h>

#include "linux/rkisp1-config.h"

/**
 * \file dpf.h
 */

namespace libcamera {

namespace ipa::rkisp1::algorithms {

/**
 * \class Dpf
 * \brief RkISP1 Denoise Pre-Filter control
 *
 * The denoise pre-filter algorithm is a bilateral filter which combines a
 * range filter and a domain filter. The denoise pre-filter is applied before
 * demosaicing.
 */

LOG_DEFINE_CATEGORY(RkISP1Dpf)

Dpf::Dpf()
	: config_({}), strengthConfig_({})
{
}

/**
 * \copydoc libcamera::ipa::Algorithm::init
 */
int Dpf::init([[maybe_unused]] IPAContext &context,
	      const YamlObject &tuningData)
{
	std::vector<uint8_t> values;

	/*
	 * The domain kernel is configured with a 9x9 kernel for the green
	 * pixels, and a 13x9 or 9x9 kernel for red and blue pixels.
	 */
	const YamlObject &dFObject = tuningData["DomainFilter"];

	/*
	 * For the green component, we have the 9x9 kernel specified
	 * as 6 coefficients:
	 *    Y
	 *    ^
	 *  4 | 6   5   4   5   6
	 *  3 |   5   3   3   5
	 *  2 | 5   3   2   3   5
	 *  1 |   3   1   1   3
	 *  0 - 4   2   0   2   4
	 * -1 |   3   1   1   3
	 * -2 | 5   3   2   3   5
	 * -3 |   5   3   3   5
	 * -4 | 6   5   4   5   6
	 *    +---------|--------> X
	 *     -4....-1 0 1 2 3 4
	 */
	values = dFObject["g"].getList<uint8_t>().value_or(utils::defopt);
	if (values.size() != RKISP1_CIF_ISP_DPF_MAX_SPATIAL_COEFFS) {
		LOG(RkISP1Dpf, Error)
			<< "Invalid 'DomainFilter:g': expected "
			<< RKISP1_CIF_ISP_DPF_MAX_SPATIAL_COEFFS
			<< " elements, got " << values.size();
		return -EINVAL;
	}

	std::copy_n(values.begin(), values.size(),
		    std::begin(config_.g_flt.spatial_coeff));

	config_.g_flt.gr_enable = true;
	config_.g_flt.gb_enable = true;

	/*
	 * For the red and blue components, we have the 13x9 kernel specified
	 * as 6 coefficients:
	 *
	 *    Y
	 *    ^
	 *  4 | 6   5   4   3   4   5   6
	 *    |
	 *  2 | 5   4   2   1   2   4   5
	 *    |
	 *  0 - 5   3   1   0   1   3   5
	 *    |
	 * -2 | 5   4   2   1   2   4   5
	 *    |
	 * -4 | 6   5   4   3   4   5   6
	 *    +-------------|------------> X
	 *     -6  -4  -2   0   2   4   6
	 *
	 * For a 9x9 kernel, columns -6 and 6 are dropped, so coefficient
	 * number 6 is not used.
	 */
	values = dFObject["rb"].getList<uint8_t>().value_or(utils::defopt);
	if (values.size() != RKISP1_CIF_ISP_DPF_MAX_SPATIAL_COEFFS &&
	    values.size() != RKISP1_CIF_ISP_DPF_MAX_SPATIAL_COEFFS - 1) {
		LOG(RkISP1Dpf, Error)
			<< "Invalid 'DomainFilter:rb': expected "
			<< RKISP1_CIF_ISP_DPF_MAX_SPATIAL_COEFFS - 1
			<< " or " << RKISP1_CIF_ISP_DPF_MAX_SPATIAL_COEFFS
			<< " elements, got " << values.size();
		return -EINVAL;
	}

	config_.rb_flt.fltsize = values.size() == RKISP1_CIF_ISP_DPF_MAX_SPATIAL_COEFFS
			       ? RKISP1_CIF_ISP_DPF_RB_FILTERSIZE_13x9
			       : RKISP1_CIF_ISP_DPF_RB_FILTERSIZE_9x9;

	std::copy_n(values.begin(), values.size(),
		    std::begin(config_.rb_flt.spatial_coeff));

	config_.rb_flt.r_enable = true;
	config_.rb_flt.b_enable = true;

	/*
	 * The range kernel is configured with a noise level lookup table (NLL)
	 * which stores a piecewise linear function that characterizes the
	 * sensor noise profile as a noise level function curve (NLF).
	 */
	const YamlObject &rFObject = tuningData["NoiseLevelFunction"];

	std::vector<uint16_t> nllValues;
	nllValues = rFObject["coeff"].getList<uint16_t>().value_or(utils::defopt);
	if (nllValues.size() != RKISP1_CIF_ISP_DPF_MAX_NLF_COEFFS) {
		LOG(RkISP1Dpf, Error)
			<< "Invalid 'RangeFilter:coeff': expected "
			<< RKISP1_CIF_ISP_DPF_MAX_NLF_COEFFS
			<< " elements, got " << nllValues.size();
		return -EINVAL;
	}

	std::copy_n(nllValues.begin(), nllValues.size(),
		    std::begin(config_.nll.coeff));

	std::string scaleMode = rFObject["scale-mode"].get<std::string>("");
	if (scaleMode == "linear") {
		config_.nll.scale_mode = RKISP1_CIF_ISP_NLL_SCALE_LINEAR;
	} else if (scaleMode == "logarithmic") {
		config_.nll.scale_mode = RKISP1_CIF_ISP_NLL_SCALE_LOGARITHMIC;
	} else {
		LOG(RkISP1Dpf, Error)
			<< "Invalid 'RangeFilter:scale-mode': expected "
			<< "'linear' or 'logarithmic' value, got "
			<< scaleMode;
		return -EINVAL;
	}

	const YamlObject &fSObject = tuningData["FilterStrength"];

	strengthConfig_.r = fSObject["r"].get<uint16_t>(64);
	strengthConfig_.g = fSObject["g"].get<uint16_t>(64);
	strengthConfig_.b = fSObject["b"].get<uint16_t>(64);

	return 0;
}

/**
 * \copydoc libcamera::ipa::Algorithm::queueRequest
 */
void Dpf::queueRequest(IPAContext &context,
		       [[maybe_unused]] const uint32_t frame,
		       IPAFrameContext &frameContext,
		       const ControlList &controls)
{
	auto &dpf = context.activeState.dpf;
	bool update = false;

	const auto &denoise = controls.get(controls::draft::NoiseReductionMode);
	if (denoise) {
		LOG(RkISP1Dpf, Debug) << "Set denoise to " << *denoise;

		switch (*denoise) {
		case controls::draft::NoiseReductionModeOff:
			if (dpf.denoise) {
				dpf.denoise = false;
				update = true;
			}
			break;
		case controls::draft::NoiseReductionModeMinimal:
		case controls::draft::NoiseReductionModeHighQuality:
		case controls::draft::NoiseReductionModeFast:
			if (!dpf.denoise) {
				dpf.denoise = true;
				update = true;
			}
			break;
		default:
			LOG(RkISP1Dpf, Error)
				<< "Unsupported denoise value "
				<< *denoise;
			break;
		}
	}

	frameContext.dpf.denoise = dpf.denoise;
	frameContext.dpf.update = update;
}

/**
 * \copydoc libcamera::ipa::Algorithm::prepare
 */
void Dpf::prepare(IPAContext &context, const uint32_t frame,
		  IPAFrameContext &frameContext, rkisp1_params_cfg *params)
{
	if (frame == 0) {
		params->others.dpf_config = config_;
		params->others.dpf_strength_config = strengthConfig_;

		const auto &awb = context.configuration.awb;
		const auto &lsc = context.configuration.lsc;
		auto &mode = params->others.dpf_config.gain.mode;

		/*
		 * The DPF needs to take into account the total amount of
		 * digital gain, which comes from the AWB and LSC modules. The
		 * DPF hardware can be programmed with a digital gain value
		 * manually, but can also use the gains supplied by the AWB and
		 * LSC modules automatically when they are enabled. Use that
		 * mode of operation as it simplifies control of the DPF.
		 */
		if (awb.enabled && lsc.enabled)
			mode = RKISP1_CIF_ISP_DPF_GAIN_USAGE_AWB_LSC_GAINS;
		else if (awb.enabled)
			mode = RKISP1_CIF_ISP_DPF_GAIN_USAGE_AWB_GAINS;
		else if (lsc.enabled)
			mode = RKISP1_CIF_ISP_DPF_GAIN_USAGE_LSC_GAINS;
		else
			mode = RKISP1_CIF_ISP_DPF_GAIN_USAGE_DISABLED;

		params->module_cfg_update |= RKISP1_CIF_ISP_MODULE_DPF |
					     RKISP1_CIF_ISP_MODULE_DPF_STRENGTH;
	}

	if (frameContext.dpf.update) {
		params->module_en_update |= RKISP1_CIF_ISP_MODULE_DPF;
		if (frameContext.dpf.denoise)
			params->module_ens |= RKISP1_CIF_ISP_MODULE_DPF;
	}
}

REGISTER_IPA_ALGORITHM(Dpf, "Dpf")

} /* namespace ipa::rkisp1::algorithms */

} /* namespace libcamera */