summaryrefslogtreecommitdiff
path: root/src/qcam/assets/feathericons/droplet.svg
diff options
context:
space:
mode:
authorJean-Michel Hautbois <jeanmichel.hautbois@ideasonboard.com>2021-11-30 08:10:58 +0100
committerKieran Bingham <kieran.bingham@ideasonboard.com>2021-12-01 15:42:55 +0000
commit437cc396685a8c50974688b814b08d36e086a9b1 (patch)
tree2768e47f8e160552bb1c2dd5e8d3e0d2b9a2b033 /src/qcam/assets/feathericons/droplet.svg
parent4085372c517e1527114dc4098194c3ae3b973ba0 (diff)
ipa: rkisp1: Initialize numCells in constructor
The non-static class member "numCells_" is not initialized in the constructor. Fix it. Reported-by: Coverity CID 365801 Signed-off-by: Jean-Michel Hautbois <jeanmichel.hautbois@ideasonboard.com> Reviewed-by: Umang Jain <umang.jain@ideasonboard.com> Reviewed-by: Kieran Bingham <kieran.bingham@ideasonboard.com> Signed-off-by: Kieran Bingham <kieran.bingham@ideasonboard.com>
Diffstat (limited to 'src/qcam/assets/feathericons/droplet.svg')
0 files changed, 0 insertions, 0 deletions
ef='#n86'>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 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 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 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 766 767 768 769 770 771 772 773
/* SPDX-License-Identifier: BSD-2-Clause */
/*
 * Copyright (C) 2019, Raspberry Pi (Trading) Limited
 *
 * agc.cpp - AGC/AEC control algorithm
 */

#include <map>

#include <linux/bcm2835-isp.h>

#include <libcamera/base/log.h>

#include "../awb_status.h"
#include "../device_status.h"
#include "../histogram.hpp"
#include "../lux_status.h"
#include "../metadata.hpp"

#include "agc.hpp"

using namespace RPiController;
using namespace libcamera;
using libcamera::utils::Duration;
using namespace std::literals::chrono_literals;

LOG_DEFINE_CATEGORY(RPiAgc)

#define NAME "rpi.agc"

#define PIPELINE_BITS 13 // seems to be a 13-bit pipeline

void AgcMeteringMode::read(boost::property_tree::ptree const &params)
{
	int num = 0;
	for (auto &p : params.get_child("weights")) {
		if (num == AGC_STATS_SIZE)
			throw std::runtime_error("AgcConfig: too many weights");
		weights[num++] = p.second.get_value<double>();
	}
	if (num != AGC_STATS_SIZE)
		throw std::runtime_error("AgcConfig: insufficient weights");
}

static std::string
readMeteringModes(std::map<std::string, AgcMeteringMode> &meteringModes,
		  boost::property_tree::ptree const &params)
{
	std::string first;
	for (auto &p : params) {
		AgcMeteringMode meteringMode;
		meteringMode.read(p.second);
		meteringModes[p.first] = std::move(meteringMode);
		if (first.empty())
			first = p.first;
	}
	return first;
}

static int readList(std::vector<double> &list,
		    boost::property_tree::ptree const &params)
{
	for (auto &p : params)
		list.push_back(p.second.get_value<double>());
	return list.size();
}

static int readList(std::vector<Duration> &list,
		    boost::property_tree::ptree const &params)
{
	for (auto &p : params)
		list.push_back(p.second.get_value<double>() * 1us);
	return list.size();
}

void AgcExposureMode::read(boost::property_tree::ptree const &params)
{
	int numShutters = readList(shutter, params.get_child("shutter"));
	int numAgs = readList(gain, params.get_child("gain"));
	if (numShutters < 2 || numAgs < 2)
		throw std::runtime_error(
			"AgcConfig: must have at least two entries in exposure profile");
	if (numShutters != numAgs)
		throw std::runtime_error(
			"AgcConfig: expect same number of exposure and gain entries in exposure profile");
}

static std::string
readExposureModes(std::map<std::string, AgcExposureMode> &exposureModes,
		  boost::property_tree::ptree const &params)
{
	std::string first;
	for (auto &p : params) {
		AgcExposureMode exposureMode;
		exposureMode.read(p.second);
		exposureModes[p.first] = std::move(exposureMode);
		if (first.empty())
			first = p.first;
	}
	return first;
}

void AgcConstraint::read(boost::property_tree::ptree const &params)
{
	std::string boundString = params.get<std::string>("bound", "");
	transform(boundString.begin(), boundString.end(),
		  boundString.begin(), ::toupper);
	if (boundString != "UPPER" && boundString != "LOWER")
		throw std::runtime_error(
			"AGC constraint type should be UPPER or LOWER");
	bound = boundString == "UPPER" ? Bound::UPPER : Bound::LOWER;
	qLo = params.get<double>("q_lo");
	qHi = params.get<double>("q_hi");
	yTarget.read(params.get_child("y_target"));
}

static AgcConstraintMode
readConstraintMode(boost::property_tree::ptree const &params)
{
	AgcConstraintMode mode;
	for (auto &p : params) {
		AgcConstraint constraint;
		constraint.read(p.second);
		mode.push_back(std::move(constraint));
	}
	return mode;
}

static std::string readConstraintModes(std::map<std::string, AgcConstraintMode> &constraintModes,
				       boost::property_tree::ptree const &params)
{
	std::string first;
	for (auto &p : params) {
		constraintModes[p.first] = readConstraintMode(p.second);
		if (first.empty())
			first = p.first;
	}
	return first;
}

void AgcConfig::read(boost::property_tree::ptree const &params)
{
	LOG(RPiAgc, Debug) << "AgcConfig";
	defaultMeteringMode = readMeteringModes(meteringModes, params.get_child("metering_modes"));
	defaultExposureMode = readExposureModes(exposureModes, params.get_child("exposure_modes"));
	defaultConstraintMode = readConstraintModes(constraintModes, params.get_child("constraint_modes"));
	yTarget.read(params.get_child("y_target"));
	speed = params.get<double>("speed", 0.2);
	startupFrames = params.get<uint16_t>("startup_frames", 10);
	convergenceFrames = params.get<unsigned int>("convergence_frames", 6);
	fastReduceThreshold = params.get<double>("fast_reduce_threshold", 0.4);
	baseEv = params.get<double>("base_ev", 1.0);
	// Start with quite a low value as ramping up is easier than ramping down.
	defaultExposureTime = params.get<double>("default_exposure_time", 1000) * 1us;
	defaultAnalogueGain = params.get<double>("default_analogueGain", 1.0);
}

Agc::ExposureValues::ExposureValues()
	: shutter(0s), analogueGain(0),
	  totalExposure(0s), totalExposureNoDG(0s)
{
}

Agc::Agc(Controller *controller)
	: AgcAlgorithm(controller), meteringMode_(nullptr),
	  exposureMode_(nullptr), constraintMode_(nullptr),
	  frameCount_(0), lockCount_(0),
	  lastTargetExposure_(0s), lastSensitivity_(0.0),
	  ev_(1.0), flickerPeriod_(0s),
	  maxShutter_(0s), fixedShutter_(0s), fixedAnalogueGain_(0.0)
{
	memset(&awb_, 0, sizeof(awb_));
	// Setting status_.totalExposureValue_ to zero initially tells us
	// it's not been calculated yet (i.e. Process hasn't yet run).
	memset(&status_, 0, sizeof(status_));
	status_.ev = ev_;
}

char const *Agc::name() const
{
	return NAME;
}

void Agc::read(boost::property_tree::ptree const &params)
{
	LOG(RPiAgc, Debug) << "Agc";
	config_.read(params);
	// Set the config's defaults (which are the first ones it read) as our
	// current modes, until someone changes them.  (they're all known to
	// exist at this point)
	meteringModeName_ = config_.defaultMeteringMode;
	meteringMode_ = &config_.meteringModes[meteringModeName_];
	exposureModeName_ = config_.defaultExposureMode;
	exposureMode_ = &config_.exposureModes[exposureModeName_];
	constraintModeName_ = config_.defaultConstraintMode;
	constraintMode_ = &config_.constraintModes[constraintModeName_];
	// Set up the "last shutter/gain" values, in case AGC starts "disabled".
	status_.shutterTime = config_.defaultExposureTime;
	status_.analogueGain = config_.defaultAnalogueGain;
}

bool Agc::isPaused() const
{
	return false;
}

void Agc::pause()
{
	fixedShutter_ = status_.shutterTime;
	fixedAnalogueGain_ = status_.analogueGain;
}

void Agc::resume()
{
	fixedShutter_ = 0s;
	fixedAnalogueGain_ = 0;
}

unsigned int Agc::getConvergenceFrames() const
{
	// If shutter and gain have been explicitly set, there is no
	// convergence to happen, so no need to drop any frames - return zero.
	if (fixedShutter_ && fixedAnalogueGain_)
		return 0;
	else
		return config_.convergenceFrames;
}

void Agc::setEv(double ev)
{
	ev_ = ev;
}

void Agc::setFlickerPeriod(Duration flickerPeriod)
{
	flickerPeriod_ = flickerPeriod;
}

void Agc::setMaxShutter(Duration maxShutter)
{
	maxShutter_ = maxShutter;
}

void Agc::setFixedShutter(Duration fixedShutter)
{
	fixedShutter_ = fixedShutter;
	// Set this in case someone calls Pause() straight after.
	status_.shutterTime = clipShutter(fixedShutter_);
}

void Agc::setFixedAnalogueGain(double fixedAnalogueGain)
{
	fixedAnalogueGain_ = fixedAnalogueGain;
	// Set this in case someone calls Pause() straight after.
	status_.analogueGain = fixedAnalogueGain;
}

void Agc::setMeteringMode(std::string const &meteringModeName)
{
	meteringModeName_ = meteringModeName;
}

void Agc::setExposureMode(std::string const &exposureModeName)
{
	exposureModeName_ = exposureModeName;
}

void Agc::setConstraintMode(std::string const &constraintModeName)
{
	constraintModeName_ = constraintModeName;
}

void Agc::switchMode(CameraMode const &cameraMode,
		     Metadata *metadata)
{
	/* AGC expects the mode sensitivity always to be non-zero. */
	ASSERT(cameraMode.sensitivity);

	housekeepConfig();

	Duration fixedShutter = clipShutter(fixedShutter_);
	if (fixedShutter && fixedAnalogueGain_) {
		// We're going to reset the algorithm here with these fixed values.

		fetchAwbStatus(metadata);
		double minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 });
		ASSERT(minColourGain != 0.0);

		// This is the equivalent of computeTargetExposure and applyDigitalGain.
		target_.totalExposureNoDG = fixedShutter_ * fixedAnalogueGain_;
		target_.totalExposure = target_.totalExposureNoDG / minColourGain;

		// Equivalent of filterExposure. This resets any "history".
		filtered_ = target_;

		// Equivalent of divideUpExposure.
		filtered_.shutter = fixedShutter;
		filtered_.analogueGain = fixedAnalogueGain_;
	} else if (status_.totalExposureValue) {
		// On a mode switch, various things could happen:
		// - the exposure profile might change
		// - a fixed exposure or gain might be set
		// - the new mode's sensitivity might be different
		// We cope with the last of these by scaling the target values. After
		// that we just need to re-divide the exposure/gain according to the
		// current exposure profile, which takes care of everything else.

		double ratio = lastSensitivity_ / cameraMode.sensitivity;
		target_.totalExposureNoDG *= ratio;
		target_.totalExposure *= ratio;
		filtered_.totalExposureNoDG *= ratio;
		filtered_.totalExposure *= ratio;

		divideUpExposure();
	} else {
		// We come through here on startup, when at least one of the shutter
		// or gain has not been fixed. We must still write those values out so
		// that they will be applied immediately. We supply some arbitrary defaults
		// for any that weren't set.

		// Equivalent of divideUpExposure.
		filtered_.shutter = fixedShutter ? fixedShutter : config_.defaultExposureTime;
		filtered_.analogueGain = fixedAnalogueGain_ ? fixedAnalogueGain_ : config_.defaultAnalogueGain;
	}

	writeAndFinish(metadata, false);

	// We must remember the sensitivity of this mode for the next SwitchMode.
	lastSensitivity_ = cameraMode.sensitivity;
}

void Agc::prepare(Metadata *imageMetadata)
{
	status_.digitalGain = 1.0;
	fetchAwbStatus(imageMetadata); // always fetch it so that Process knows it's been done

	if (status_.totalExposureValue) {
		// Process has run, so we have meaningful values.
		DeviceStatus deviceStatus;
		if (imageMetadata->get("device.status", deviceStatus) == 0) {
			Duration actualExposure = deviceStatus.shutterSpeed *
						  deviceStatus.analogueGain;
			if (actualExposure) {
				status_.digitalGain = status_.totalExposureValue / actualExposure;
				LOG(RPiAgc, Debug) << "Want total exposure " << status_.totalExposureValue;
				// Never ask for a gain < 1.0, and also impose
				// some upper limit. Make it customisable?
				status_.digitalGain = std::max(1.0, std::min(status_.digitalGain, 4.0));
				LOG(RPiAgc, Debug) << "Actual exposure " << actualExposure;
				LOG(RPiAgc, Debug) << "Use digitalGain " << status_.digitalGain;
				LOG(RPiAgc, Debug) << "Effective exposure "
						   << actualExposure * status_.digitalGain;
				// Decide whether AEC/AGC has converged.
				updateLockStatus(deviceStatus);
			}
		} else
			LOG(RPiAgc, Warning) << name() << ": no device metadata";
		imageMetadata->set("agc.status", status_);
	}
}

void Agc::process(StatisticsPtr &stats, Metadata *imageMetadata)
{
	frameCount_++;
	// First a little bit of housekeeping, fetching up-to-date settings and
	// configuration, that kind of thing.
	housekeepConfig();
	// Get the current exposure values for the frame that's just arrived.
	fetchCurrentExposure(imageMetadata);
	// Compute the total gain we require relative to the current exposure.
	double gain, targetY;
	computeGain(stats.get(), imageMetadata, gain, targetY);
	// Now compute the target (final) exposure which we think we want.
	computeTargetExposure(gain);
	// Some of the exposure has to be applied as digital gain, so work out
	// what that is. This function also tells us whether it's decided to
	// "desaturate" the image more quickly.
	bool desaturate = applyDigitalGain(gain, targetY);
	// The results have to be filtered so as not to change too rapidly.
	filterExposure(desaturate);
	// The last thing is to divide up the exposure value into a shutter time
	// and analogue gain, according to the current exposure mode.
	divideUpExposure();
	// Finally advertise what we've done.
	writeAndFinish(imageMetadata, desaturate);
}

void Agc::updateLockStatus(DeviceStatus const &deviceStatus)
{
	const double errorFactor = 0.10; // make these customisable?
	const int maxLockCount = 5;
	// Reset "lock count" when we exceed this multiple of errorFactor
	const double resetMargin = 1.5;