/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2021, Ideas on Board Oy * * drm.h - DRM/KMS Helpers */ #pragma once #include #include #include #include #include #include #include #include #include #include #include #include namespace libcamera { class FrameBuffer; class PixelFormat; class Size; } /* namespace libcamera */ namespace DRM { class Device; class Plane; class Property; class PropertyValue; class Object { public: enum Type { TypeCrtc = DRM_MODE_OBJECT_CRTC, TypeConnector = DRM_MODE_OBJECT_CONNECTOR, TypeEncoder = DRM_MODE_OBJECT_ENCODER, TypeMode = DRM_MODE_OBJECT_MODE, TypeProperty = DRM_MODE_OBJECT_PROPERTY, TypeFb = DRM_MODE_OBJECT_FB, TypeBlob = DRM_MODE_OBJECT_BLOB, TypePlane = DRM_MODE_OBJECT_PLANE, TypeAny = DRM_MODE_OBJECT_ANY, }; Object(Device *dev, uint32_t id, Type type); virtual ~Object(); Device *device() const { return dev_; } uint32_t id() const { return id_; } Type type() const { return type_; } const Property *property(const std::string &name) const; const PropertyValue *propertyValue(const std::string &name) const; const std::vector &properties() const { return properties_; } protected: virtual int setup() { return 0; } uint32_t id_; private: friend Device; Device *dev_; Type type_; std::vector properties_; }; class Property : public Object { public: enum Type { TypeUnknown = 0, TypeRange, TypeEnum, TypeBlob, TypeBitmask, TypeObject, TypeSignedRange, }; Property(Device *dev, drmModePropertyRes *property); Type type() const { return type_; } const std::string &name() const { return name_; } bool isImmutable() const { return flags_ & DRM_MODE_PROP_IMMUTABLE; } const std::vector values() const { return values_; } const std::map &enums() const { return enums_; } const std::vector blobs() const { return blobs_; } private: Type type_; std::string name_; uint32_t flags_; std::vector values_; std::map enums_; std::vector blobs_; }; class PropertyValue { public: PropertyValue(uint32_t id, uint64_t value) : id_(id), value_(value) { } uint32_t id() const { return id_; } uint32_t value() const { return value_; } private: uint32_t id_; uint64_t value_; }; class Blob : public Object { public: Blob(Device *dev, const libcamera::Span &data); ~Blob(); bool isValid() const { return id() != 0; } }; class Mode : public drmModeModeInfo { public: Mode(const drmModeModeInfo &mode); std::unique_ptr toBlob(Device *dev) const; }; class Crtc : public Object { public: Crtc(Device *dev, const drmModeCrtc *crtc, unsigned int index); unsigned int index() const { return index_; } const std::vector &planes() const { return planes_; } private: friend Device; unsigned int index_; std::vector planes_; }; class Encoder : public Object { public: Encoder(Device *dev, const drmModeEncoder *encoder); uint32_t type() const { return type_; } const std::vector &possibleCrtcs() const { return possibleCrtcs_; } private: uint32_t type_; std::vector possibleCrtcs_; }; class Connector : public Object { public: enum Status { Connected, Disconnected, Unknown, }; Connector(Device *dev, const drmModeConnector *connector); uint32_t type() const { return type_; } const std::string &name() const { return name_; } Status status() const { return status_; } const std::vector &encoders() const { return encoders_; } const std::vector &modes() const { return modes_; } private: uint32_t type_; std::string name_; Status status_; std::vector encoders_; std::vector modes_; }; class Plane : public Object { public: enum Type { TypeOverlay, TypePrimary, TypeCursor, }; Plane(Device *dev, const drmModePlane *plane); Type type() const { return type_; } const std::vector &formats() const { return formats_; } const std::vector &possibleCrtcs() const { return possibleCrtcs_; } bool supportsFormat(const libcamera::PixelFormat &format) const; protected: int setup() override; private: friend class Device; Type type_; std::vector formats_; std::vector possibleCrtcs_; uint32_t possibleCrtcsMask_; }; class FrameBuffer : public Object { public: struct Plane { uint32_t handle; }; ~FrameBuffer(); private: friend class Device; FrameBuffer(Device *dev); std::map planes_; }; class AtomicRequest { public: enum Flags { FlagAllowModeset = (1 << 0), FlagAsync = (1 << 1), }; AtomicRequest(Device *dev); ~AtomicRequest(); Device *device() const { return dev_; } bool isValid() const { return valid_; } int addProperty(const Object *object, const std::string &property, uint64_t value); int addProperty(const Object *object, const std::string &property, std::unique_ptr blob); int commit(unsigned int flags = 0); private: AtomicRequest(const AtomicRequest &) = delete; AtomicRequest(const AtomicRequest &&) = delete; AtomicRequest &operator=(const AtomicRequest &) = delete; AtomicRequest &operator=(const AtomicRequest &&) = delete; int addProperty(uint32_t object, uint32_t property, uint64_t value); Device *dev_; bool valid_; drmModeAtomicReq *request_; std::list> blobs_; }; class Device { public: Device(); ~Device(); int init(); int fd() const { return fd_; } const std::list &crtcs() const { return crtcs_; } const std::list &encoders() const { return encoders_; } const std::list &connectors() const { return connectors_; } const std::list &planes() const { return planes_; } const std::list &properties() const { return properties_; } const Object *object(uint32_t id); std::unique_ptr createFrameBuffer( const libcamera::FrameBuffer &buffer, const libcamera::PixelFormat &format, const libcamera::Size &size, const std::array &strides); libcamera::Signal requestComplete; private: Device(const Device &) = delete; Device(const Device &&) = delete; Device &operator=(const Device &) = delete; Device &operator=(const Device &&) = delete; int openCard(); int getResources(); void drmEvent(); static void pageFlipComplete(int fd, unsigned int sequence, unsigned int tv_sec, unsigned int tv_usec, void *user_data); int fd_; std::list crtcs_; std::list encoders_; std::list connectors_; std::list planes_; std::list properties_; std::map objects_; }; } /* namespace DRM */ a id='n37' href='#n37'>37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 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 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 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
/* SPDX-License-Identifier: BSD-2-Clause */
/*
 * Copyright (C) 2023, Raspberry Pi Ltd
 *
 * agc_channel.cpp - AGC/AEC control algorithm
 */

#include "agc_channel.h"

#include <algorithm>
#include <tuple>

#include <libcamera/base/log.h>

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

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

LOG_DECLARE_CATEGORY(RPiAgc)

int AgcMeteringMode::read(const libcamera::YamlObject &params)
{
	const YamlObject &yamlWeights = params["weights"];

	for (const auto &p : yamlWeights.asList()) {
		auto value = p.get<double>();
		if (!value)
			return -EINVAL;
		weights.push_back(*value);
	}

	return 0;
}

static std::tuple<int, std::string>
readMeteringModes(std::map<std::string, AgcMeteringMode> &metering_modes,
		  const libcamera::YamlObject &params)
{
	std::string first;
	int ret;

	for (const auto &[key, value] : params.asDict()) {
		AgcMeteringMode meteringMode;
		ret = meteringMode.read(value);
		if (ret)
			return { ret, {} };

		metering_modes[key] = std::move(meteringMode);
		if (first.empty())
			first = key;
	}

	return { 0, first };
}

int AgcExposureMode::read(const libcamera::YamlObject &params)
{
	auto value = params["shutter"].getList<double>();
	if (!value)
		return -EINVAL;
	std::transform(value->begin(), value->end(), std::back_inserter(shutter),
		       [](double v) { return v * 1us; });

	value = params["gain"].getList<double>();
	if (!value)
		return -EINVAL;
	gain = std::move(*value);

	if (shutter.size() < 2 || gain.size() < 2) {
		LOG(RPiAgc, Error)
			<< "AgcExposureMode: must have at least two entries in exposure profile";
		return -EINVAL;
	}

	if (shutter.size() != gain.size()) {
		LOG(RPiAgc, Error)
			<< "AgcExposureMode: expect same number of exposure and gain entries in exposure profile";
		return -EINVAL;
	}

	return 0;
}

static std::tuple<int, std::string>
readExposureModes(std::map<std::string, AgcExposureMode> &exposureModes,
		  const libcamera::YamlObject &params)
{
	std::string first;
	int ret;

	for (const auto &[key, value] : params.asDict()) {
		AgcExposureMode exposureMode;
		ret = exposureMode.read(value);
		if (ret)
			return { ret, {} };

		exposureModes[key] = std::move(exposureMode);
		if (first.empty())
			first = key;
	}

	return { 0, first };
}

int AgcConstraint::read(const libcamera::YamlObject &params)
{
	std::string boundString = params["bound"].get<std::string>("");
	transform(boundString.begin(), boundString.end(),
		  boundString.begin(), ::toupper);
	if (boundString != "UPPER" && boundString != "LOWER") {
		LOG(RPiAgc, Error) << "AGC constraint type should be UPPER or LOWER";
		return -EINVAL;
	}
	bound = boundString == "UPPER" ? Bound::UPPER : Bound::LOWER;

	auto value = params["q_lo"].get<double>();
	if (!value)
		return -EINVAL;
	qLo = *value;

	value = params["q_hi"].get<double>();
	if (!value)
		return -EINVAL;
	qHi = *value;

	return yTarget.read(params["y_target"]);
}

static std::tuple<int, AgcConstraintMode>
readConstraintMode(const libcamera::YamlObject &params)
{
	AgcConstraintMode mode;
	int ret;

	for (const auto &p : params.asList()) {
		AgcConstraint constraint;
		ret = constraint.read(p);
		if (ret)
			return { ret, {} };

		mode.push_back(std::move(constraint));
	}

	return { 0, mode };
}

static std::tuple<int, std::string>
readConstraintModes(std::map<std::string, AgcConstraintMode> &constraintModes,
		    const libcamera::YamlObject &params)
{
	std::string first;
	int ret;

	for (const auto &[key, value] : params.asDict()) {
		std::tie(ret, constraintModes[key]) = readConstraintMode(value);
		if (ret)
			return { ret, {} };

		if (first.empty())
			first = key;
	}

	return { 0, first };
}

int AgcChannelConstraint::read(const libcamera::YamlObject &params)
{
	auto channelValue = params["channel"].get<unsigned int>();
	if (!channelValue) {
		LOG(RPiAgc, Error) << "AGC channel constraint must have a channel";
		return -EINVAL;
	}
	channel = *channelValue;

	std::string boundString = params["bound"].get<std::string>("");
	transform(boundString.begin(), boundString.end(),
		  boundString.begin(), ::toupper);
	if (boundString != "UPPER" && boundString != "LOWER") {
		LOG(RPiAgc, Error) << "AGC channel constraint type should be UPPER or LOWER";
		return -EINVAL;
	}
	bound = boundString == "UPPER" ? Bound::UPPER : Bound::LOWER;

	auto factorValue = params["factor"].get<double>();
	if (!factorValue) {
		LOG(RPiAgc, Error) << "AGC channel constraint must have a factor";
		return -EINVAL;
	}
	factor = *factorValue;

	return 0;
}

static int readChannelConstraints(std::vector<AgcChannelConstraint> &channelConstraints,
				  const libcamera::YamlObject &params)
{
	for (const auto &p : params.asList()) {
		AgcChannelConstraint constraint;
		int ret = constraint.read(p);
		if (ret)
			return ret;

		channelConstraints.push_back(constraint);
	}

	return 0;
}

int AgcConfig::read(const libcamera::YamlObject &params)
{
	LOG(RPiAgc, Debug) << "AgcConfig";
	int ret;

	std::tie(ret, defaultMeteringMode) =
		readMeteringModes(meteringModes, params["metering_modes"]);
	if (ret)
		return ret;
	std::tie(ret, defaultExposureMode) =
		readExposureModes(exposureModes, params["exposure_modes"]);
	if (ret)
		return ret;
	std::tie(ret, defaultConstraintMode) =
		readConstraintModes(constraintModes, params["constraint_modes"]);
	if (ret)
		return ret;

	if (params.contains("channel_constraints")) {
		ret = readChannelConstraints(channelConstraints, params["channel_constraints"]);
		if (ret)
			return ret;
	}

	ret = yTarget.read(params["y_target"]);
	if (ret)
		return ret;

	speed = params["speed"].get<double>(0.2);
	startupFrames = params["startup_frames"].get<uint16_t>(10);
	convergenceFrames = params["convergence_frames"].get<unsigned int>(6);
	fastReduceThreshold = params["fast_reduce_threshold"].get<double>(0.4);
	baseEv = params["base_ev"].get<double>(1.0);

	/* Start with quite a low value as ramping up is easier than ramping down. */
	defaultExposureTime = params["default_exposure_time"].get<double>(1000) * 1us;
	defaultAnalogueGain = params["default_analogue_gain"].get<double>(1.0);

	return 0;
}

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

AgcChannel::AgcChannel()
	: meteringMode_(nullptr), exposureMode_(nullptr), constraintMode_(nullptr),
	  frameCount_(0), lockCount_(0),
	  lastTargetExposure_(0s), 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).
	 */
	status_ = {};
	status_.ev = ev_;
}

int AgcChannel::read(const libcamera::YamlObject &params,
		     const Controller::HardwareConfig &hardwareConfig)
{
	int ret = config_.read(params);
	if (ret)
		return ret;

	const Size &size = hardwareConfig.agcZoneWeights;
	for (auto const &modes : config_.meteringModes) {
		if (modes.second.weights.size() != size.width * size.height) {
			LOG(RPiAgc, Error) << "AgcMeteringMode: Incorrect number of weights";
			return -EINVAL;
		}
	}

	/*
	 * 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;
	return 0;
}

void AgcChannel::disableAuto()
{
	fixedShutter_ = status_.shutterTime;
	fixedAnalogueGain_ = status_.analogueGain;
}

void AgcChannel::enableAuto()
{
	fixedShutter_ = 0s;
	fixedAnalogueGain_ = 0;
}

unsigned int AgcChannel::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;
}

std::vector<double> const &AgcChannel::getWeights() const
{
	/*
	 * In case someone calls setMeteringMode and then this before the
	 * algorithm has run and updated the meteringMode_ pointer.
	 */
	auto it = config_.meteringModes.find(meteringModeName_);
	if (it == config_.meteringModes.end())
		return meteringMode_->weights;
	return it->second.weights;
}

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

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

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

void AgcChannel::setFixedShutter(Duration fixedShutter)
{
	fixedShutter_ = fixedShutter;
	/* Set this in case someone calls disableAuto() straight after. */
	status_.shutterTime = limitShutter(fixedShutter_);
}

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

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

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

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

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

	housekeepConfig();

	/*
	 * Store the mode in the local state. We must cache the sensitivity of
	 * of the previous mode for the calculations below.
	 */
	double lastSensitivity = mode_.sensitivity;
	mode_ = cameraMode;

	Duration fixedShutter = limitShutter(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);
}

void AgcChannel::prepare(Metadata *imageMetadata)
{
	Duration totalExposureValue = status_.totalExposureValue;
	AgcStatus delayedStatus;
	AgcPrepareStatus prepareStatus;

	if (!imageMetadata->get("agc.delayed_status", delayedStatus))
		totalExposureValue = delayedStatus.totalExposureValue;

	prepareStatus.digitalGain = 1.0;
	prepareStatus.locked = false;

	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) {
				double digitalGain = totalExposureValue / actualExposure;
				LOG(RPiAgc, Debug) << "Want total exposure " << totalExposureValue;
				/*
				 * Never ask for a gain < 1.0, and also impose
				 * some upper limit. Make it customisable?
				 */
				prepareStatus.digitalGain = std::max(1.0, std::min(digitalGain, 4.0));
				LOG(RPiAgc, Debug) << "Actual exposure " << actualExposure;
				LOG(RPiAgc, Debug) << "Use digitalGain " << prepareStatus.digitalGain;
				LOG(RPiAgc, Debug) << "Effective exposure "
						   << actualExposure * prepareStatus.digitalGain;
				/* Decide whether AEC/AGC has converged. */
				prepareStatus.locked = updateLockStatus(deviceStatus);
			}
		} else
			LOG(RPiAgc, Warning) << "AgcChannel: no device metadata";
		imageMetadata->set("agc.prepare_status", prepareStatus);
	}
}

void AgcChannel::process(StatisticsPtr &stats, DeviceStatus const &deviceStatus, Metadata *imageMetadata)
{
	frameCount_++;
	/*
	 * First a little bit of housekeeping, fetching up-to-date settings and
	 * configuration, that kind of thing.
	 */
	housekeepConfig();
	/* Fetch the AWB status immediately, so that we can assume it's there. */
	fetchAwbStatus(imageMetadata);
	/* Get the current exposure values for the frame that's just arrived. */
	fetchCurrentExposure(deviceStatus);
	/* Compute the total gain we require relative to the current exposure. */
	double gain, targetY;
	computeGain(stats, imageMetadata, gain, targetY);
	/* Now compute the target (final) exposure which we think we want. */
	computeTargetExposure(gain);
	/* The results have to be filtered so as not to change too rapidly. */
	filterExposure();
	/*
	 * 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 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);
}

bool AgcChannel::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;

	/* Add 200us to the exposure time error to allow for line quantisation. */
	Duration exposureError = lastDeviceStatus_.shutterSpeed * errorFactor + 200us;
	double gainError = lastDeviceStatus_.analogueGain * errorFactor;
	Duration targetError = lastTargetExposure_ * errorFactor;

	/*
	 * Note that we don't know the exposure/gain limits of the sensor, so
	 * the values we keep requesting may be unachievable. For this reason
	 * we only insist that we're close to values in the past few frames.
	 */
	if (deviceStatus.shutterSpeed > lastDeviceStatus_.shutterSpeed - exposureError &&
	    deviceStatus.shutterSpeed < lastDeviceStatus_.shutterSpeed + exposureError &&
	    deviceStatus.analogueGain > lastDeviceStatus_.analogueGain - gainError &&
	    deviceStatus.analogueGain < lastDeviceStatus_.analogueGain + gainError &&
	    status_.targetExposureValue > lastTargetExposure_ - targetError &&
	    status_.targetExposureValue < lastTargetExposure_ + targetError)
		lockCount_ = std::min(lockCount_ + 1, maxLockCount);
	else if (deviceStatus.shutterSpeed < lastDeviceStatus_.shutterSpeed - resetMargin * exposureError ||
		 deviceStatus.shutterSpeed > lastDeviceStatus_.shutterSpeed + resetMargin * exposureError ||
		 deviceStatus.analogueGain < lastDeviceStatus_.analogueGain - resetMargin * gainError ||
		 deviceStatus.analogueGain > lastDeviceStatus_.analogueGain + resetMargin * gainError ||
		 status_.targetExposureValue < lastTargetExposure_ - resetMargin * targetError ||
		 status_.targetExposureValue > lastTargetExposure_ + resetMargin * targetError)
		lockCount_ = 0;

	lastDeviceStatus_ = deviceStatus;
	lastTargetExposure_ = status_.targetExposureValue;

	LOG(RPiAgc, Debug) << "Lock count updated to " << lockCount_;
	return lockCount_ == maxLockCount;
}

void AgcChannel::housekeepConfig()
{
	/* First fetch all the up-to-date settings, so no one else has to do it. */
	status_.ev = ev_;
	status_.fixedShutter = limitShutter(fixedShutter_);
	status_.fixedAnalogueGain = fixedAnalogueGain_;
	status_.flickerPeriod = flickerPeriod_;
	LOG(RPiAgc, Debug) << "ev " << status_.ev << " fixedShutter "
			   << status_.fixedShutter << " fixedAnalogueGain "
			   << status_.fixedAnalogueGain;
	/*
	 * Make sure the "mode" pointers point to the up-to-date things, if
	 * they've changed.
	 */
	if (meteringModeName_ != status_.meteringMode) {
		auto it = config_.meteringModes.find(meteringModeName_);
		if (it == config_.meteringModes.end()) {
			LOG(RPiAgc, Warning) << "No metering mode " << meteringModeName_;
			meteringModeName_ = status_.meteringMode;
		} else {
			meteringMode_ = &it->second;
			status_.meteringMode = meteringModeName_;
		}
	}
	if (exposureModeName_ != status_.exposureMode) {
		auto it = config_.exposureModes.find(exposureModeName_);