summaryrefslogtreecommitdiff
path: root/src/ipa/ipu3/algorithms
ModeNameSize
-rw-r--r--agc.cpp7113logplain
-rw-r--r--agc.h1237logplain
-rw-r--r--algorithm.cpp3420logplain
-rw-r--r--algorithm.h740logplain
-rw-r--r--awb.cpp11340logplain
-rw-r--r--awb.h2119logplain
-rw-r--r--meson.build144logplain
-rw-r--r--tone_mapping.cpp1478logplain
-rw-r--r--tone_mapping.h709logplain
> 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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2021-2022, Ideas On Board
 *
 * RkISP1 Lens Shading Correction control
 */

#include "lsc.h"

#include <algorithm>
#include <cmath>
#include <numeric>

#include <libcamera/base/log.h>
#include <libcamera/base/utils.h>

#include "libcamera/internal/yaml_parser.h"

#include "libipa/lsc_polynomial.h"
#include "linux/rkisp1-config.h"

/**
 * \file lsc.h
 */

namespace libcamera {

namespace ipa {

constexpr int kColourTemperatureChangeThreshhold = 10;

template<typename T>
void interpolateVector(const std::vector<T> &a, const std::vector<T> &b,
		       std::vector<T> &dest, double lambda)
{
	assert(a.size() == b.size());
	dest.resize(a.size());
	for (size_t i = 0; i < a.size(); i++) {
		dest[i] = a[i] * (1.0 - lambda) + b[i] * lambda;
	}
}

template<>
void Interpolator<rkisp1::algorithms::LensShadingCorrection::Components>::
	interpolate(const rkisp1::algorithms::LensShadingCorrection::Components &a,
		    const rkisp1::algorithms::LensShadingCorrection::Components &b,
		    rkisp1::algorithms::LensShadingCorrection::Components &dest,
		    double lambda)
{
	interpolateVector(a.r, b.r, dest.r, lambda);
	interpolateVector(a.gr, b.gr, dest.gr, lambda);
	interpolateVector(a.gb, b.gb, dest.gb, lambda);
	interpolateVector(a.b, b.b, dest.b, lambda);
}

} /* namespace ipa */

namespace ipa::rkisp1::algorithms {

/**
 * \class LensShadingCorrection
 * \brief RkISP1 Lens Shading Correction control
 *
 * Due to the optical characteristics of the lens, the light intensity received
 * by the sensor is not uniform.
 *
 * The Lens Shading Correction algorithm applies multipliers to all pixels
 * to compensate for the lens shading effect. The coefficients are
 * specified in a downscaled table in the YAML tuning file.
 */

LOG_DEFINE_CATEGORY(RkISP1Lsc)

class LscPolynomialLoader
{
public:
	LscPolynomialLoader(const Size &sensorSize,
			    const Rectangle &cropRectangle,
			    const std::vector<double> &xSizes,
			    const std::vector<double> &ySizes)
		: sensorSize_(sensorSize),
		  cropRectangle_(cropRectangle),
		  xSizes_(xSizes),
		  ySizes_(ySizes)
	{
	}

	int parseLscData(const YamlObject &yamlSets,
			 std::map<unsigned int, LensShadingCorrection::Components> &lscData)
	{
		const auto &sets = yamlSets.asList();
		for (const auto &yamlSet : sets) {
			std::optional<LscPolynomial> pr, pgr, pgb, pb;
			uint32_t ct = yamlSet["ct"].get<uint32_t>(0);

			if (lscData.count(ct)) {
				LOG(RkISP1Lsc, Error)
					<< "Multiple sets found for "
					<< "color temperature " << ct;
				return -EINVAL;
			}

			LensShadingCorrection::Components &set = lscData[ct];
			pr = yamlSet["r"].get<LscPolynomial>();
			pgr = yamlSet["gr"].get<LscPolynomial>();
			pgb = yamlSet["gb"].get<LscPolynomial>();
			pb = yamlSet["b"].get<LscPolynomial>();

			if (!(pr || pgr || pgb || pb)) {
				LOG(RkISP1Lsc, Error)
					<< "Failed to parse polynomial for "
					<< "colour temperature " << ct;
				return -EINVAL;
			}

			set.ct = ct;
			pr->setReferenceImageSize(sensorSize_);
			pgr->setReferenceImageSize(sensorSize_);
			pgb->setReferenceImageSize(sensorSize_);
			pb->setReferenceImageSize(sensorSize_);
			set.r = samplePolynomial(*pr);
			set.gr = samplePolynomial(*pgr);
			set.gb = samplePolynomial(*pgb);
			set.b = samplePolynomial(*pb);
		}

		if (lscData.empty()) {
			LOG(RkISP1Lsc, Error) << "Failed to load any sets";
			return -EINVAL;
		}

		return 0;
	}

private:
	/*
	 * The lsc grid has custom spacing defined on half the range (see
	 * parseSizes() for details). For easier handling this function converts
	 * the spaces vector to positions and mirrors them. E.g.:
	 *
	 * input:   | 0.2 | 0.3 |
	 * output: 0.0   0.2   0.5   0.8   1.0
	 */
	std::vector<double> sizesListToPositions(const std::vector<double> &sizes)
	{
		const int half = sizes.size();
		std::vector<double> res(half * 2 + 1);
		double x = 0.0;

		res[half] = 0.5;
		for (int i = 1; i <= half; i++) {
			x += sizes[half - i];
			res[half - i] = 0.5 - x;
			res[half + i] = 0.5 + x;
		}

		return res;
	}

	std::vector<uint16_t> samplePolynomial(const LscPolynomial &poly)
	{
		constexpr int k = RKISP1_CIF_ISP_LSC_SAMPLES_MAX;

		double m = poly.getM();
		double x0 = cropRectangle_.x / m;
		double y0 = cropRectangle_.y / m;
		double w = cropRectangle_.width / m;
		double h = cropRectangle_.height / m;
		std::vector<uint16_t> res;

		assert(xSizes_.size() * 2 + 1 == k);
		assert(ySizes_.size() * 2 + 1 == k);

		res.reserve(k * k);

		std::vector<double> xPos(sizesListToPositions(xSizes_));
		std::vector<double> yPos(sizesListToPositions(ySizes_));

		for (int y = 0; y < k; y++) {
			for (int x = 0; x < k; x++) {
				double xp = x0 + xPos[x] * w;
				double yp = y0 + yPos[y] * h;
				/*
				 * The hardware uses 2.10 fixed point format and
				 * limits the legal values to [1..3.999]. Scale
				 * and clamp the sampled value accordingly.
				 */
				int v = static_cast<int>(
					poly.sampleAtNormalizedPixelPos(xp, yp) *
					1024);
				v = std::min(std::max(v, 1024), 4095);
				res.push_back(v);
			}
		}
		return res;
	}

	Size sensorSize_;
	Rectangle cropRectangle_;
	const std::vector<double> &xSizes_;
	const std::vector<double> &ySizes_;
};

class LscTableLoader
{
public:
	int parseLscData(const YamlObject &yamlSets,
			 std::map<unsigned int, LensShadingCorrection::Components> &lscData)
	{
		const auto &sets = yamlSets.asList();

		for (const auto &yamlSet : sets) {
			uint32_t ct = yamlSet["ct"].get<uint32_t>(0);

			if (lscData.count(ct)) {
				LOG(RkISP1Lsc, Error)
					<< "Multiple sets found for color temperature "
					<< ct;
				return -EINVAL;
			}

			LensShadingCorrection::Components &set = lscData[ct];

			set.ct = ct;
			set.r = parseTable(yamlSet, "r");
			set.gr = parseTable(yamlSet, "gr");
			set.gb = parseTable(yamlSet, "gb");
			set.b = parseTable(yamlSet, "b");

			if (set.r.empty() || set.gr.empty() ||
			    set.gb.empty() || set.b.empty()) {
				LOG(RkISP1Lsc, Error)
					<< "Set for color temperature " << ct
					<< " is missing tables";
				return -EINVAL;
			}
		}

		if (lscData.empty()) {
			LOG(RkISP1Lsc, Error) << "Failed to load any sets";
			return -EINVAL;
		}

		return 0;
	}

private:
	std::vector<uint16_t> parseTable(const YamlObject &tuningData,
					 const char *prop)
	{
		static constexpr unsigned int kLscNumSamples =
			RKISP1_CIF_ISP_LSC_SAMPLES_MAX * RKISP1_CIF_ISP_LSC_SAMPLES_MAX;

		std::vector<uint16_t> table =
			tuningData[prop].getList<uint16_t>().value_or(std::vector<uint16_t>{});
		if (table.size() != kLscNumSamples) {
			LOG(RkISP1Lsc, Error)
				<< "Invalid '" << prop << "' values: expected "
				<< kLscNumSamples
				<< " elements, got " << table.size();
			return {};
		}

		return table;
	}
};

static std::vector<double> parseSizes(const YamlObject &tuningData,
				      const char *prop)
{
	std::vector<double> sizes =
		tuningData[prop].getList<double>().value_or(std::vector<double>{});
	if (sizes.size() != RKISP1_CIF_ISP_LSC_SECTORS_TBL_SIZE) {
		LOG(RkISP1Lsc, Error)
			<< "Invalid '" << prop << "' values: expected "
			<< RKISP1_CIF_ISP_LSC_SECTORS_TBL_SIZE
			<< " elements, got " << sizes.size();
		return {};
	}

	/*
	 * The sum of all elements must be 0.5 to satisfy hardware constraints.
	 * Validate it here, allowing a 1% tolerance as rounding errors may
	 * prevent an exact match (further adjustments will be performed in
	 * LensShadingCorrection::prepare()).
	 */
	double sum = std::accumulate(sizes.begin(), sizes.end(), 0.0);
	if (sum < 0.495 || sum > 0.505) {
		LOG(RkISP1Lsc, Error)
			<< "Invalid '" << prop << "' values: sum of the elements"
			<< " should be 0.5, got " << sum;
		return {};
	}

	return sizes;
}

LensShadingCorrection::LensShadingCorrection()
	: lastAppliedCt_(0), lastAppliedQuantizedCt_(0)
{
	sets_.setQuantization(kColourTemperatureChangeThreshhold);
}

/**
 * \copydoc libcamera::ipa::Algorithm::init
 */
int LensShadingCorrection::init([[maybe_unused]] IPAContext &context,
				const YamlObject &tuningData)
{
	xSize_ = parseSizes(tuningData, "x-size");
	ySize_ = parseSizes(tuningData, "y-size");

	if (xSize_.empty() || ySize_.empty())
		return -EINVAL;

	/* Get all defined sets to apply. */
	const YamlObject &yamlSets = tuningData["sets"];