Show a patch.

GET /api/1.1/patches/18992/?format=api
HTTP 200 OK
Allow: GET, PUT, PATCH, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "id": 18992,
    "url": "https://patchwork.libcamera.org/api/1.1/patches/18992/?format=api",
    "web_url": "https://patchwork.libcamera.org/patch/18992/",
    "project": {
        "id": 1,
        "url": "https://patchwork.libcamera.org/api/1.1/projects/1/?format=api",
        "name": "libcamera",
        "link_name": "libcamera",
        "list_id": "libcamera_core",
        "list_email": "libcamera-devel@lists.libcamera.org",
        "web_url": "",
        "scm_url": "",
        "webscm_url": ""
    },
    "msgid": "<20230912102442.169001-3-david.plowman@raspberrypi.com>",
    "date": "2023-09-12T10:24:39",
    "name": "[libcamera-devel,v3,2/5] ipa: rpi: agc: Reorganise code for multi-channel AGC",
    "commit_ref": null,
    "pull_url": null,
    "state": "accepted",
    "archived": false,
    "hash": "4581fbb8e1745e7851402c8ed2b4eb4f66fa28d8",
    "submitter": {
        "id": 42,
        "url": "https://patchwork.libcamera.org/api/1.1/people/42/?format=api",
        "name": "David Plowman",
        "email": "david.plowman@raspberrypi.com"
    },
    "delegate": null,
    "mbox": "https://patchwork.libcamera.org/patch/18992/mbox/",
    "series": [
        {
            "id": 4017,
            "url": "https://patchwork.libcamera.org/api/1.1/series/4017/?format=api",
            "web_url": "https://patchwork.libcamera.org/project/libcamera/list/?series=4017",
            "date": "2023-09-12T10:24:37",
            "name": "Multi-channel AGC",
            "version": 3,
            "mbox": "https://patchwork.libcamera.org/series/4017/mbox/"
        }
    ],
    "comments": "https://patchwork.libcamera.org/api/patches/18992/comments/",
    "check": "pending",
    "checks": "https://patchwork.libcamera.org/api/patches/18992/checks/",
    "tags": {},
    "headers": {
        "Return-Path": "<libcamera-devel-bounces@lists.libcamera.org>",
        "X-Original-To": "parsemail@patchwork.libcamera.org",
        "Delivered-To": "parsemail@patchwork.libcamera.org",
        "Received": [
            "from lancelot.ideasonboard.com (lancelot.ideasonboard.com\n\t[92.243.16.209])\n\tby patchwork.libcamera.org (Postfix) with ESMTPS id 40165C32B1\n\tfor <parsemail@patchwork.libcamera.org>;\n\tTue, 12 Sep 2023 10:24:55 +0000 (UTC)",
            "from lancelot.ideasonboard.com (localhost [IPv6:::1])\n\tby lancelot.ideasonboard.com (Postfix) with ESMTP id C0560628EB;\n\tTue, 12 Sep 2023 12:24:54 +0200 (CEST)",
            "from mail-wm1-x336.google.com (mail-wm1-x336.google.com\n\t[IPv6:2a00:1450:4864:20::336])\n\tby lancelot.ideasonboard.com (Postfix) with ESMTPS id 85A1761DF5\n\tfor <libcamera-devel@lists.libcamera.org>;\n\tTue, 12 Sep 2023 12:24:52 +0200 (CEST)",
            "by mail-wm1-x336.google.com with SMTP id\n\t5b1f17b1804b1-4018af103bcso34594655e9.1\n\tfor <libcamera-devel@lists.libcamera.org>;\n\tTue, 12 Sep 2023 03:24:52 -0700 (PDT)",
            "from pi4-davidp.pitowers.org\n\t([2a00:1098:3142:14:2bce:64d6:1a5c:49a2])\n\tby smtp.gmail.com with ESMTPSA id\n\tn10-20020a05600c294a00b003fefaf299b6sm12426575wmd.38.2023.09.12.03.24.49\n\t(version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256);\n\tTue, 12 Sep 2023 03:24:49 -0700 (PDT)"
        ],
        "DKIM-Signature": [
            "v=1; a=rsa-sha256; c=relaxed/simple; d=libcamera.org;\n\ts=mail; t=1694514294;\n\tbh=sf8MdZkMbHJDrMmwoxTcDDSG2vfli1OykBh5oZVGUUI=;\n\th=To:Date:In-Reply-To:References:Subject:List-Id:List-Unsubscribe:\n\tList-Archive:List-Post:List-Help:List-Subscribe:From:Reply-To:\n\tFrom;\n\tb=wsYSzoua5ErwFW8wslS2jahUT9eyLygL6P8iR7Si/E7TIBFb1REYnL91fkTS88a1d\n\thlXxXAcIKnLyUWq0LC9lC28RbNynaBUn19519ng8qOk0ICvRLSaj/3mn6zcuILiA/Q\n\t6ASdGhq17Y6rXqFNQa07GcR68BkAm9F41RNtrPnTmfV0TaFifmvoWRha0ohNdYFjfM\n\tD5qHh4czgw44Mhs+7y+Sow2TgtjXuZz4yrjHO2j8d1SMrG+m88ANjYx0iGYzyMcVkO\n\tKm7NTxiOgOKV4deMswdkPQLU9RwExtNU5AcutXzHig0ZeU8MW/vM5s564FEcfYW2V/\n\tFOUP8+7Zz0Jtw==",
            "v=1; a=rsa-sha256; c=relaxed/relaxed;\n\td=raspberrypi.com; s=google; t=1694514292; x=1695119092;\n\tdarn=lists.libcamera.org; \n\th=content-transfer-encoding:mime-version:references:in-reply-to\n\t:message-id:date:subject:cc:to:from:from:to:cc:subject:date\n\t:message-id:reply-to;\n\tbh=Pdx3XN2ESN14pNd63ngQ+jyMdJluJvR/yqlCcQiHuOg=;\n\tb=iupcUqye2j7Gq3jCXkEd0Qe6N38wG9MZ5A9XSgPHRgZ4PI++qHZYo3JbnOWb5xmFz+\n\tyUDKauPXABS5Q7UB1+anzue64QQQUX7eSj80H0veWH+f/l8XK9H3W2vnTl3XGibnh1Yu\n\twmtuzbkBZI0mnJVojPAvTscyrUiyxeC5149XKIrijqUSXIwNAgEdfLqmDKs2VBSnjG0q\n\t/QtwOrzMmkDZxZ3kpMrBfrbAYwdRW9vDrpvegAlCQh249JJuLzp54hYt01wnQ4hLu+z9\n\th1IaljbVE5cMXkfhhHCFXhEu3GKB6oEazFTcM9Jzr8XKaMpX8OyOFNngZIdS+KvzFJFR\n\tl4mw=="
        ],
        "Authentication-Results": "lancelot.ideasonboard.com; dkim=pass (2048-bit key; \n\tunprotected) header.d=raspberrypi.com\n\theader.i=@raspberrypi.com\n\theader.b=\"iupcUqye\"; dkim-atps=neutral",
        "X-Google-DKIM-Signature": "v=1; a=rsa-sha256; c=relaxed/relaxed;\n\td=1e100.net; s=20230601; t=1694514292; x=1695119092;\n\th=content-transfer-encoding:mime-version:references:in-reply-to\n\t:message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc\n\t:subject:date:message-id:reply-to;\n\tbh=Pdx3XN2ESN14pNd63ngQ+jyMdJluJvR/yqlCcQiHuOg=;\n\tb=SS1lpGRtdVKomGUqj/ro1sym4zleMb5rEByoxQURsPq0+K1xwV1zWG3IYUOqQEWwWz\n\t/NUNVAyvSwJUq8D6WMBxYRpMJJzpei4Pzpd2MRPyHJSCJkXw4mLP39Mu+PcUrU/hnaOv\n\tJuhO0rLYQXAbMr1ujOzujxXxUPXiWdOImUYqWxwHL9+2rYhWphFGWg45NaYKEOo+9AsY\n\tzNlZIEhP/q+0UjMlTb2b5q066EwWb8svS6cA87Y4l9dO3hQSbk2VQjc9bBKno39gDCRi\n\tzq6b4p5v3f6COe41maPm2WBS55SkqLPsPqPz/69KML4C4A5vs9IavldUiIAUA+5Vox5/\n\tUdkQ==",
        "X-Gm-Message-State": "AOJu0YyMPLuoazjUWB5xLFtw3/iqwR/P7Bi5X/fKtf4qPyzoKTfWtqWy\n\tZvxjQjSWD+wZNcVxqMg+zY9KRE7qCYRDIWsuRrI=",
        "X-Google-Smtp-Source": "AGHT+IGgw8qkTZxk+NRE6IepIP042ZOaIwZfAByYYJO4aSYWXQ+yd3D2/MMzuRWosns9FcSFE7OlEg==",
        "X-Received": "by 2002:a05:600c:510a:b0:400:140c:6083 with SMTP id\n\to10-20020a05600c510a00b00400140c6083mr1588892wms.2.1694514290203; \n\tTue, 12 Sep 2023 03:24:50 -0700 (PDT)",
        "To": "libcamera-devel@lists.libcamera.org",
        "Date": "Tue, 12 Sep 2023 11:24:39 +0100",
        "Message-Id": "<20230912102442.169001-3-david.plowman@raspberrypi.com>",
        "X-Mailer": "git-send-email 2.30.2",
        "In-Reply-To": "<20230912102442.169001-1-david.plowman@raspberrypi.com>",
        "References": "<20230912102442.169001-1-david.plowman@raspberrypi.com>",
        "MIME-Version": "1.0",
        "Content-Transfer-Encoding": "8bit",
        "Subject": "[libcamera-devel] [PATCH v3 2/5] ipa: rpi: agc: Reorganise code for\n\tmulti-channel AGC",
        "X-BeenThere": "libcamera-devel@lists.libcamera.org",
        "X-Mailman-Version": "2.1.29",
        "Precedence": "list",
        "List-Id": "<libcamera-devel.lists.libcamera.org>",
        "List-Unsubscribe": "<https://lists.libcamera.org/options/libcamera-devel>,\n\t<mailto:libcamera-devel-request@lists.libcamera.org?subject=unsubscribe>",
        "List-Archive": "<https://lists.libcamera.org/pipermail/libcamera-devel/>",
        "List-Post": "<mailto:libcamera-devel@lists.libcamera.org>",
        "List-Help": "<mailto:libcamera-devel-request@lists.libcamera.org?subject=help>",
        "List-Subscribe": "<https://lists.libcamera.org/listinfo/libcamera-devel>,\n\t<mailto:libcamera-devel-request@lists.libcamera.org?subject=subscribe>",
        "From": "David Plowman via libcamera-devel <libcamera-devel@lists.libcamera.org>",
        "Reply-To": "David Plowman <david.plowman@raspberrypi.com>",
        "Errors-To": "libcamera-devel-bounces@lists.libcamera.org",
        "Sender": "\"libcamera-devel\" <libcamera-devel-bounces@lists.libcamera.org>"
    },
    "content": "This commit does the basic reorganisation of the code in order to\nimplement multi-channel AGC. The main changes are:\n\n* The previous Agc class (in agc.cpp) has become the AgcChannel class\n  in (agc_channel.cpp).\n\n* A new Agc class is introduced which is a wrapper round a number of\n  AgcChannels.\n\n* The basic plumbing from ipa_base.cpp to Agc is updated to include a\n  channel number. All the existing controls are hardwired to talk\n  directly to channel 0.\n\nThere are a couple of limitations which we expect to apply to\nmulti-channel AGC. We're not allowing different frame durations to be\napplied to the channels, nor are we allowing separate metering\nmodes. To be fair, supporting these things is not impossible, but\nthere are reasons why it may be tricky so they remain \"TBD\" for now.\n\nThis patch only includes the basic reorganisation and plumbing. It\ndoes not yet update the important methods (switchMode, prepare and\nprocess) to implement multi-channel AGC properly. This will appear in\na subsequent commit. For now, these functions are hard-coded just to\nuse channel 0, thereby preserving the existing behaviour.\n\nSigned-off-by: David Plowman <david.plowman@raspberrypi.com>\nReviewed-by: Naushir Patuck <naush@raspberrypi.com>\n---\n src/ipa/rpi/common/ipa_base.cpp            |  20 +-\n src/ipa/rpi/controller/agc_algorithm.h     |  19 +-\n src/ipa/rpi/controller/meson.build         |   1 +\n src/ipa/rpi/controller/rpi/agc.cpp         | 912 +++-----------------\n src/ipa/rpi/controller/rpi/agc.h           | 121 +--\n src/ipa/rpi/controller/rpi/agc_channel.cpp | 924 +++++++++++++++++++++\n src/ipa/rpi/controller/rpi/agc_channel.h   | 137 +++\n 7 files changed, 1219 insertions(+), 915 deletions(-)\n create mode 100644 src/ipa/rpi/controller/rpi/agc_channel.cpp\n create mode 100644 src/ipa/rpi/controller/rpi/agc_channel.h",
    "diff": "diff --git a/src/ipa/rpi/common/ipa_base.cpp b/src/ipa/rpi/common/ipa_base.cpp\nindex a47ae3a9..f7e7ad5e 100644\n--- a/src/ipa/rpi/common/ipa_base.cpp\n+++ b/src/ipa/rpi/common/ipa_base.cpp\n@@ -699,9 +699,9 @@ void IpaBase::applyControls(const ControlList &controls)\n \t\t\t}\n \n \t\t\tif (ctrl.second.get<bool>() == false)\n-\t\t\t\tagc->disableAuto();\n+\t\t\t\tagc->disableAuto(0);\n \t\t\telse\n-\t\t\t\tagc->enableAuto();\n+\t\t\t\tagc->enableAuto(0);\n \n \t\t\tlibcameraMetadata_.set(controls::AeEnable, ctrl.second.get<bool>());\n \t\t\tbreak;\n@@ -717,7 +717,7 @@ void IpaBase::applyControls(const ControlList &controls)\n \t\t\t}\n \n \t\t\t/* The control provides units of microseconds. */\n-\t\t\tagc->setFixedShutter(ctrl.second.get<int32_t>() * 1.0us);\n+\t\t\tagc->setFixedShutter(0, ctrl.second.get<int32_t>() * 1.0us);\n \n \t\t\tlibcameraMetadata_.set(controls::ExposureTime, ctrl.second.get<int32_t>());\n \t\t\tbreak;\n@@ -732,7 +732,7 @@ void IpaBase::applyControls(const ControlList &controls)\n \t\t\t\tbreak;\n \t\t\t}\n \n-\t\t\tagc->setFixedAnalogueGain(ctrl.second.get<float>());\n+\t\t\tagc->setFixedAnalogueGain(0, ctrl.second.get<float>());\n \n \t\t\tlibcameraMetadata_.set(controls::AnalogueGain,\n \t\t\t\t\t       ctrl.second.get<float>());\n@@ -770,7 +770,7 @@ void IpaBase::applyControls(const ControlList &controls)\n \n \t\t\tint32_t idx = ctrl.second.get<int32_t>();\n \t\t\tif (ConstraintModeTable.count(idx)) {\n-\t\t\t\tagc->setConstraintMode(ConstraintModeTable.at(idx));\n+\t\t\t\tagc->setConstraintMode(0, ConstraintModeTable.at(idx));\n \t\t\t\tlibcameraMetadata_.set(controls::AeConstraintMode, idx);\n \t\t\t} else {\n \t\t\t\tLOG(IPARPI, Error) << \"Constraint mode \" << idx\n@@ -790,7 +790,7 @@ void IpaBase::applyControls(const ControlList &controls)\n \n \t\t\tint32_t idx = ctrl.second.get<int32_t>();\n \t\t\tif (ExposureModeTable.count(idx)) {\n-\t\t\t\tagc->setExposureMode(ExposureModeTable.at(idx));\n+\t\t\t\tagc->setExposureMode(0, ExposureModeTable.at(idx));\n \t\t\t\tlibcameraMetadata_.set(controls::AeExposureMode, idx);\n \t\t\t} else {\n \t\t\t\tLOG(IPARPI, Error) << \"Exposure mode \" << idx\n@@ -813,7 +813,7 @@ void IpaBase::applyControls(const ControlList &controls)\n \t\t\t * So convert to 2^EV\n \t\t\t */\n \t\t\tdouble ev = pow(2.0, ctrl.second.get<float>());\n-\t\t\tagc->setEv(ev);\n+\t\t\tagc->setEv(0, ev);\n \t\t\tlibcameraMetadata_.set(controls::ExposureValue,\n \t\t\t\t\t       ctrl.second.get<float>());\n \t\t\tbreak;\n@@ -833,12 +833,12 @@ void IpaBase::applyControls(const ControlList &controls)\n \n \t\t\tswitch (mode) {\n \t\t\tcase controls::FlickerOff:\n-\t\t\t\tagc->setFlickerPeriod(0us);\n+\t\t\t\tagc->setFlickerPeriod(0, 0us);\n \n \t\t\t\tbreak;\n \n \t\t\tcase controls::FlickerManual:\n-\t\t\t\tagc->setFlickerPeriod(flickerState_.manualPeriod);\n+\t\t\t\tagc->setFlickerPeriod(0, flickerState_.manualPeriod);\n \n \t\t\t\tbreak;\n \n@@ -872,7 +872,7 @@ void IpaBase::applyControls(const ControlList &controls)\n \t\t\t * first, and the period updated after, or vice versa.\n \t\t\t */\n \t\t\tif (flickerState_.mode == controls::FlickerManual)\n-\t\t\t\tagc->setFlickerPeriod(flickerState_.manualPeriod);\n+\t\t\t\tagc->setFlickerPeriod(0, flickerState_.manualPeriod);\n \n \t\t\tbreak;\n \t\t}\ndiff --git a/src/ipa/rpi/controller/agc_algorithm.h b/src/ipa/rpi/controller/agc_algorithm.h\nindex b6949daa..b8986560 100644\n--- a/src/ipa/rpi/controller/agc_algorithm.h\n+++ b/src/ipa/rpi/controller/agc_algorithm.h\n@@ -21,16 +21,19 @@ public:\n \t/* An AGC algorithm must provide the following: */\n \tvirtual unsigned int getConvergenceFrames() const = 0;\n \tvirtual std::vector<double> const &getWeights() const = 0;\n-\tvirtual void setEv(double ev) = 0;\n-\tvirtual void setFlickerPeriod(libcamera::utils::Duration flickerPeriod) = 0;\n-\tvirtual void setFixedShutter(libcamera::utils::Duration fixedShutter) = 0;\n+\tvirtual void setEv(unsigned int channel, double ev) = 0;\n+\tvirtual void setFlickerPeriod(unsigned int channel,\n+\t\t\t\t      libcamera::utils::Duration flickerPeriod) = 0;\n+\tvirtual void setFixedShutter(unsigned int channel,\n+\t\t\t\t     libcamera::utils::Duration fixedShutter) = 0;\n \tvirtual void setMaxShutter(libcamera::utils::Duration maxShutter) = 0;\n-\tvirtual void setFixedAnalogueGain(double fixedAnalogueGain) = 0;\n+\tvirtual void setFixedAnalogueGain(unsigned int channel, double fixedAnalogueGain) = 0;\n \tvirtual void setMeteringMode(std::string const &meteringModeName) = 0;\n-\tvirtual void setExposureMode(std::string const &exposureModeName) = 0;\n-\tvirtual void setConstraintMode(std::string const &contraintModeName) = 0;\n-\tvirtual void enableAuto() = 0;\n-\tvirtual void disableAuto() = 0;\n+\tvirtual void setExposureMode(unsigned int channel, std::string const &exposureModeName) = 0;\n+\tvirtual void setConstraintMode(unsigned int channel, std::string const &contraintModeName) = 0;\n+\tvirtual void enableAuto(unsigned int channel) = 0;\n+\tvirtual void disableAuto(unsigned int channel) = 0;\n+\tvirtual void setActiveChannels(const std::vector<unsigned int> &activeChannels) = 0;\n };\n \n } /* namespace RPiController */\ndiff --git a/src/ipa/rpi/controller/meson.build b/src/ipa/rpi/controller/meson.build\nindex feb0334e..20b9cda9 100644\n--- a/src/ipa/rpi/controller/meson.build\n+++ b/src/ipa/rpi/controller/meson.build\n@@ -8,6 +8,7 @@ rpi_ipa_controller_sources = files([\n     'pwl.cpp',\n     'rpi/af.cpp',\n     'rpi/agc.cpp',\n+    'rpi/agc_channel.cpp',\n     'rpi/alsc.cpp',\n     'rpi/awb.cpp',\n     'rpi/black_level.cpp',\ndiff --git a/src/ipa/rpi/controller/rpi/agc.cpp b/src/ipa/rpi/controller/rpi/agc.cpp\nindex 7b02972a..598fc890 100644\n--- a/src/ipa/rpi/controller/rpi/agc.cpp\n+++ b/src/ipa/rpi/controller/rpi/agc.cpp\n@@ -5,20 +5,12 @@\n  * agc.cpp - AGC/AEC control algorithm\n  */\n \n-#include <algorithm>\n-#include <map>\n-#include <tuple>\n+#include \"agc.h\"\n \n #include <libcamera/base/log.h>\n \n-#include \"../awb_status.h\"\n-#include \"../device_status.h\"\n-#include \"../histogram.h\"\n-#include \"../lux_status.h\"\n #include \"../metadata.h\"\n \n-#include \"agc.h\"\n-\n using namespace RPiController;\n using namespace libcamera;\n using libcamera::utils::Duration;\n@@ -28,881 +20,205 @@ LOG_DEFINE_CATEGORY(RPiAgc)\n \n #define NAME \"rpi.agc\"\n \n-int AgcMeteringMode::read(const libcamera::YamlObject &params)\n+Agc::Agc(Controller *controller)\n+\t: AgcAlgorithm(controller),\n+\t  activeChannels_({ 0 })\n {\n-\tconst YamlObject &yamlWeights = params[\"weights\"];\n-\n-\tfor (const auto &p : yamlWeights.asList()) {\n-\t\tauto value = p.get<double>();\n-\t\tif (!value)\n-\t\t\treturn -EINVAL;\n-\t\tweights.push_back(*value);\n-\t}\n-\n-\treturn 0;\n }\n \n-static std::tuple<int, std::string>\n-readMeteringModes(std::map<std::string, AgcMeteringMode> &metering_modes,\n-\t\t  const libcamera::YamlObject &params)\n+char const *Agc::name() const\n {\n-\tstd::string first;\n-\tint ret;\n-\n-\tfor (const auto &[key, value] : params.asDict()) {\n-\t\tAgcMeteringMode meteringMode;\n-\t\tret = meteringMode.read(value);\n-\t\tif (ret)\n-\t\t\treturn { ret, {} };\n-\n-\t\tmetering_modes[key] = std::move(meteringMode);\n-\t\tif (first.empty())\n-\t\t\tfirst = key;\n-\t}\n-\n-\treturn { 0, first };\n+\treturn NAME;\n }\n \n-int AgcExposureMode::read(const libcamera::YamlObject &params)\n+int Agc::read(const libcamera::YamlObject &params)\n {\n-\tauto value = params[\"shutter\"].getList<double>();\n-\tif (!value)\n-\t\treturn -EINVAL;\n-\tstd::transform(value->begin(), value->end(), std::back_inserter(shutter),\n-\t\t       [](double v) { return v * 1us; });\n-\n-\tvalue = params[\"gain\"].getList<double>();\n-\tif (!value)\n-\t\treturn -EINVAL;\n-\tgain = std::move(*value);\n-\n-\tif (shutter.size() < 2 || gain.size() < 2) {\n-\t\tLOG(RPiAgc, Error)\n-\t\t\t<< \"AgcExposureMode: must have at least two entries in exposure profile\";\n-\t\treturn -EINVAL;\n-\t}\n-\n-\tif (shutter.size() != gain.size()) {\n-\t\tLOG(RPiAgc, Error)\n-\t\t\t<< \"AgcExposureMode: expect same number of exposure and gain entries in exposure profile\";\n-\t\treturn -EINVAL;\n+\t/*\n+\t * When there is only a single channel we can read the old style syntax.\n+\t * Otherwise we expect a \"channels\" keyword followed by a list of configurations.\n+\t */\n+\tif (!params.contains(\"channels\")) {\n+\t\tLOG(RPiAgc, Debug) << \"Single channel only\";\n+\t\tchannelData_.emplace_back();\n+\t\treturn channelData_.back().channel.read(params, getHardwareConfig());\n \t}\n \n-\treturn 0;\n-}\n-\n-static std::tuple<int, std::string>\n-readExposureModes(std::map<std::string, AgcExposureMode> &exposureModes,\n-\t\t  const libcamera::YamlObject &params)\n-{\n-\tstd::string first;\n-\tint ret;\n-\n-\tfor (const auto &[key, value] : params.asDict()) {\n-\t\tAgcExposureMode exposureMode;\n-\t\tret = exposureMode.read(value);\n+\tconst auto &channels = params[\"channels\"].asList();\n+\tfor (auto ch = channels.begin(); ch != channels.end(); ch++) {\n+\t\tLOG(RPiAgc, Debug) << \"Read AGC channel\";\n+\t\tchannelData_.emplace_back();\n+\t\tint ret = channelData_.back().channel.read(*ch, getHardwareConfig());\n \t\tif (ret)\n-\t\t\treturn { ret, {} };\n-\n-\t\texposureModes[key] = std::move(exposureMode);\n-\t\tif (first.empty())\n-\t\t\tfirst = key;\n+\t\t\treturn ret;\n \t}\n \n-\treturn { 0, first };\n-}\n-\n-int AgcConstraint::read(const libcamera::YamlObject &params)\n-{\n-\tstd::string boundString = params[\"bound\"].get<std::string>(\"\");\n-\ttransform(boundString.begin(), boundString.end(),\n-\t\t  boundString.begin(), ::toupper);\n-\tif (boundString != \"UPPER\" && boundString != \"LOWER\") {\n-\t\tLOG(RPiAgc, Error) << \"AGC constraint type should be UPPER or LOWER\";\n-\t\treturn -EINVAL;\n+\tLOG(RPiAgc, Debug) << \"Read \" << channelData_.size() << \" channel(s)\";\n+\tif (channelData_.empty()) {\n+\t\tLOG(RPiAgc, Error) << \"No AGC channels provided\";\n+\t\treturn -1;\n \t}\n-\tbound = boundString == \"UPPER\" ? Bound::UPPER : Bound::LOWER;\n-\n-\tauto value = params[\"q_lo\"].get<double>();\n-\tif (!value)\n-\t\treturn -EINVAL;\n-\tqLo = *value;\n-\n-\tvalue = params[\"q_hi\"].get<double>();\n-\tif (!value)\n-\t\treturn -EINVAL;\n-\tqHi = *value;\n-\n-\treturn yTarget.read(params[\"y_target\"]);\n-}\n \n-static std::tuple<int, AgcConstraintMode>\n-readConstraintMode(const libcamera::YamlObject &params)\n-{\n-\tAgcConstraintMode mode;\n-\tint ret;\n-\n-\tfor (const auto &p : params.asList()) {\n-\t\tAgcConstraint constraint;\n-\t\tret = constraint.read(p);\n-\t\tif (ret)\n-\t\t\treturn { ret, {} };\n-\n-\t\tmode.push_back(std::move(constraint));\n-\t}\n-\n-\treturn { 0, mode };\n+\treturn 0;\n }\n \n-static std::tuple<int, std::string>\n-readConstraintModes(std::map<std::string, AgcConstraintMode> &constraintModes,\n-\t\t    const libcamera::YamlObject &params)\n+int Agc::checkChannel(unsigned int channelIndex) const\n {\n-\tstd::string first;\n-\tint ret;\n-\n-\tfor (const auto &[key, value] : params.asDict()) {\n-\t\tstd::tie(ret, constraintModes[key]) = readConstraintMode(value);\n-\t\tif (ret)\n-\t\t\treturn { ret, {} };\n-\n-\t\tif (first.empty())\n-\t\t\tfirst = key;\n+\tif (channelIndex >= channelData_.size()) {\n+\t\tLOG(RPiAgc, Warning) << \"AGC channel \" << channelIndex << \" not available\";\n+\t\treturn -1;\n \t}\n \n-\treturn { 0, first };\n-}\n-\n-int AgcConfig::read(const libcamera::YamlObject &params)\n-{\n-\tLOG(RPiAgc, Debug) << \"AgcConfig\";\n-\tint ret;\n-\n-\tstd::tie(ret, defaultMeteringMode) =\n-\t\treadMeteringModes(meteringModes, params[\"metering_modes\"]);\n-\tif (ret)\n-\t\treturn ret;\n-\tstd::tie(ret, defaultExposureMode) =\n-\t\treadExposureModes(exposureModes, params[\"exposure_modes\"]);\n-\tif (ret)\n-\t\treturn ret;\n-\tstd::tie(ret, defaultConstraintMode) =\n-\t\treadConstraintModes(constraintModes, params[\"constraint_modes\"]);\n-\tif (ret)\n-\t\treturn ret;\n-\n-\tret = yTarget.read(params[\"y_target\"]);\n-\tif (ret)\n-\t\treturn ret;\n-\n-\tspeed = params[\"speed\"].get<double>(0.2);\n-\tstartupFrames = params[\"startup_frames\"].get<uint16_t>(10);\n-\tconvergenceFrames = params[\"convergence_frames\"].get<unsigned int>(6);\n-\tfastReduceThreshold = params[\"fast_reduce_threshold\"].get<double>(0.4);\n-\tbaseEv = params[\"base_ev\"].get<double>(1.0);\n-\n-\t/* Start with quite a low value as ramping up is easier than ramping down. */\n-\tdefaultExposureTime = params[\"default_exposure_time\"].get<double>(1000) * 1us;\n-\tdefaultAnalogueGain = params[\"default_analogue_gain\"].get<double>(1.0);\n-\n \treturn 0;\n }\n \n-Agc::ExposureValues::ExposureValues()\n-\t: shutter(0s), analogueGain(0),\n-\t  totalExposure(0s), totalExposureNoDG(0s)\n+void Agc::disableAuto(unsigned int channelIndex)\n {\n-}\n-\n-Agc::Agc(Controller *controller)\n-\t: AgcAlgorithm(controller), meteringMode_(nullptr),\n-\t  exposureMode_(nullptr), constraintMode_(nullptr),\n-\t  frameCount_(0), lockCount_(0),\n-\t  lastTargetExposure_(0s), ev_(1.0), flickerPeriod_(0s),\n-\t  maxShutter_(0s), fixedShutter_(0s), fixedAnalogueGain_(0.0)\n-{\n-\tmemset(&awb_, 0, sizeof(awb_));\n-\t/*\n-\t * Setting status_.totalExposureValue_ to zero initially tells us\n-\t * it's not been calculated yet (i.e. Process hasn't yet run).\n-\t */\n-\tstatus_ = {};\n-\tstatus_.ev = ev_;\n-}\n+\tif (checkChannel(channelIndex))\n+\t\treturn;\n \n-char const *Agc::name() const\n-{\n-\treturn NAME;\n+\tLOG(RPiAgc, Debug) << \"disableAuto for channel \" << channelIndex;\n+\tchannelData_[channelIndex].channel.disableAuto();\n }\n \n-int Agc::read(const libcamera::YamlObject &params)\n+void Agc::enableAuto(unsigned int channelIndex)\n {\n-\tLOG(RPiAgc, Debug) << \"Agc\";\n-\n-\tint ret = config_.read(params);\n-\tif (ret)\n-\t\treturn ret;\n-\n-\tconst Size &size = getHardwareConfig().agcZoneWeights;\n-\tfor (auto const &modes : config_.meteringModes) {\n-\t\tif (modes.second.weights.size() != size.width * size.height) {\n-\t\t\tLOG(RPiAgc, Error) << \"AgcMeteringMode: Incorrect number of weights\";\n-\t\t\treturn -EINVAL;\n-\t\t}\n-\t}\n+\tif (checkChannel(channelIndex))\n+\t\treturn;\n \n-\t/*\n-\t * Set the config's defaults (which are the first ones it read) as our\n-\t * current modes, until someone changes them.  (they're all known to\n-\t * exist at this point)\n-\t */\n-\tmeteringModeName_ = config_.defaultMeteringMode;\n-\tmeteringMode_ = &config_.meteringModes[meteringModeName_];\n-\texposureModeName_ = config_.defaultExposureMode;\n-\texposureMode_ = &config_.exposureModes[exposureModeName_];\n-\tconstraintModeName_ = config_.defaultConstraintMode;\n-\tconstraintMode_ = &config_.constraintModes[constraintModeName_];\n-\t/* Set up the \"last shutter/gain\" values, in case AGC starts \"disabled\". */\n-\tstatus_.shutterTime = config_.defaultExposureTime;\n-\tstatus_.analogueGain = config_.defaultAnalogueGain;\n-\treturn 0;\n-}\n-\n-void Agc::disableAuto()\n-{\n-\tfixedShutter_ = status_.shutterTime;\n-\tfixedAnalogueGain_ = status_.analogueGain;\n-}\n-\n-void Agc::enableAuto()\n-{\n-\tfixedShutter_ = 0s;\n-\tfixedAnalogueGain_ = 0;\n+\tLOG(RPiAgc, Debug) << \"enableAuto for channel \" << channelIndex;\n+\tchannelData_[channelIndex].channel.enableAuto();\n }\n \n unsigned int Agc::getConvergenceFrames() const\n {\n-\t/*\n-\t * If shutter and gain have been explicitly set, there is no\n-\t * convergence to happen, so no need to drop any frames - return zero.\n-\t */\n-\tif (fixedShutter_ && fixedAnalogueGain_)\n-\t\treturn 0;\n-\telse\n-\t\treturn config_.convergenceFrames;\n+\t/* If there are n channels, it presumably takes n times as long to converge. */\n+\treturn channelData_[0].channel.getConvergenceFrames() * activeChannels_.size();\n }\n \n std::vector<double> const &Agc::getWeights() const\n {\n \t/*\n-\t * In case someone calls setMeteringMode and then this before the\n-\t * algorithm has run and updated the meteringMode_ pointer.\n+\t * In future the metering weights may be determined differently, making it\n+\t * difficult to associate different sets of weight with different channels.\n+\t * Therefore we shall impose a limitation, at least for now, that all\n+\t * channels will use the same weights.\n \t */\n-\tauto it = config_.meteringModes.find(meteringModeName_);\n-\tif (it == config_.meteringModes.end())\n-\t\treturn meteringMode_->weights;\n-\treturn it->second.weights;\n+\treturn channelData_[0].channel.getWeights();\n }\n \n-void Agc::setEv(double ev)\n+void Agc::setEv(unsigned int channelIndex, double ev)\n {\n-\tev_ = ev;\n-}\n+\tif (checkChannel(channelIndex))\n+\t\treturn;\n \n-void Agc::setFlickerPeriod(Duration flickerPeriod)\n-{\n-\tflickerPeriod_ = flickerPeriod;\n+\tLOG(RPiAgc, Debug) << \"setEv \" << ev << \" for channel \" << channelIndex;\n+\tchannelData_[channelIndex].channel.setEv(ev);\n }\n \n-void Agc::setMaxShutter(Duration maxShutter)\n+void Agc::setFlickerPeriod(unsigned int channelIndex, Duration flickerPeriod)\n {\n-\tmaxShutter_ = maxShutter;\n-}\n+\tif (checkChannel(channelIndex))\n+\t\treturn;\n \n-void Agc::setFixedShutter(Duration fixedShutter)\n-{\n-\tfixedShutter_ = fixedShutter;\n-\t/* Set this in case someone calls disableAuto() straight after. */\n-\tstatus_.shutterTime = limitShutter(fixedShutter_);\n+\tLOG(RPiAgc, Debug) << \"setFlickerPeriod \" << flickerPeriod\n+\t\t\t   << \" for channel \" << channelIndex;\n+\tchannelData_[channelIndex].channel.setFlickerPeriod(flickerPeriod);\n }\n \n-void Agc::setFixedAnalogueGain(double fixedAnalogueGain)\n-{\n-\tfixedAnalogueGain_ = fixedAnalogueGain;\n-\t/* Set this in case someone calls disableAuto() straight after. */\n-\tstatus_.analogueGain = limitGain(fixedAnalogueGain);\n-}\n-\n-void Agc::setMeteringMode(std::string const &meteringModeName)\n-{\n-\tmeteringModeName_ = meteringModeName;\n-}\n-\n-void Agc::setExposureMode(std::string const &exposureModeName)\n-{\n-\texposureModeName_ = exposureModeName;\n-}\n-\n-void Agc::setConstraintMode(std::string const &constraintModeName)\n-{\n-\tconstraintModeName_ = constraintModeName;\n-}\n-\n-void Agc::switchMode(CameraMode const &cameraMode,\n-\t\t     Metadata *metadata)\n+void Agc::setMaxShutter(Duration maxShutter)\n {\n-\t/* AGC expects the mode sensitivity always to be non-zero. */\n-\tASSERT(cameraMode.sensitivity);\n-\n-\thousekeepConfig();\n-\n-\t/*\n-\t * Store the mode in the local state. We must cache the sensitivity of\n-\t * of the previous mode for the calculations below.\n-\t */\n-\tdouble lastSensitivity = mode_.sensitivity;\n-\tmode_ = cameraMode;\n-\n-\tDuration fixedShutter = limitShutter(fixedShutter_);\n-\tif (fixedShutter && fixedAnalogueGain_) {\n-\t\t/* We're going to reset the algorithm here with these fixed values. */\n-\n-\t\tfetchAwbStatus(metadata);\n-\t\tdouble minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 });\n-\t\tASSERT(minColourGain != 0.0);\n-\n-\t\t/* This is the equivalent of computeTargetExposure and applyDigitalGain. */\n-\t\ttarget_.totalExposureNoDG = fixedShutter_ * fixedAnalogueGain_;\n-\t\ttarget_.totalExposure = target_.totalExposureNoDG / minColourGain;\n-\n-\t\t/* Equivalent of filterExposure. This resets any \"history\". */\n-\t\tfiltered_ = target_;\n-\n-\t\t/* Equivalent of divideUpExposure. */\n-\t\tfiltered_.shutter = fixedShutter;\n-\t\tfiltered_.analogueGain = fixedAnalogueGain_;\n-\t} else if (status_.totalExposureValue) {\n-\t\t/*\n-\t\t * On a mode switch, various things could happen:\n-\t\t * - the exposure profile might change\n-\t\t * - a fixed exposure or gain might be set\n-\t\t * - the new mode's sensitivity might be different\n-\t\t * We cope with the last of these by scaling the target values. After\n-\t\t * that we just need to re-divide the exposure/gain according to the\n-\t\t * current exposure profile, which takes care of everything else.\n-\t\t */\n-\n-\t\tdouble ratio = lastSensitivity / cameraMode.sensitivity;\n-\t\ttarget_.totalExposureNoDG *= ratio;\n-\t\ttarget_.totalExposure *= ratio;\n-\t\tfiltered_.totalExposureNoDG *= ratio;\n-\t\tfiltered_.totalExposure *= ratio;\n-\n-\t\tdivideUpExposure();\n-\t} else {\n-\t\t/*\n-\t\t * We come through here on startup, when at least one of the shutter\n-\t\t * or gain has not been fixed. We must still write those values out so\n-\t\t * that they will be applied immediately. We supply some arbitrary defaults\n-\t\t * for any that weren't set.\n-\t\t */\n-\n-\t\t/* Equivalent of divideUpExposure. */\n-\t\tfiltered_.shutter = fixedShutter ? fixedShutter : config_.defaultExposureTime;\n-\t\tfiltered_.analogueGain = fixedAnalogueGain_ ? fixedAnalogueGain_ : config_.defaultAnalogueGain;\n-\t}\n-\n-\twriteAndFinish(metadata, false);\n+\t/* Frame durations will be the same across all channels too. */\n+\tfor (auto &data : channelData_)\n+\t\tdata.channel.setMaxShutter(maxShutter);\n }\n \n-void Agc::prepare(Metadata *imageMetadata)\n+void Agc::setFixedShutter(unsigned int channelIndex, Duration fixedShutter)\n {\n-\tDuration totalExposureValue = status_.totalExposureValue;\n-\tAgcStatus delayedStatus;\n-\tAgcPrepareStatus prepareStatus;\n-\n-\tif (!imageMetadata->get(\"agc.delayed_status\", delayedStatus))\n-\t\ttotalExposureValue = delayedStatus.totalExposureValue;\n-\n-\tprepareStatus.digitalGain = 1.0;\n-\tprepareStatus.locked = false;\n-\n-\tif (status_.totalExposureValue) {\n-\t\t/* Process has run, so we have meaningful values. */\n-\t\tDeviceStatus deviceStatus;\n-\t\tif (imageMetadata->get(\"device.status\", deviceStatus) == 0) {\n-\t\t\tDuration actualExposure = deviceStatus.shutterSpeed *\n-\t\t\t\t\t\t  deviceStatus.analogueGain;\n-\t\t\tif (actualExposure) {\n-\t\t\t\tdouble digitalGain = totalExposureValue / actualExposure;\n-\t\t\t\tLOG(RPiAgc, Debug) << \"Want total exposure \" << totalExposureValue;\n-\t\t\t\t/*\n-\t\t\t\t * Never ask for a gain < 1.0, and also impose\n-\t\t\t\t * some upper limit. Make it customisable?\n-\t\t\t\t */\n-\t\t\t\tprepareStatus.digitalGain = std::max(1.0, std::min(digitalGain, 4.0));\n-\t\t\t\tLOG(RPiAgc, Debug) << \"Actual exposure \" << actualExposure;\n-\t\t\t\tLOG(RPiAgc, Debug) << \"Use digitalGain \" << prepareStatus.digitalGain;\n-\t\t\t\tLOG(RPiAgc, Debug) << \"Effective exposure \"\n-\t\t\t\t\t\t   << actualExposure * prepareStatus.digitalGain;\n-\t\t\t\t/* Decide whether AEC/AGC has converged. */\n-\t\t\t\tprepareStatus.locked = updateLockStatus(deviceStatus);\n-\t\t\t}\n-\t\t} else\n-\t\t\tLOG(RPiAgc, Warning) << name() << \": no device metadata\";\n-\t\timageMetadata->set(\"agc.prepare_status\", prepareStatus);\n-\t}\n-}\n+\tif (checkChannel(channelIndex))\n+\t\treturn;\n \n-void Agc::process(StatisticsPtr &stats, Metadata *imageMetadata)\n-{\n-\tframeCount_++;\n-\t/*\n-\t * First a little bit of housekeeping, fetching up-to-date settings and\n-\t * configuration, that kind of thing.\n-\t */\n-\thousekeepConfig();\n-\t/* Fetch the AWB status immediately, so that we can assume it's there. */\n-\tfetchAwbStatus(imageMetadata);\n-\t/* Get the current exposure values for the frame that's just arrived. */\n-\tfetchCurrentExposure(imageMetadata);\n-\t/* Compute the total gain we require relative to the current exposure. */\n-\tdouble gain, targetY;\n-\tcomputeGain(stats, imageMetadata, gain, targetY);\n-\t/* Now compute the target (final) exposure which we think we want. */\n-\tcomputeTargetExposure(gain);\n-\t/* The results have to be filtered so as not to change too rapidly. */\n-\tfilterExposure();\n-\t/*\n-\t * Some of the exposure has to be applied as digital gain, so work out\n-\t * what that is. This function also tells us whether it's decided to\n-\t * \"desaturate\" the image more quickly.\n-\t */\n-\tbool desaturate = applyDigitalGain(gain, targetY);\n-\t/*\n-\t * The last thing is to divide up the exposure value into a shutter time\n-\t * and analogue gain, according to the current exposure mode.\n-\t */\n-\tdivideUpExposure();\n-\t/* Finally advertise what we've done. */\n-\twriteAndFinish(imageMetadata, desaturate);\n+\tLOG(RPiAgc, Debug) << \"setFixedShutter \" << fixedShutter\n+\t\t\t   << \" for channel \" << channelIndex;\n+\tchannelData_[channelIndex].channel.setFixedShutter(fixedShutter);\n }\n \n-bool Agc::updateLockStatus(DeviceStatus const &deviceStatus)\n+void Agc::setFixedAnalogueGain(unsigned int channelIndex, double fixedAnalogueGain)\n {\n-\tconst double errorFactor = 0.10; /* make these customisable? */\n-\tconst int maxLockCount = 5;\n-\t/* Reset \"lock count\" when we exceed this multiple of errorFactor */\n-\tconst double resetMargin = 1.5;\n+\tif (checkChannel(channelIndex))\n+\t\treturn;\n \n-\t/* Add 200us to the exposure time error to allow for line quantisation. */\n-\tDuration exposureError = lastDeviceStatus_.shutterSpeed * errorFactor + 200us;\n-\tdouble gainError = lastDeviceStatus_.analogueGain * errorFactor;\n-\tDuration targetError = lastTargetExposure_ * errorFactor;\n-\n-\t/*\n-\t * Note that we don't know the exposure/gain limits of the sensor, so\n-\t * the values we keep requesting may be unachievable. For this reason\n-\t * we only insist that we're close to values in the past few frames.\n-\t */\n-\tif (deviceStatus.shutterSpeed > lastDeviceStatus_.shutterSpeed - exposureError &&\n-\t    deviceStatus.shutterSpeed < lastDeviceStatus_.shutterSpeed + exposureError &&\n-\t    deviceStatus.analogueGain > lastDeviceStatus_.analogueGain - gainError &&\n-\t    deviceStatus.analogueGain < lastDeviceStatus_.analogueGain + gainError &&\n-\t    status_.targetExposureValue > lastTargetExposure_ - targetError &&\n-\t    status_.targetExposureValue < lastTargetExposure_ + targetError)\n-\t\tlockCount_ = std::min(lockCount_ + 1, maxLockCount);\n-\telse if (deviceStatus.shutterSpeed < lastDeviceStatus_.shutterSpeed - resetMargin * exposureError ||\n-\t\t deviceStatus.shutterSpeed > lastDeviceStatus_.shutterSpeed + resetMargin * exposureError ||\n-\t\t deviceStatus.analogueGain < lastDeviceStatus_.analogueGain - resetMargin * gainError ||\n-\t\t deviceStatus.analogueGain > lastDeviceStatus_.analogueGain + resetMargin * gainError ||\n-\t\t status_.targetExposureValue < lastTargetExposure_ - resetMargin * targetError ||\n-\t\t status_.targetExposureValue > lastTargetExposure_ + resetMargin * targetError)\n-\t\tlockCount_ = 0;\n-\n-\tlastDeviceStatus_ = deviceStatus;\n-\tlastTargetExposure_ = status_.targetExposureValue;\n-\n-\tLOG(RPiAgc, Debug) << \"Lock count updated to \" << lockCount_;\n-\treturn lockCount_ == maxLockCount;\n+\tLOG(RPiAgc, Debug) << \"setFixedAnalogueGain \" << fixedAnalogueGain\n+\t\t\t   << \" for channel \" << channelIndex;\n+\tchannelData_[channelIndex].channel.setFixedAnalogueGain(fixedAnalogueGain);\n }\n \n-void Agc::housekeepConfig()\n+void Agc::setMeteringMode(std::string const &meteringModeName)\n {\n-\t/* First fetch all the up-to-date settings, so no one else has to do it. */\n-\tstatus_.ev = ev_;\n-\tstatus_.fixedShutter = limitShutter(fixedShutter_);\n-\tstatus_.fixedAnalogueGain = fixedAnalogueGain_;\n-\tstatus_.flickerPeriod = flickerPeriod_;\n-\tLOG(RPiAgc, Debug) << \"ev \" << status_.ev << \" fixedShutter \"\n-\t\t\t   << status_.fixedShutter << \" fixedAnalogueGain \"\n-\t\t\t   << status_.fixedAnalogueGain;\n-\t/*\n-\t * Make sure the \"mode\" pointers point to the up-to-date things, if\n-\t * they've changed.\n-\t */\n-\tif (meteringModeName_ != status_.meteringMode) {\n-\t\tauto it = config_.meteringModes.find(meteringModeName_);\n-\t\tif (it == config_.meteringModes.end()) {\n-\t\t\tLOG(RPiAgc, Warning) << \"No metering mode \" << meteringModeName_;\n-\t\t\tmeteringModeName_ = status_.meteringMode;\n-\t\t} else {\n-\t\t\tmeteringMode_ = &it->second;\n-\t\t\tstatus_.meteringMode = meteringModeName_;\n-\t\t}\n-\t}\n-\tif (exposureModeName_ != status_.exposureMode) {\n-\t\tauto it = config_.exposureModes.find(exposureModeName_);\n-\t\tif (it == config_.exposureModes.end()) {\n-\t\t\tLOG(RPiAgc, Warning) << \"No exposure profile \" << exposureModeName_;\n-\t\t\texposureModeName_ = status_.exposureMode;\n-\t\t} else {\n-\t\t\texposureMode_ = &it->second;\n-\t\t\tstatus_.exposureMode = exposureModeName_;\n-\t\t}\n-\t}\n-\tif (constraintModeName_ != status_.constraintMode) {\n-\t\tauto it = config_.constraintModes.find(constraintModeName_);\n-\t\tif (it == config_.constraintModes.end()) {\n-\t\t\tLOG(RPiAgc, Warning) << \"No constraint list \" << constraintModeName_;\n-\t\t\tconstraintModeName_ = status_.constraintMode;\n-\t\t} else {\n-\t\t\tconstraintMode_ = &it->second;\n-\t\t\tstatus_.constraintMode = constraintModeName_;\n-\t\t}\n-\t}\n-\tLOG(RPiAgc, Debug) << \"exposureMode \"\n-\t\t\t   << exposureModeName_ << \" constraintMode \"\n-\t\t\t   << constraintModeName_ << \" meteringMode \"\n-\t\t\t   << meteringModeName_;\n+\t/* Metering modes will be the same across all channels too. */\n+\tfor (auto &data : channelData_)\n+\t\tdata.channel.setMeteringMode(meteringModeName);\n }\n \n-void Agc::fetchCurrentExposure(Metadata *imageMetadata)\n+void Agc::setExposureMode(unsigned int channelIndex, std::string const &exposureModeName)\n {\n-\tstd::unique_lock<Metadata> lock(*imageMetadata);\n-\tDeviceStatus *deviceStatus =\n-\t\timageMetadata->getLocked<DeviceStatus>(\"device.status\");\n-\tif (!deviceStatus)\n-\t\tLOG(RPiAgc, Fatal) << \"No device metadata\";\n-\tcurrent_.shutter = deviceStatus->shutterSpeed;\n-\tcurrent_.analogueGain = deviceStatus->analogueGain;\n-\tAgcStatus *agcStatus =\n-\t\timageMetadata->getLocked<AgcStatus>(\"agc.status\");\n-\tcurrent_.totalExposure = agcStatus ? agcStatus->totalExposureValue : 0s;\n-\tcurrent_.totalExposureNoDG = current_.shutter * current_.analogueGain;\n-}\n+\tif (checkChannel(channelIndex))\n+\t\treturn;\n \n-void Agc::fetchAwbStatus(Metadata *imageMetadata)\n-{\n-\tawb_.gainR = 1.0; /* in case not found in metadata */\n-\tawb_.gainG = 1.0;\n-\tawb_.gainB = 1.0;\n-\tif (imageMetadata->get(\"awb.status\", awb_) != 0)\n-\t\tLOG(RPiAgc, Debug) << \"No AWB status found\";\n+\tLOG(RPiAgc, Debug) << \"setExposureMode \" << exposureModeName\n+\t\t\t   << \" for channel \" << channelIndex;\n+\tchannelData_[channelIndex].channel.setExposureMode(exposureModeName);\n }\n \n-static double computeInitialY(StatisticsPtr &stats, AwbStatus const &awb,\n-\t\t\t      std::vector<double> &weights, double gain)\n+void Agc::setConstraintMode(unsigned int channelIndex, std::string const &constraintModeName)\n {\n-\tconstexpr uint64_t maxVal = 1 << Statistics::NormalisationFactorPow2;\n+\tif (checkChannel(channelIndex))\n+\t\treturn;\n \n-\tASSERT(weights.size() == stats->agcRegions.numRegions());\n-\n-\t/*\n-\t * Note that the weights are applied by the IPA to the statistics directly,\n-\t * before they are given to us here.\n-\t */\n-\tdouble rSum = 0, gSum = 0, bSum = 0, pixelSum = 0;\n-\tfor (unsigned int i = 0; i < stats->agcRegions.numRegions(); i++) {\n-\t\tauto &region = stats->agcRegions.get(i);\n-\t\trSum += std::min<double>(region.val.rSum * gain, (maxVal - 1) * region.counted);\n-\t\tgSum += std::min<double>(region.val.gSum * gain, (maxVal - 1) * region.counted);\n-\t\tbSum += std::min<double>(region.val.bSum * gain, (maxVal - 1) * region.counted);\n-\t\tpixelSum += region.counted;\n-\t}\n-\tif (pixelSum == 0.0) {\n-\t\tLOG(RPiAgc, Warning) << \"computeInitialY: pixelSum is zero\";\n-\t\treturn 0;\n-\t}\n-\tdouble ySum = rSum * awb.gainR * .299 +\n-\t\t      gSum * awb.gainG * .587 +\n-\t\t      bSum * awb.gainB * .114;\n-\treturn ySum / pixelSum / maxVal;\n+\tchannelData_[channelIndex].channel.setConstraintMode(constraintModeName);\n }\n \n-/*\n- * We handle extra gain through EV by adjusting our Y targets. However, you\n- * simply can't monitor histograms once they get very close to (or beyond!)\n- * saturation, so we clamp the Y targets to this value. It does mean that EV\n- * increases don't necessarily do quite what you might expect in certain\n- * (contrived) cases.\n- */\n-\n-static constexpr double EvGainYTargetLimit = 0.9;\n-\n-static double constraintComputeGain(AgcConstraint &c, const Histogram &h, double lux,\n-\t\t\t\t    double evGain, double &targetY)\n+template<typename T>\n+std::ostream &operator<<(std::ostream &os, const std::vector<T> &v)\n {\n-\ttargetY = c.yTarget.eval(c.yTarget.domain().clip(lux));\n-\ttargetY = std::min(EvGainYTargetLimit, targetY * evGain);\n-\tdouble iqm = h.interQuantileMean(c.qLo, c.qHi);\n-\treturn (targetY * h.bins()) / iqm;\n+\tos << \"{\";\n+\tfor (const auto &e : v)\n+\t\tos << \" \" << e;\n+\tos << \" }\";\n+\treturn os;\n }\n \n-void Agc::computeGain(StatisticsPtr &statistics, Metadata *imageMetadata,\n-\t\t      double &gain, double &targetY)\n+void Agc::setActiveChannels(const std::vector<unsigned int> &activeChannels)\n {\n-\tstruct LuxStatus lux = {};\n-\tlux.lux = 400; /* default lux level to 400 in case no metadata found */\n-\tif (imageMetadata->get(\"lux.status\", lux) != 0)\n-\t\tLOG(RPiAgc, Warning) << \"No lux level found\";\n-\tconst Histogram &h = statistics->yHist;\n-\tdouble evGain = status_.ev * config_.baseEv;\n-\t/*\n-\t * The initial gain and target_Y come from some of the regions. After\n-\t * that we consider the histogram constraints.\n-\t */\n-\ttargetY = config_.yTarget.eval(config_.yTarget.domain().clip(lux.lux));\n-\ttargetY = std::min(EvGainYTargetLimit, targetY * evGain);\n-\n-\t/*\n-\t * Do this calculation a few times as brightness increase can be\n-\t * non-linear when there are saturated regions.\n-\t */\n-\tgain = 1.0;\n-\tfor (int i = 0; i < 8; i++) {\n-\t\tdouble initialY = computeInitialY(statistics, awb_, meteringMode_->weights, gain);\n-\t\tdouble extraGain = std::min(10.0, targetY / (initialY + .001));\n-\t\tgain *= extraGain;\n-\t\tLOG(RPiAgc, Debug) << \"Initial Y \" << initialY << \" target \" << targetY\n-\t\t\t\t   << \" gives gain \" << gain;\n-\t\tif (extraGain < 1.01) /* close enough */\n-\t\t\tbreak;\n-\t}\n-\n-\tfor (auto &c : *constraintMode_) {\n-\t\tdouble newTargetY;\n-\t\tdouble newGain = constraintComputeGain(c, h, lux.lux, evGain, newTargetY);\n-\t\tLOG(RPiAgc, Debug) << \"Constraint has target_Y \"\n-\t\t\t\t   << newTargetY << \" giving gain \" << newGain;\n-\t\tif (c.bound == AgcConstraint::Bound::LOWER && newGain > gain) {\n-\t\t\tLOG(RPiAgc, Debug) << \"Lower bound constraint adopted\";\n-\t\t\tgain = newGain;\n-\t\t\ttargetY = newTargetY;\n-\t\t} else if (c.bound == AgcConstraint::Bound::UPPER && newGain < gain) {\n-\t\t\tLOG(RPiAgc, Debug) << \"Upper bound constraint adopted\";\n-\t\t\tgain = newGain;\n-\t\t\ttargetY = newTargetY;\n-\t\t}\n+\tif (activeChannels.empty()) {\n+\t\tLOG(RPiAgc, Warning) << \"No active AGC channels supplied\";\n+\t\treturn;\n \t}\n-\tLOG(RPiAgc, Debug) << \"Final gain \" << gain << \" (target_Y \" << targetY << \" ev \"\n-\t\t\t   << status_.ev << \" base_ev \" << config_.baseEv\n-\t\t\t   << \")\";\n-}\n-\n-void Agc::computeTargetExposure(double gain)\n-{\n-\tif (status_.fixedShutter && status_.fixedAnalogueGain) {\n-\t\t/*\n-\t\t * When ag and shutter are both fixed, we need to drive the\n-\t\t * total exposure so that we end up with a digital gain of at least\n-\t\t * 1/minColourGain. Otherwise we'd desaturate channels causing\n-\t\t * white to go cyan or magenta.\n-\t\t */\n-\t\tdouble minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 });\n-\t\tASSERT(minColourGain != 0.0);\n-\t\ttarget_.totalExposure =\n-\t\t\tstatus_.fixedShutter * status_.fixedAnalogueGain / minColourGain;\n-\t} else {\n-\t\t/*\n-\t\t * The statistics reflect the image without digital gain, so the final\n-\t\t * total exposure we're aiming for is:\n-\t\t */\n-\t\ttarget_.totalExposure = current_.totalExposureNoDG * gain;\n-\t\t/* The final target exposure is also limited to what the exposure mode allows. */\n-\t\tDuration maxShutter = status_.fixedShutter\n-\t\t\t\t\t      ? status_.fixedShutter\n-\t\t\t\t\t      : exposureMode_->shutter.back();\n-\t\tmaxShutter = limitShutter(maxShutter);\n-\t\tDuration maxTotalExposure =\n-\t\t\tmaxShutter *\n-\t\t\t(status_.fixedAnalogueGain != 0.0\n-\t\t\t\t ? status_.fixedAnalogueGain\n-\t\t\t\t : exposureMode_->gain.back());\n-\t\ttarget_.totalExposure = std::min(target_.totalExposure, maxTotalExposure);\n-\t}\n-\tLOG(RPiAgc, Debug) << \"Target totalExposure \" << target_.totalExposure;\n-}\n \n-bool Agc::applyDigitalGain(double gain, double targetY)\n-{\n-\tdouble minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 });\n-\tASSERT(minColourGain != 0.0);\n-\tdouble dg = 1.0 / minColourGain;\n-\t/*\n-\t * I think this pipeline subtracts black level and rescales before we\n-\t * get the stats, so no need to worry about it.\n-\t */\n-\tLOG(RPiAgc, Debug) << \"after AWB, target dg \" << dg << \" gain \" << gain\n-\t\t\t   << \" target_Y \" << targetY;\n-\t/*\n-\t * Finally, if we're trying to reduce exposure but the target_Y is\n-\t * \"close\" to 1.0, then the gain computed for that constraint will be\n-\t * only slightly less than one, because the measured Y can never be\n-\t * larger than 1.0. When this happens, demand a large digital gain so\n-\t * that the exposure can be reduced, de-saturating the image much more\n-\t * quickly (and we then approach the correct value more quickly from\n-\t * below).\n-\t */\n-\tbool desaturate = targetY > config_.fastReduceThreshold &&\n-\t\t\t  gain < sqrt(targetY);\n-\tif (desaturate)\n-\t\tdg /= config_.fastReduceThreshold;\n-\tLOG(RPiAgc, Debug) << \"Digital gain \" << dg << \" desaturate? \" << desaturate;\n-\tfiltered_.totalExposureNoDG = filtered_.totalExposure / dg;\n-\tLOG(RPiAgc, Debug) << \"Target totalExposureNoDG \" << filtered_.totalExposureNoDG;\n-\treturn desaturate;\n-}\n-\n-void Agc::filterExposure()\n-{\n-\tdouble speed = config_.speed;\n-\t/*\n-\t * AGC adapts instantly if both shutter and gain are directly specified\n-\t * or we're in the startup phase.\n-\t */\n-\tif ((status_.fixedShutter && status_.fixedAnalogueGain) ||\n-\t    frameCount_ <= config_.startupFrames)\n-\t\tspeed = 1.0;\n-\tif (!filtered_.totalExposure) {\n-\t\tfiltered_.totalExposure = target_.totalExposure;\n-\t} else {\n-\t\t/*\n-\t\t * If close to the result go faster, to save making so many\n-\t\t * micro-adjustments on the way. (Make this customisable?)\n-\t\t */\n-\t\tif (filtered_.totalExposure < 1.2 * target_.totalExposure &&\n-\t\t    filtered_.totalExposure > 0.8 * target_.totalExposure)\n-\t\t\tspeed = sqrt(speed);\n-\t\tfiltered_.totalExposure = speed * target_.totalExposure +\n-\t\t\t\t\t  filtered_.totalExposure * (1.0 - speed);\n-\t}\n-\tLOG(RPiAgc, Debug) << \"After filtering, totalExposure \" << filtered_.totalExposure\n-\t\t\t   << \" no dg \" << filtered_.totalExposureNoDG;\n-}\n+\tfor (auto index : activeChannels)\n+\t\tif (checkChannel(index))\n+\t\t\treturn;\n \n-void Agc::divideUpExposure()\n-{\n-\t/*\n-\t * Sending the fixed shutter/gain cases through the same code may seem\n-\t * unnecessary, but it will make more sense when extend this to cover\n-\t * variable aperture.\n-\t */\n-\tDuration exposureValue = filtered_.totalExposureNoDG;\n-\tDuration shutterTime;\n-\tdouble analogueGain;\n-\tshutterTime = status_.fixedShutter ? status_.fixedShutter\n-\t\t\t\t\t   : exposureMode_->shutter[0];\n-\tshutterTime = limitShutter(shutterTime);\n-\tanalogueGain = status_.fixedAnalogueGain != 0.0 ? status_.fixedAnalogueGain\n-\t\t\t\t\t\t\t: exposureMode_->gain[0];\n-\tanalogueGain = limitGain(analogueGain);\n-\tif (shutterTime * analogueGain < exposureValue) {\n-\t\tfor (unsigned int stage = 1;\n-\t\t     stage < exposureMode_->gain.size(); stage++) {\n-\t\t\tif (!status_.fixedShutter) {\n-\t\t\t\tDuration stageShutter =\n-\t\t\t\t\tlimitShutter(exposureMode_->shutter[stage]);\n-\t\t\t\tif (stageShutter * analogueGain >= exposureValue) {\n-\t\t\t\t\tshutterTime = exposureValue / analogueGain;\n-\t\t\t\t\tbreak;\n-\t\t\t\t}\n-\t\t\t\tshutterTime = stageShutter;\n-\t\t\t}\n-\t\t\tif (status_.fixedAnalogueGain == 0.0) {\n-\t\t\t\tif (exposureMode_->gain[stage] * shutterTime >= exposureValue) {\n-\t\t\t\t\tanalogueGain = exposureValue / shutterTime;\n-\t\t\t\t\tbreak;\n-\t\t\t\t}\n-\t\t\t\tanalogueGain = exposureMode_->gain[stage];\n-\t\t\t\tanalogueGain = limitGain(analogueGain);\n-\t\t\t}\n-\t\t}\n-\t}\n-\tLOG(RPiAgc, Debug) << \"Divided up shutter and gain are \" << shutterTime << \" and \"\n-\t\t\t   << analogueGain;\n-\t/*\n-\t * Finally adjust shutter time for flicker avoidance (require both\n-\t * shutter and gain not to be fixed).\n-\t */\n-\tif (!status_.fixedShutter && !status_.fixedAnalogueGain &&\n-\t    status_.flickerPeriod) {\n-\t\tint flickerPeriods = shutterTime / status_.flickerPeriod;\n-\t\tif (flickerPeriods) {\n-\t\t\tDuration newShutterTime = flickerPeriods * status_.flickerPeriod;\n-\t\t\tanalogueGain *= shutterTime / newShutterTime;\n-\t\t\t/*\n-\t\t\t * We should still not allow the ag to go over the\n-\t\t\t * largest value in the exposure mode. Note that this\n-\t\t\t * may force more of the total exposure into the digital\n-\t\t\t * gain as a side-effect.\n-\t\t\t */\n-\t\t\tanalogueGain = std::min(analogueGain, exposureMode_->gain.back());\n-\t\t\tanalogueGain = limitGain(analogueGain);\n-\t\t\tshutterTime = newShutterTime;\n-\t\t}\n-\t\tLOG(RPiAgc, Debug) << \"After flicker avoidance, shutter \"\n-\t\t\t\t   << shutterTime << \" gain \" << analogueGain;\n-\t}\n-\tfiltered_.shutter = shutterTime;\n-\tfiltered_.analogueGain = analogueGain;\n+\tLOG(RPiAgc, Debug) << \"setActiveChannels \" << activeChannels;\n+\tactiveChannels_ = activeChannels;\n }\n \n-void Agc::writeAndFinish(Metadata *imageMetadata, bool desaturate)\n+void Agc::switchMode(CameraMode const &cameraMode,\n+\t\t     Metadata *metadata)\n {\n-\tstatus_.totalExposureValue = filtered_.totalExposure;\n-\tstatus_.targetExposureValue = desaturate ? 0s : target_.totalExposureNoDG;\n-\tstatus_.shutterTime = filtered_.shutter;\n-\tstatus_.analogueGain = filtered_.analogueGain;\n-\t/*\n-\t * Write to metadata as well, in case anyone wants to update the camera\n-\t * immediately.\n-\t */\n-\timageMetadata->set(\"agc.status\", status_);\n-\tLOG(RPiAgc, Debug) << \"Output written, total exposure requested is \"\n-\t\t\t   << filtered_.totalExposure;\n-\tLOG(RPiAgc, Debug) << \"Camera exposure update: shutter time \" << filtered_.shutter\n-\t\t\t   << \" analogue gain \" << filtered_.analogueGain;\n+\tLOG(RPiAgc, Debug) << \"switchMode for channel 0\";\n+\tchannelData_[0].channel.switchMode(cameraMode, metadata);\n }\n \n-Duration Agc::limitShutter(Duration shutter)\n+void Agc::prepare(Metadata *imageMetadata)\n {\n-\t/*\n-\t * shutter == 0 is a special case for fixed shutter values, and must pass\n-\t * through unchanged\n-\t */\n-\tif (!shutter)\n-\t\treturn shutter;\n-\n-\tshutter = std::clamp(shutter, mode_.minShutter, maxShutter_);\n-\treturn shutter;\n+\tLOG(RPiAgc, Debug) << \"prepare for channel 0\";\n+\tchannelData_[0].channel.prepare(imageMetadata);\n }\n \n-double Agc::limitGain(double gain) const\n+void Agc::process(StatisticsPtr &stats, Metadata *imageMetadata)\n {\n-\t/*\n-\t * Only limit the lower bounds of the gain value to what the sensor limits.\n-\t * The upper bound on analogue gain will be made up with additional digital\n-\t * gain applied by the ISP.\n-\t *\n-\t * gain == 0.0 is a special case for fixed shutter values, and must pass\n-\t * through unchanged\n-\t */\n-\tif (!gain)\n-\t\treturn gain;\n-\n-\tgain = std::max(gain, mode_.minAnalogueGain);\n-\treturn gain;\n+\tLOG(RPiAgc, Debug) << \"process for channel 0\";\n+\tchannelData_[0].channel.process(stats, imageMetadata);\n }\n \n /* Register algorithm with the system. */\ndiff --git a/src/ipa/rpi/controller/rpi/agc.h b/src/ipa/rpi/controller/rpi/agc.h\nindex aaf77c8f..24f0a271 100644\n--- a/src/ipa/rpi/controller/rpi/agc.h\n+++ b/src/ipa/rpi/controller/rpi/agc.h\n@@ -6,60 +6,18 @@\n  */\n #pragma once\n \n+#include <optional>\n+#include <string>\n #include <vector>\n-#include <mutex>\n-\n-#include <libcamera/base/utils.h>\n \n #include \"../agc_algorithm.h\"\n-#include \"../agc_status.h\"\n-#include \"../pwl.h\"\n \n-/* This is our implementation of AGC. */\n+#include \"agc_channel.h\"\n \n namespace RPiController {\n \n-struct AgcMeteringMode {\n-\tstd::vector<double> weights;\n-\tint read(const libcamera::YamlObject &params);\n-};\n-\n-struct AgcExposureMode {\n-\tstd::vector<libcamera::utils::Duration> shutter;\n-\tstd::vector<double> gain;\n-\tint read(const libcamera::YamlObject &params);\n-};\n-\n-struct AgcConstraint {\n-\tenum class Bound { LOWER = 0, UPPER = 1 };\n-\tBound bound;\n-\tdouble qLo;\n-\tdouble qHi;\n-\tPwl yTarget;\n-\tint read(const libcamera::YamlObject &params);\n-};\n-\n-typedef std::vector<AgcConstraint> AgcConstraintMode;\n-\n-struct AgcConfig {\n-\tint read(const libcamera::YamlObject &params);\n-\tstd::map<std::string, AgcMeteringMode> meteringModes;\n-\tstd::map<std::string, AgcExposureMode> exposureModes;\n-\tstd::map<std::string, AgcConstraintMode> constraintModes;\n-\tPwl yTarget;\n-\tdouble speed;\n-\tuint16_t startupFrames;\n-\tunsigned int convergenceFrames;\n-\tdouble maxChange;\n-\tdouble minChange;\n-\tdouble fastReduceThreshold;\n-\tdouble speedUpThreshold;\n-\tstd::string defaultMeteringMode;\n-\tstd::string defaultExposureMode;\n-\tstd::string defaultConstraintMode;\n-\tdouble baseEv;\n-\tlibcamera::utils::Duration defaultExposureTime;\n-\tdouble defaultAnalogueGain;\n+struct AgcChannelData {\n+\tAgcChannel channel;\n };\n \n class Agc : public AgcAlgorithm\n@@ -70,65 +28,30 @@ public:\n \tint read(const libcamera::YamlObject &params) override;\n \tunsigned int getConvergenceFrames() const override;\n \tstd::vector<double> const &getWeights() const override;\n-\tvoid setEv(double ev) override;\n-\tvoid setFlickerPeriod(libcamera::utils::Duration flickerPeriod) override;\n+\tvoid setEv(unsigned int channel, double ev) override;\n+\tvoid setFlickerPeriod(unsigned int channelIndex,\n+\t\t\t      libcamera::utils::Duration flickerPeriod) override;\n \tvoid setMaxShutter(libcamera::utils::Duration maxShutter) override;\n-\tvoid setFixedShutter(libcamera::utils::Duration fixedShutter) override;\n-\tvoid setFixedAnalogueGain(double fixedAnalogueGain) override;\n+\tvoid setFixedShutter(unsigned int channelIndex,\n+\t\t\t     libcamera::utils::Duration fixedShutter) override;\n+\tvoid setFixedAnalogueGain(unsigned int channelIndex,\n+\t\t\t\t  double fixedAnalogueGain) override;\n \tvoid setMeteringMode(std::string const &meteringModeName) override;\n-\tvoid setExposureMode(std::string const &exposureModeName) override;\n-\tvoid setConstraintMode(std::string const &contraintModeName) override;\n-\tvoid enableAuto() override;\n-\tvoid disableAuto() override;\n+\tvoid setExposureMode(unsigned int channelIndex,\n+\t\t\t     std::string const &exposureModeName) override;\n+\tvoid setConstraintMode(unsigned int channelIndex,\n+\t\t\t       std::string const &contraintModeName) override;\n+\tvoid enableAuto(unsigned int channelIndex) override;\n+\tvoid disableAuto(unsigned int channelIndex) override;\n \tvoid switchMode(CameraMode const &cameraMode, Metadata *metadata) override;\n \tvoid prepare(Metadata *imageMetadata) override;\n \tvoid process(StatisticsPtr &stats, Metadata *imageMetadata) override;\n+\tvoid setActiveChannels(const std::vector<unsigned int> &activeChannels) override;\n \n private:\n-\tbool updateLockStatus(DeviceStatus const &deviceStatus);\n-\tAgcConfig config_;\n-\tvoid housekeepConfig();\n-\tvoid fetchCurrentExposure(Metadata *imageMetadata);\n-\tvoid fetchAwbStatus(Metadata *imageMetadata);\n-\tvoid computeGain(StatisticsPtr &statistics, Metadata *imageMetadata,\n-\t\t\t double &gain, double &targetY);\n-\tvoid computeTargetExposure(double gain);\n-\tvoid filterExposure();\n-\tbool applyDigitalGain(double gain, double targetY);\n-\tvoid divideUpExposure();\n-\tvoid writeAndFinish(Metadata *imageMetadata, bool desaturate);\n-\tlibcamera::utils::Duration limitShutter(libcamera::utils::Duration shutter);\n-\tdouble limitGain(double gain) const;\n-\tAgcMeteringMode *meteringMode_;\n-\tAgcExposureMode *exposureMode_;\n-\tAgcConstraintMode *constraintMode_;\n-\tCameraMode mode_;\n-\tuint64_t frameCount_;\n-\tAwbStatus awb_;\n-\tstruct ExposureValues {\n-\t\tExposureValues();\n-\n-\t\tlibcamera::utils::Duration shutter;\n-\t\tdouble analogueGain;\n-\t\tlibcamera::utils::Duration totalExposure;\n-\t\tlibcamera::utils::Duration totalExposureNoDG; /* without digital gain */\n-\t};\n-\tExposureValues current_;  /* values for the current frame */\n-\tExposureValues target_;   /* calculate the values we want here */\n-\tExposureValues filtered_; /* these values are filtered towards target */\n-\tAgcStatus status_;\n-\tint lockCount_;\n-\tDeviceStatus lastDeviceStatus_;\n-\tlibcamera::utils::Duration lastTargetExposure_;\n-\t/* Below here the \"settings\" that applications can change. */\n-\tstd::string meteringModeName_;\n-\tstd::string exposureModeName_;\n-\tstd::string constraintModeName_;\n-\tdouble ev_;\n-\tlibcamera::utils::Duration flickerPeriod_;\n-\tlibcamera::utils::Duration maxShutter_;\n-\tlibcamera::utils::Duration fixedShutter_;\n-\tdouble fixedAnalogueGain_;\n+\tint checkChannel(unsigned int channel) const;\n+\tstd::vector<AgcChannelData> channelData_;\n+\tstd::vector<unsigned int> activeChannels_;\n };\n \n } /* namespace RPiController */\ndiff --git a/src/ipa/rpi/controller/rpi/agc_channel.cpp b/src/ipa/rpi/controller/rpi/agc_channel.cpp\nnew file mode 100644\nindex 00000000..7c1aba81\n--- /dev/null\n+++ b/src/ipa/rpi/controller/rpi/agc_channel.cpp\n@@ -0,0 +1,924 @@\n+/* SPDX-License-Identifier: BSD-2-Clause */\n+/*\n+ * Copyright (C) 2023, Raspberry Pi Ltd\n+ *\n+ * agc.cpp - AGC/AEC control algorithm\n+ */\n+\n+#include \"agc_channel.h\"\n+\n+#include <algorithm>\n+#include <tuple>\n+\n+#include <libcamera/base/log.h>\n+\n+#include \"../awb_status.h\"\n+#include \"../device_status.h\"\n+#include \"../histogram.h\"\n+#include \"../lux_status.h\"\n+#include \"../metadata.h\"\n+\n+using namespace RPiController;\n+using namespace libcamera;\n+using libcamera::utils::Duration;\n+using namespace std::literals::chrono_literals;\n+\n+LOG_DECLARE_CATEGORY(RPiAgc)\n+\n+int AgcMeteringMode::read(const libcamera::YamlObject &params)\n+{\n+\tconst YamlObject &yamlWeights = params[\"weights\"];\n+\n+\tfor (const auto &p : yamlWeights.asList()) {\n+\t\tauto value = p.get<double>();\n+\t\tif (!value)\n+\t\t\treturn -EINVAL;\n+\t\tweights.push_back(*value);\n+\t}\n+\n+\treturn 0;\n+}\n+\n+static std::tuple<int, std::string>\n+readMeteringModes(std::map<std::string, AgcMeteringMode> &metering_modes,\n+\t\t  const libcamera::YamlObject &params)\n+{\n+\tstd::string first;\n+\tint ret;\n+\n+\tfor (const auto &[key, value] : params.asDict()) {\n+\t\tAgcMeteringMode meteringMode;\n+\t\tret = meteringMode.read(value);\n+\t\tif (ret)\n+\t\t\treturn { ret, {} };\n+\n+\t\tmetering_modes[key] = std::move(meteringMode);\n+\t\tif (first.empty())\n+\t\t\tfirst = key;\n+\t}\n+\n+\treturn { 0, first };\n+}\n+\n+int AgcExposureMode::read(const libcamera::YamlObject &params)\n+{\n+\tauto value = params[\"shutter\"].getList<double>();\n+\tif (!value)\n+\t\treturn -EINVAL;\n+\tstd::transform(value->begin(), value->end(), std::back_inserter(shutter),\n+\t\t       [](double v) { return v * 1us; });\n+\n+\tvalue = params[\"gain\"].getList<double>();\n+\tif (!value)\n+\t\treturn -EINVAL;\n+\tgain = std::move(*value);\n+\n+\tif (shutter.size() < 2 || gain.size() < 2) {\n+\t\tLOG(RPiAgc, Error)\n+\t\t\t<< \"AgcExposureMode: must have at least two entries in exposure profile\";\n+\t\treturn -EINVAL;\n+\t}\n+\n+\tif (shutter.size() != gain.size()) {\n+\t\tLOG(RPiAgc, Error)\n+\t\t\t<< \"AgcExposureMode: expect same number of exposure and gain entries in exposure profile\";\n+\t\treturn -EINVAL;\n+\t}\n+\n+\treturn 0;\n+}\n+\n+static std::tuple<int, std::string>\n+readExposureModes(std::map<std::string, AgcExposureMode> &exposureModes,\n+\t\t  const libcamera::YamlObject &params)\n+{\n+\tstd::string first;\n+\tint ret;\n+\n+\tfor (const auto &[key, value] : params.asDict()) {\n+\t\tAgcExposureMode exposureMode;\n+\t\tret = exposureMode.read(value);\n+\t\tif (ret)\n+\t\t\treturn { ret, {} };\n+\n+\t\texposureModes[key] = std::move(exposureMode);\n+\t\tif (first.empty())\n+\t\t\tfirst = key;\n+\t}\n+\n+\treturn { 0, first };\n+}\n+\n+int AgcConstraint::read(const libcamera::YamlObject &params)\n+{\n+\tstd::string boundString = params[\"bound\"].get<std::string>(\"\");\n+\ttransform(boundString.begin(), boundString.end(),\n+\t\t  boundString.begin(), ::toupper);\n+\tif (boundString != \"UPPER\" && boundString != \"LOWER\") {\n+\t\tLOG(RPiAgc, Error) << \"AGC constraint type should be UPPER or LOWER\";\n+\t\treturn -EINVAL;\n+\t}\n+\tbound = boundString == \"UPPER\" ? Bound::UPPER : Bound::LOWER;\n+\n+\tauto value = params[\"q_lo\"].get<double>();\n+\tif (!value)\n+\t\treturn -EINVAL;\n+\tqLo = *value;\n+\n+\tvalue = params[\"q_hi\"].get<double>();\n+\tif (!value)\n+\t\treturn -EINVAL;\n+\tqHi = *value;\n+\n+\treturn yTarget.read(params[\"y_target\"]);\n+}\n+\n+static std::tuple<int, AgcConstraintMode>\n+readConstraintMode(const libcamera::YamlObject &params)\n+{\n+\tAgcConstraintMode mode;\n+\tint ret;\n+\n+\tfor (const auto &p : params.asList()) {\n+\t\tAgcConstraint constraint;\n+\t\tret = constraint.read(p);\n+\t\tif (ret)\n+\t\t\treturn { ret, {} };\n+\n+\t\tmode.push_back(std::move(constraint));\n+\t}\n+\n+\treturn { 0, mode };\n+}\n+\n+static std::tuple<int, std::string>\n+readConstraintModes(std::map<std::string, AgcConstraintMode> &constraintModes,\n+\t\t    const libcamera::YamlObject &params)\n+{\n+\tstd::string first;\n+\tint ret;\n+\n+\tfor (const auto &[key, value] : params.asDict()) {\n+\t\tstd::tie(ret, constraintModes[key]) = readConstraintMode(value);\n+\t\tif (ret)\n+\t\t\treturn { ret, {} };\n+\n+\t\tif (first.empty())\n+\t\t\tfirst = key;\n+\t}\n+\n+\treturn { 0, first };\n+}\n+\n+int AgcConfig::read(const libcamera::YamlObject &params)\n+{\n+\tLOG(RPiAgc, Debug) << \"AgcConfig\";\n+\tint ret;\n+\n+\tstd::tie(ret, defaultMeteringMode) =\n+\t\treadMeteringModes(meteringModes, params[\"metering_modes\"]);\n+\tif (ret)\n+\t\treturn ret;\n+\tstd::tie(ret, defaultExposureMode) =\n+\t\treadExposureModes(exposureModes, params[\"exposure_modes\"]);\n+\tif (ret)\n+\t\treturn ret;\n+\tstd::tie(ret, defaultConstraintMode) =\n+\t\treadConstraintModes(constraintModes, params[\"constraint_modes\"]);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tret = yTarget.read(params[\"y_target\"]);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tspeed = params[\"speed\"].get<double>(0.2);\n+\tstartupFrames = params[\"startup_frames\"].get<uint16_t>(10);\n+\tconvergenceFrames = params[\"convergence_frames\"].get<unsigned int>(6);\n+\tfastReduceThreshold = params[\"fast_reduce_threshold\"].get<double>(0.4);\n+\tbaseEv = params[\"base_ev\"].get<double>(1.0);\n+\n+\t/* Start with quite a low value as ramping up is easier than ramping down. */\n+\tdefaultExposureTime = params[\"default_exposure_time\"].get<double>(1000) * 1us;\n+\tdefaultAnalogueGain = params[\"default_analogue_gain\"].get<double>(1.0);\n+\n+\treturn 0;\n+}\n+\n+AgcChannel::ExposureValues::ExposureValues()\n+\t: shutter(0s), analogueGain(0),\n+\t  totalExposure(0s), totalExposureNoDG(0s)\n+{\n+}\n+\n+AgcChannel::AgcChannel()\n+\t: meteringMode_(nullptr), exposureMode_(nullptr), constraintMode_(nullptr),\n+\t  frameCount_(0), lockCount_(0),\n+\t  lastTargetExposure_(0s), ev_(1.0), flickerPeriod_(0s),\n+\t  maxShutter_(0s), fixedShutter_(0s), fixedAnalogueGain_(0.0)\n+{\n+\tmemset(&awb_, 0, sizeof(awb_));\n+\t/*\n+\t * Setting status_.totalExposureValue_ to zero initially tells us\n+\t * it's not been calculated yet (i.e. Process hasn't yet run).\n+\t */\n+\tstatus_ = {};\n+\tstatus_.ev = ev_;\n+}\n+\n+int AgcChannel::read(const libcamera::YamlObject &params,\n+\t\t     const Controller::HardwareConfig &hardwareConfig)\n+{\n+\tint ret = config_.read(params);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tconst Size &size = hardwareConfig.agcZoneWeights;\n+\tfor (auto const &modes : config_.meteringModes) {\n+\t\tif (modes.second.weights.size() != size.width * size.height) {\n+\t\t\tLOG(RPiAgc, Error) << \"AgcMeteringMode: Incorrect number of weights\";\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\t}\n+\n+\t/*\n+\t * Set the config's defaults (which are the first ones it read) as our\n+\t * current modes, until someone changes them.  (they're all known to\n+\t * exist at this point)\n+\t */\n+\tmeteringModeName_ = config_.defaultMeteringMode;\n+\tmeteringMode_ = &config_.meteringModes[meteringModeName_];\n+\texposureModeName_ = config_.defaultExposureMode;\n+\texposureMode_ = &config_.exposureModes[exposureModeName_];\n+\tconstraintModeName_ = config_.defaultConstraintMode;\n+\tconstraintMode_ = &config_.constraintModes[constraintModeName_];\n+\t/* Set up the \"last shutter/gain\" values, in case AGC starts \"disabled\". */\n+\tstatus_.shutterTime = config_.defaultExposureTime;\n+\tstatus_.analogueGain = config_.defaultAnalogueGain;\n+\treturn 0;\n+}\n+\n+void AgcChannel::disableAuto()\n+{\n+\tfixedShutter_ = status_.shutterTime;\n+\tfixedAnalogueGain_ = status_.analogueGain;\n+}\n+\n+void AgcChannel::enableAuto()\n+{\n+\tfixedShutter_ = 0s;\n+\tfixedAnalogueGain_ = 0;\n+}\n+\n+unsigned int AgcChannel::getConvergenceFrames() const\n+{\n+\t/*\n+\t * If shutter and gain have been explicitly set, there is no\n+\t * convergence to happen, so no need to drop any frames - return zero.\n+\t */\n+\tif (fixedShutter_ && fixedAnalogueGain_)\n+\t\treturn 0;\n+\telse\n+\t\treturn config_.convergenceFrames;\n+}\n+\n+std::vector<double> const &AgcChannel::getWeights() const\n+{\n+\t/*\n+\t * In case someone calls setMeteringMode and then this before the\n+\t * algorithm has run and updated the meteringMode_ pointer.\n+\t */\n+\tauto it = config_.meteringModes.find(meteringModeName_);\n+\tif (it == config_.meteringModes.end())\n+\t\treturn meteringMode_->weights;\n+\treturn it->second.weights;\n+}\n+\n+void AgcChannel::setEv(double ev)\n+{\n+\tev_ = ev;\n+}\n+\n+void AgcChannel::setFlickerPeriod(Duration flickerPeriod)\n+{\n+\tflickerPeriod_ = flickerPeriod;\n+}\n+\n+void AgcChannel::setMaxShutter(Duration maxShutter)\n+{\n+\tmaxShutter_ = maxShutter;\n+}\n+\n+void AgcChannel::setFixedShutter(Duration fixedShutter)\n+{\n+\tfixedShutter_ = fixedShutter;\n+\t/* Set this in case someone calls disableAuto() straight after. */\n+\tstatus_.shutterTime = limitShutter(fixedShutter_);\n+}\n+\n+void AgcChannel::setFixedAnalogueGain(double fixedAnalogueGain)\n+{\n+\tfixedAnalogueGain_ = fixedAnalogueGain;\n+\t/* Set this in case someone calls disableAuto() straight after. */\n+\tstatus_.analogueGain = limitGain(fixedAnalogueGain);\n+}\n+\n+void AgcChannel::setMeteringMode(std::string const &meteringModeName)\n+{\n+\tmeteringModeName_ = meteringModeName;\n+}\n+\n+void AgcChannel::setExposureMode(std::string const &exposureModeName)\n+{\n+\texposureModeName_ = exposureModeName;\n+}\n+\n+void AgcChannel::setConstraintMode(std::string const &constraintModeName)\n+{\n+\tconstraintModeName_ = constraintModeName;\n+}\n+\n+void AgcChannel::switchMode(CameraMode const &cameraMode,\n+\t\t\t    Metadata *metadata)\n+{\n+\t/* AGC expects the mode sensitivity always to be non-zero. */\n+\tASSERT(cameraMode.sensitivity);\n+\n+\thousekeepConfig();\n+\n+\t/*\n+\t * Store the mode in the local state. We must cache the sensitivity of\n+\t * of the previous mode for the calculations below.\n+\t */\n+\tdouble lastSensitivity = mode_.sensitivity;\n+\tmode_ = cameraMode;\n+\n+\tDuration fixedShutter = limitShutter(fixedShutter_);\n+\tif (fixedShutter && fixedAnalogueGain_) {\n+\t\t/* We're going to reset the algorithm here with these fixed values. */\n+\n+\t\tfetchAwbStatus(metadata);\n+\t\tdouble minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 });\n+\t\tASSERT(minColourGain != 0.0);\n+\n+\t\t/* This is the equivalent of computeTargetExposure and applyDigitalGain. */\n+\t\ttarget_.totalExposureNoDG = fixedShutter_ * fixedAnalogueGain_;\n+\t\ttarget_.totalExposure = target_.totalExposureNoDG / minColourGain;\n+\n+\t\t/* Equivalent of filterExposure. This resets any \"history\". */\n+\t\tfiltered_ = target_;\n+\n+\t\t/* Equivalent of divideUpExposure. */\n+\t\tfiltered_.shutter = fixedShutter;\n+\t\tfiltered_.analogueGain = fixedAnalogueGain_;\n+\t} else if (status_.totalExposureValue) {\n+\t\t/*\n+\t\t * On a mode switch, various things could happen:\n+\t\t * - the exposure profile might change\n+\t\t * - a fixed exposure or gain might be set\n+\t\t * - the new mode's sensitivity might be different\n+\t\t * We cope with the last of these by scaling the target values. After\n+\t\t * that we just need to re-divide the exposure/gain according to the\n+\t\t * current exposure profile, which takes care of everything else.\n+\t\t */\n+\n+\t\tdouble ratio = lastSensitivity / cameraMode.sensitivity;\n+\t\ttarget_.totalExposureNoDG *= ratio;\n+\t\ttarget_.totalExposure *= ratio;\n+\t\tfiltered_.totalExposureNoDG *= ratio;\n+\t\tfiltered_.totalExposure *= ratio;\n+\n+\t\tdivideUpExposure();\n+\t} else {\n+\t\t/*\n+\t\t * We come through here on startup, when at least one of the shutter\n+\t\t * or gain has not been fixed. We must still write those values out so\n+\t\t * that they will be applied immediately. We supply some arbitrary defaults\n+\t\t * for any that weren't set.\n+\t\t */\n+\n+\t\t/* Equivalent of divideUpExposure. */\n+\t\tfiltered_.shutter = fixedShutter ? fixedShutter : config_.defaultExposureTime;\n+\t\tfiltered_.analogueGain = fixedAnalogueGain_ ? fixedAnalogueGain_ : config_.defaultAnalogueGain;\n+\t}\n+\n+\twriteAndFinish(metadata, false);\n+}\n+\n+void AgcChannel::prepare(Metadata *imageMetadata)\n+{\n+\tDuration totalExposureValue = status_.totalExposureValue;\n+\tAgcStatus delayedStatus;\n+\tAgcPrepareStatus prepareStatus;\n+\n+\tif (!imageMetadata->get(\"agc.delayed_status\", delayedStatus))\n+\t\ttotalExposureValue = delayedStatus.totalExposureValue;\n+\n+\tprepareStatus.digitalGain = 1.0;\n+\tprepareStatus.locked = false;\n+\n+\tif (status_.totalExposureValue) {\n+\t\t/* Process has run, so we have meaningful values. */\n+\t\tDeviceStatus deviceStatus;\n+\t\tif (imageMetadata->get(\"device.status\", deviceStatus) == 0) {\n+\t\t\tDuration actualExposure = deviceStatus.shutterSpeed *\n+\t\t\t\t\t\t  deviceStatus.analogueGain;\n+\t\t\tif (actualExposure) {\n+\t\t\t\tdouble digitalGain = totalExposureValue / actualExposure;\n+\t\t\t\tLOG(RPiAgc, Debug) << \"Want total exposure \" << totalExposureValue;\n+\t\t\t\t/*\n+\t\t\t\t * Never ask for a gain < 1.0, and also impose\n+\t\t\t\t * some upper limit. Make it customisable?\n+\t\t\t\t */\n+\t\t\t\tprepareStatus.digitalGain = std::max(1.0, std::min(digitalGain, 4.0));\n+\t\t\t\tLOG(RPiAgc, Debug) << \"Actual exposure \" << actualExposure;\n+\t\t\t\tLOG(RPiAgc, Debug) << \"Use digitalGain \" << prepareStatus.digitalGain;\n+\t\t\t\tLOG(RPiAgc, Debug) << \"Effective exposure \"\n+\t\t\t\t\t\t   << actualExposure * prepareStatus.digitalGain;\n+\t\t\t\t/* Decide whether AEC/AGC has converged. */\n+\t\t\t\tprepareStatus.locked = updateLockStatus(deviceStatus);\n+\t\t\t}\n+\t\t} else\n+\t\t\tLOG(RPiAgc, Warning) << \"AgcChannel: no device metadata\";\n+\t\timageMetadata->set(\"agc.prepare_status\", prepareStatus);\n+\t}\n+}\n+\n+void AgcChannel::process(StatisticsPtr &stats, Metadata *imageMetadata)\n+{\n+\tframeCount_++;\n+\t/*\n+\t * First a little bit of housekeeping, fetching up-to-date settings and\n+\t * configuration, that kind of thing.\n+\t */\n+\thousekeepConfig();\n+\t/* Fetch the AWB status immediately, so that we can assume it's there. */\n+\tfetchAwbStatus(imageMetadata);\n+\t/* Get the current exposure values for the frame that's just arrived. */\n+\tfetchCurrentExposure(imageMetadata);\n+\t/* Compute the total gain we require relative to the current exposure. */\n+\tdouble gain, targetY;\n+\tcomputeGain(stats, imageMetadata, gain, targetY);\n+\t/* Now compute the target (final) exposure which we think we want. */\n+\tcomputeTargetExposure(gain);\n+\t/* The results have to be filtered so as not to change too rapidly. */\n+\tfilterExposure();\n+\t/*\n+\t * Some of the exposure has to be applied as digital gain, so work out\n+\t * what that is. This function also tells us whether it's decided to\n+\t * \"desaturate\" the image more quickly.\n+\t */\n+\tbool desaturate = applyDigitalGain(gain, targetY);\n+\t/*\n+\t * The last thing is to divide up the exposure value into a shutter time\n+\t * and analogue gain, according to the current exposure mode.\n+\t */\n+\tdivideUpExposure();\n+\t/* Finally advertise what we've done. */\n+\twriteAndFinish(imageMetadata, desaturate);\n+}\n+\n+bool AgcChannel::updateLockStatus(DeviceStatus const &deviceStatus)\n+{\n+\tconst double errorFactor = 0.10; /* make these customisable? */\n+\tconst int maxLockCount = 5;\n+\t/* Reset \"lock count\" when we exceed this multiple of errorFactor */\n+\tconst double resetMargin = 1.5;\n+\n+\t/* Add 200us to the exposure time error to allow for line quantisation. */\n+\tDuration exposureError = lastDeviceStatus_.shutterSpeed * errorFactor + 200us;\n+\tdouble gainError = lastDeviceStatus_.analogueGain * errorFactor;\n+\tDuration targetError = lastTargetExposure_ * errorFactor;\n+\n+\t/*\n+\t * Note that we don't know the exposure/gain limits of the sensor, so\n+\t * the values we keep requesting may be unachievable. For this reason\n+\t * we only insist that we're close to values in the past few frames.\n+\t */\n+\tif (deviceStatus.shutterSpeed > lastDeviceStatus_.shutterSpeed - exposureError &&\n+\t    deviceStatus.shutterSpeed < lastDeviceStatus_.shutterSpeed + exposureError &&\n+\t    deviceStatus.analogueGain > lastDeviceStatus_.analogueGain - gainError &&\n+\t    deviceStatus.analogueGain < lastDeviceStatus_.analogueGain + gainError &&\n+\t    status_.targetExposureValue > lastTargetExposure_ - targetError &&\n+\t    status_.targetExposureValue < lastTargetExposure_ + targetError)\n+\t\tlockCount_ = std::min(lockCount_ + 1, maxLockCount);\n+\telse if (deviceStatus.shutterSpeed < lastDeviceStatus_.shutterSpeed - resetMargin * exposureError ||\n+\t\t deviceStatus.shutterSpeed > lastDeviceStatus_.shutterSpeed + resetMargin * exposureError ||\n+\t\t deviceStatus.analogueGain < lastDeviceStatus_.analogueGain - resetMargin * gainError ||\n+\t\t deviceStatus.analogueGain > lastDeviceStatus_.analogueGain + resetMargin * gainError ||\n+\t\t status_.targetExposureValue < lastTargetExposure_ - resetMargin * targetError ||\n+\t\t status_.targetExposureValue > lastTargetExposure_ + resetMargin * targetError)\n+\t\tlockCount_ = 0;\n+\n+\tlastDeviceStatus_ = deviceStatus;\n+\tlastTargetExposure_ = status_.targetExposureValue;\n+\n+\tLOG(RPiAgc, Debug) << \"Lock count updated to \" << lockCount_;\n+\treturn lockCount_ == maxLockCount;\n+}\n+\n+void AgcChannel::housekeepConfig()\n+{\n+\t/* First fetch all the up-to-date settings, so no one else has to do it. */\n+\tstatus_.ev = ev_;\n+\tstatus_.fixedShutter = limitShutter(fixedShutter_);\n+\tstatus_.fixedAnalogueGain = fixedAnalogueGain_;\n+\tstatus_.flickerPeriod = flickerPeriod_;\n+\tLOG(RPiAgc, Debug) << \"ev \" << status_.ev << \" fixedShutter \"\n+\t\t\t   << status_.fixedShutter << \" fixedAnalogueGain \"\n+\t\t\t   << status_.fixedAnalogueGain;\n+\t/*\n+\t * Make sure the \"mode\" pointers point to the up-to-date things, if\n+\t * they've changed.\n+\t */\n+\tif (meteringModeName_ != status_.meteringMode) {\n+\t\tauto it = config_.meteringModes.find(meteringModeName_);\n+\t\tif (it == config_.meteringModes.end()) {\n+\t\t\tLOG(RPiAgc, Warning) << \"No metering mode \" << meteringModeName_;\n+\t\t\tmeteringModeName_ = status_.meteringMode;\n+\t\t} else {\n+\t\t\tmeteringMode_ = &it->second;\n+\t\t\tstatus_.meteringMode = meteringModeName_;\n+\t\t}\n+\t}\n+\tif (exposureModeName_ != status_.exposureMode) {\n+\t\tauto it = config_.exposureModes.find(exposureModeName_);\n+\t\tif (it == config_.exposureModes.end()) {\n+\t\t\tLOG(RPiAgc, Warning) << \"No exposure profile \" << exposureModeName_;\n+\t\t\texposureModeName_ = status_.exposureMode;\n+\t\t} else {\n+\t\t\texposureMode_ = &it->second;\n+\t\t\tstatus_.exposureMode = exposureModeName_;\n+\t\t}\n+\t}\n+\tif (constraintModeName_ != status_.constraintMode) {\n+\t\tauto it = config_.constraintModes.find(constraintModeName_);\n+\t\tif (it == config_.constraintModes.end()) {\n+\t\t\tLOG(RPiAgc, Warning) << \"No constraint list \" << constraintModeName_;\n+\t\t\tconstraintModeName_ = status_.constraintMode;\n+\t\t} else {\n+\t\t\tconstraintMode_ = &it->second;\n+\t\t\tstatus_.constraintMode = constraintModeName_;\n+\t\t}\n+\t}\n+\tLOG(RPiAgc, Debug) << \"exposureMode \"\n+\t\t\t   << exposureModeName_ << \" constraintMode \"\n+\t\t\t   << constraintModeName_ << \" meteringMode \"\n+\t\t\t   << meteringModeName_;\n+}\n+\n+void AgcChannel::fetchCurrentExposure(Metadata *imageMetadata)\n+{\n+\tstd::unique_lock<Metadata> lock(*imageMetadata);\n+\tDeviceStatus *deviceStatus =\n+\t\timageMetadata->getLocked<DeviceStatus>(\"device.status\");\n+\tif (!deviceStatus)\n+\t\tLOG(RPiAgc, Fatal) << \"No device metadata\";\n+\tcurrent_.shutter = deviceStatus->shutterSpeed;\n+\tcurrent_.analogueGain = deviceStatus->analogueGain;\n+\tAgcStatus *agcStatus =\n+\t\timageMetadata->getLocked<AgcStatus>(\"agc.status\");\n+\tcurrent_.totalExposure = agcStatus ? agcStatus->totalExposureValue : 0s;\n+\tcurrent_.totalExposureNoDG = current_.shutter * current_.analogueGain;\n+}\n+\n+void AgcChannel::fetchAwbStatus(Metadata *imageMetadata)\n+{\n+\tawb_.gainR = 1.0; /* in case not found in metadata */\n+\tawb_.gainG = 1.0;\n+\tawb_.gainB = 1.0;\n+\tif (imageMetadata->get(\"awb.status\", awb_) != 0)\n+\t\tLOG(RPiAgc, Debug) << \"No AWB status found\";\n+}\n+\n+static double computeInitialY(StatisticsPtr &stats, AwbStatus const &awb,\n+\t\t\t      std::vector<double> &weights, double gain)\n+{\n+\tconstexpr uint64_t maxVal = 1 << Statistics::NormalisationFactorPow2;\n+\n+\t/*\n+\t * If we have no AGC region stats, but do have a a Y histogram, use that\n+\t * directly to caluclate the mean Y value of the image.\n+\t */\n+\tif (!stats->agcRegions.numRegions() && stats->yHist.bins()) {\n+\t\t/*\n+\t\t * When the gain is applied to the histogram, anything below minBin\n+\t\t * will scale up directly with the gain, but anything above that\n+\t\t * will saturate into the top bin.\n+\t\t */\n+\t\tauto &hist = stats->yHist;\n+\t\tdouble minBin = std::min(1.0, 1.0 / gain) * hist.bins();\n+\t\tdouble binMean = hist.interBinMean(0.0, minBin);\n+\t\tdouble numUnsaturated = hist.cumulativeFreq(minBin);\n+\t\t/* This term is from all the pixels that won't saturate. */\n+\t\tdouble ySum = binMean * gain * numUnsaturated;\n+\t\t/* And add the ones that will saturate. */\n+\t\tySum += (hist.total() - numUnsaturated) * hist.bins();\n+\t\treturn ySum / hist.total() / hist.bins();\n+\t}\n+\n+\tASSERT(weights.size() == stats->agcRegions.numRegions());\n+\n+\t/*\n+\t * Note that the weights are applied by the IPA to the statistics directly,\n+\t * before they are given to us here.\n+\t */\n+\tdouble rSum = 0, gSum = 0, bSum = 0, pixelSum = 0;\n+\tfor (unsigned int i = 0; i < stats->agcRegions.numRegions(); i++) {\n+\t\tauto &region = stats->agcRegions.get(i);\n+\t\trSum += std::min<double>(region.val.rSum * gain, (maxVal - 1) * region.counted);\n+\t\tgSum += std::min<double>(region.val.gSum * gain, (maxVal - 1) * region.counted);\n+\t\tbSum += std::min<double>(region.val.bSum * gain, (maxVal - 1) * region.counted);\n+\t\tpixelSum += region.counted;\n+\t}\n+\tif (pixelSum == 0.0) {\n+\t\tLOG(RPiAgc, Warning) << \"computeInitialY: pixelSum is zero\";\n+\t\treturn 0;\n+\t}\n+\n+\tdouble ySum;\n+\t/* Factor in the AWB correction if needed. */\n+\tif (stats->agcStatsPos == Statistics::AgcStatsPos::PreWb) {\n+\t\tySum = rSum * awb.gainR * .299 +\n+\t\t       gSum * awb.gainG * .587 +\n+\t\t       gSum * awb.gainB * .114;\n+\t} else\n+\t\tySum = rSum * .299 + gSum * .587 + gSum * .114;\n+\n+\treturn ySum / pixelSum / (1 << 16);\n+}\n+\n+/*\n+ * We handle extra gain through EV by adjusting our Y targets. However, you\n+ * simply can't monitor histograms once they get very close to (or beyond!)\n+ * saturation, so we clamp the Y targets to this value. It does mean that EV\n+ * increases don't necessarily do quite what you might expect in certain\n+ * (contrived) cases.\n+ */\n+\n+static constexpr double EvGainYTargetLimit = 0.9;\n+\n+static double constraintComputeGain(AgcConstraint &c, const Histogram &h, double lux,\n+\t\t\t\t    double evGain, double &targetY)\n+{\n+\ttargetY = c.yTarget.eval(c.yTarget.domain().clip(lux));\n+\ttargetY = std::min(EvGainYTargetLimit, targetY * evGain);\n+\tdouble iqm = h.interQuantileMean(c.qLo, c.qHi);\n+\treturn (targetY * h.bins()) / iqm;\n+}\n+\n+void AgcChannel::computeGain(StatisticsPtr &statistics, Metadata *imageMetadata,\n+\t\t\t     double &gain, double &targetY)\n+{\n+\tstruct LuxStatus lux = {};\n+\tlux.lux = 400; /* default lux level to 400 in case no metadata found */\n+\tif (imageMetadata->get(\"lux.status\", lux) != 0)\n+\t\tLOG(RPiAgc, Warning) << \"No lux level found\";\n+\tconst Histogram &h = statistics->yHist;\n+\tdouble evGain = status_.ev * config_.baseEv;\n+\t/*\n+\t * The initial gain and target_Y come from some of the regions. After\n+\t * that we consider the histogram constraints.\n+\t */\n+\ttargetY = config_.yTarget.eval(config_.yTarget.domain().clip(lux.lux));\n+\ttargetY = std::min(EvGainYTargetLimit, targetY * evGain);\n+\n+\t/*\n+\t * Do this calculation a few times as brightness increase can be\n+\t * non-linear when there are saturated regions.\n+\t */\n+\tgain = 1.0;\n+\tfor (int i = 0; i < 8; i++) {\n+\t\tdouble initialY = computeInitialY(statistics, awb_, meteringMode_->weights, gain);\n+\t\tdouble extraGain = std::min(10.0, targetY / (initialY + .001));\n+\t\tgain *= extraGain;\n+\t\tLOG(RPiAgc, Debug) << \"Initial Y \" << initialY << \" target \" << targetY\n+\t\t\t\t   << \" gives gain \" << gain;\n+\t\tif (extraGain < 1.01) /* close enough */\n+\t\t\tbreak;\n+\t}\n+\n+\tfor (auto &c : *constraintMode_) {\n+\t\tdouble newTargetY;\n+\t\tdouble newGain = constraintComputeGain(c, h, lux.lux, evGain, newTargetY);\n+\t\tLOG(RPiAgc, Debug) << \"Constraint has target_Y \"\n+\t\t\t\t   << newTargetY << \" giving gain \" << newGain;\n+\t\tif (c.bound == AgcConstraint::Bound::LOWER && newGain > gain) {\n+\t\t\tLOG(RPiAgc, Debug) << \"Lower bound constraint adopted\";\n+\t\t\tgain = newGain;\n+\t\t\ttargetY = newTargetY;\n+\t\t} else if (c.bound == AgcConstraint::Bound::UPPER && newGain < gain) {\n+\t\t\tLOG(RPiAgc, Debug) << \"Upper bound constraint adopted\";\n+\t\t\tgain = newGain;\n+\t\t\ttargetY = newTargetY;\n+\t\t}\n+\t}\n+\tLOG(RPiAgc, Debug) << \"Final gain \" << gain << \" (target_Y \" << targetY << \" ev \"\n+\t\t\t   << status_.ev << \" base_ev \" << config_.baseEv\n+\t\t\t   << \")\";\n+}\n+\n+void AgcChannel::computeTargetExposure(double gain)\n+{\n+\tif (status_.fixedShutter && status_.fixedAnalogueGain) {\n+\t\t/*\n+\t\t * When ag and shutter are both fixed, we need to drive the\n+\t\t * total exposure so that we end up with a digital gain of at least\n+\t\t * 1/minColourGain. Otherwise we'd desaturate channels causing\n+\t\t * white to go cyan or magenta.\n+\t\t */\n+\t\tdouble minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 });\n+\t\tASSERT(minColourGain != 0.0);\n+\t\ttarget_.totalExposure =\n+\t\t\tstatus_.fixedShutter * status_.fixedAnalogueGain / minColourGain;\n+\t} else {\n+\t\t/*\n+\t\t * The statistics reflect the image without digital gain, so the final\n+\t\t * total exposure we're aiming for is:\n+\t\t */\n+\t\ttarget_.totalExposure = current_.totalExposureNoDG * gain;\n+\t\t/* The final target exposure is also limited to what the exposure mode allows. */\n+\t\tDuration maxShutter = status_.fixedShutter\n+\t\t\t\t\t      ? status_.fixedShutter\n+\t\t\t\t\t      : exposureMode_->shutter.back();\n+\t\tmaxShutter = limitShutter(maxShutter);\n+\t\tDuration maxTotalExposure =\n+\t\t\tmaxShutter *\n+\t\t\t(status_.fixedAnalogueGain != 0.0\n+\t\t\t\t ? status_.fixedAnalogueGain\n+\t\t\t\t : exposureMode_->gain.back());\n+\t\ttarget_.totalExposure = std::min(target_.totalExposure, maxTotalExposure);\n+\t}\n+\tLOG(RPiAgc, Debug) << \"Target totalExposure \" << target_.totalExposure;\n+}\n+\n+bool AgcChannel::applyDigitalGain(double gain, double targetY)\n+{\n+\tdouble minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 });\n+\tASSERT(minColourGain != 0.0);\n+\tdouble dg = 1.0 / minColourGain;\n+\t/*\n+\t * I think this pipeline subtracts black level and rescales before we\n+\t * get the stats, so no need to worry about it.\n+\t */\n+\tLOG(RPiAgc, Debug) << \"after AWB, target dg \" << dg << \" gain \" << gain\n+\t\t\t   << \" target_Y \" << targetY;\n+\t/*\n+\t * Finally, if we're trying to reduce exposure but the target_Y is\n+\t * \"close\" to 1.0, then the gain computed for that constraint will be\n+\t * only slightly less than one, because the measured Y can never be\n+\t * larger than 1.0. When this happens, demand a large digital gain so\n+\t * that the exposure can be reduced, de-saturating the image much more\n+\t * quickly (and we then approach the correct value more quickly from\n+\t * below).\n+\t */\n+\tbool desaturate = targetY > config_.fastReduceThreshold &&\n+\t\t\t  gain < sqrt(targetY);\n+\tif (desaturate)\n+\t\tdg /= config_.fastReduceThreshold;\n+\tLOG(RPiAgc, Debug) << \"Digital gain \" << dg << \" desaturate? \" << desaturate;\n+\tfiltered_.totalExposureNoDG = filtered_.totalExposure / dg;\n+\tLOG(RPiAgc, Debug) << \"Target totalExposureNoDG \" << filtered_.totalExposureNoDG;\n+\treturn desaturate;\n+}\n+\n+void AgcChannel::filterExposure()\n+{\n+\tdouble speed = config_.speed;\n+\t/*\n+\t * AGC adapts instantly if both shutter and gain are directly specified\n+\t * or we're in the startup phase.\n+\t */\n+\tif ((status_.fixedShutter && status_.fixedAnalogueGain) ||\n+\t    frameCount_ <= config_.startupFrames)\n+\t\tspeed = 1.0;\n+\tif (!filtered_.totalExposure) {\n+\t\tfiltered_.totalExposure = target_.totalExposure;\n+\t} else {\n+\t\t/*\n+\t\t * If close to the result go faster, to save making so many\n+\t\t * micro-adjustments on the way. (Make this customisable?)\n+\t\t */\n+\t\tif (filtered_.totalExposure < 1.2 * target_.totalExposure &&\n+\t\t    filtered_.totalExposure > 0.8 * target_.totalExposure)\n+\t\t\tspeed = sqrt(speed);\n+\t\tfiltered_.totalExposure = speed * target_.totalExposure +\n+\t\t\t\t\t  filtered_.totalExposure * (1.0 - speed);\n+\t}\n+\tLOG(RPiAgc, Debug) << \"After filtering, totalExposure \" << filtered_.totalExposure\n+\t\t\t   << \" no dg \" << filtered_.totalExposureNoDG;\n+}\n+\n+void AgcChannel::divideUpExposure()\n+{\n+\t/*\n+\t * Sending the fixed shutter/gain cases through the same code may seem\n+\t * unnecessary, but it will make more sense when extend this to cover\n+\t * variable aperture.\n+\t */\n+\tDuration exposureValue = filtered_.totalExposureNoDG;\n+\tDuration shutterTime;\n+\tdouble analogueGain;\n+\tshutterTime = status_.fixedShutter ? status_.fixedShutter\n+\t\t\t\t\t   : exposureMode_->shutter[0];\n+\tshutterTime = limitShutter(shutterTime);\n+\tanalogueGain = status_.fixedAnalogueGain != 0.0 ? status_.fixedAnalogueGain\n+\t\t\t\t\t\t\t: exposureMode_->gain[0];\n+\tanalogueGain = limitGain(analogueGain);\n+\tif (shutterTime * analogueGain < exposureValue) {\n+\t\tfor (unsigned int stage = 1;\n+\t\t     stage < exposureMode_->gain.size(); stage++) {\n+\t\t\tif (!status_.fixedShutter) {\n+\t\t\t\tDuration stageShutter =\n+\t\t\t\t\tlimitShutter(exposureMode_->shutter[stage]);\n+\t\t\t\tif (stageShutter * analogueGain >= exposureValue) {\n+\t\t\t\t\tshutterTime = exposureValue / analogueGain;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tshutterTime = stageShutter;\n+\t\t\t}\n+\t\t\tif (status_.fixedAnalogueGain == 0.0) {\n+\t\t\t\tif (exposureMode_->gain[stage] * shutterTime >= exposureValue) {\n+\t\t\t\t\tanalogueGain = exposureValue / shutterTime;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tanalogueGain = exposureMode_->gain[stage];\n+\t\t\t\tanalogueGain = limitGain(analogueGain);\n+\t\t\t}\n+\t\t}\n+\t}\n+\tLOG(RPiAgc, Debug) << \"Divided up shutter and gain are \" << shutterTime << \" and \"\n+\t\t\t   << analogueGain;\n+\t/*\n+\t * Finally adjust shutter time for flicker avoidance (require both\n+\t * shutter and gain not to be fixed).\n+\t */\n+\tif (!status_.fixedShutter && !status_.fixedAnalogueGain &&\n+\t    status_.flickerPeriod) {\n+\t\tint flickerPeriods = shutterTime / status_.flickerPeriod;\n+\t\tif (flickerPeriods) {\n+\t\t\tDuration newShutterTime = flickerPeriods * status_.flickerPeriod;\n+\t\t\tanalogueGain *= shutterTime / newShutterTime;\n+\t\t\t/*\n+\t\t\t * We should still not allow the ag to go over the\n+\t\t\t * largest value in the exposure mode. Note that this\n+\t\t\t * may force more of the total exposure into the digital\n+\t\t\t * gain as a side-effect.\n+\t\t\t */\n+\t\t\tanalogueGain = std::min(analogueGain, exposureMode_->gain.back());\n+\t\t\tanalogueGain = limitGain(analogueGain);\n+\t\t\tshutterTime = newShutterTime;\n+\t\t}\n+\t\tLOG(RPiAgc, Debug) << \"After flicker avoidance, shutter \"\n+\t\t\t\t   << shutterTime << \" gain \" << analogueGain;\n+\t}\n+\tfiltered_.shutter = shutterTime;\n+\tfiltered_.analogueGain = analogueGain;\n+}\n+\n+void AgcChannel::writeAndFinish(Metadata *imageMetadata, bool desaturate)\n+{\n+\tstatus_.totalExposureValue = filtered_.totalExposure;\n+\tstatus_.targetExposureValue = desaturate ? 0s : target_.totalExposureNoDG;\n+\tstatus_.shutterTime = filtered_.shutter;\n+\tstatus_.analogueGain = filtered_.analogueGain;\n+\t/*\n+\t * Write to metadata as well, in case anyone wants to update the camera\n+\t * immediately.\n+\t */\n+\timageMetadata->set(\"agc.status\", status_);\n+\tLOG(RPiAgc, Debug) << \"Output written, total exposure requested is \"\n+\t\t\t   << filtered_.totalExposure;\n+\tLOG(RPiAgc, Debug) << \"Camera exposure update: shutter time \" << filtered_.shutter\n+\t\t\t   << \" analogue gain \" << filtered_.analogueGain;\n+}\n+\n+Duration AgcChannel::limitShutter(Duration shutter)\n+{\n+\t/*\n+\t * shutter == 0 is a special case for fixed shutter values, and must pass\n+\t * through unchanged\n+\t */\n+\tif (!shutter)\n+\t\treturn shutter;\n+\n+\tshutter = std::clamp(shutter, mode_.minShutter, maxShutter_);\n+\treturn shutter;\n+}\n+\n+double AgcChannel::limitGain(double gain) const\n+{\n+\t/*\n+\t * Only limit the lower bounds of the gain value to what the sensor limits.\n+\t * The upper bound on analogue gain will be made up with additional digital\n+\t * gain applied by the ISP.\n+\t *\n+\t * gain == 0.0 is a special case for fixed shutter values, and must pass\n+\t * through unchanged\n+\t */\n+\tif (!gain)\n+\t\treturn gain;\n+\n+\tgain = std::max(gain, mode_.minAnalogueGain);\n+\treturn gain;\n+}\ndiff --git a/src/ipa/rpi/controller/rpi/agc_channel.h b/src/ipa/rpi/controller/rpi/agc_channel.h\nnew file mode 100644\nindex 00000000..d5a5cf3a\n--- /dev/null\n+++ b/src/ipa/rpi/controller/rpi/agc_channel.h\n@@ -0,0 +1,137 @@\n+/* SPDX-License-Identifier: BSD-2-Clause */\n+/*\n+ * Copyright (C) 2023, Raspberry Pi Ltd\n+ *\n+ * agc.h - AGC/AEC control algorithm\n+ */\n+#pragma once\n+\n+#include <map>\n+#include <string>\n+#include <vector>\n+\n+#include <libcamera/base/utils.h>\n+\n+#include \"../agc_status.h\"\n+#include \"../awb_status.h\"\n+#include \"../controller.h\"\n+#include \"../pwl.h\"\n+\n+/* This is our implementation of AGC. */\n+\n+namespace RPiController {\n+\n+struct AgcMeteringMode {\n+\tstd::vector<double> weights;\n+\tint read(const libcamera::YamlObject &params);\n+};\n+\n+struct AgcExposureMode {\n+\tstd::vector<libcamera::utils::Duration> shutter;\n+\tstd::vector<double> gain;\n+\tint read(const libcamera::YamlObject &params);\n+};\n+\n+struct AgcConstraint {\n+\tenum class Bound { LOWER = 0,\n+\t\t\t   UPPER = 1 };\n+\tBound bound;\n+\tdouble qLo;\n+\tdouble qHi;\n+\tPwl yTarget;\n+\tint read(const libcamera::YamlObject &params);\n+};\n+\n+typedef std::vector<AgcConstraint> AgcConstraintMode;\n+\n+struct AgcConfig {\n+\tint read(const libcamera::YamlObject &params);\n+\tstd::map<std::string, AgcMeteringMode> meteringModes;\n+\tstd::map<std::string, AgcExposureMode> exposureModes;\n+\tstd::map<std::string, AgcConstraintMode> constraintModes;\n+\tPwl yTarget;\n+\tdouble speed;\n+\tuint16_t startupFrames;\n+\tunsigned int convergenceFrames;\n+\tdouble maxChange;\n+\tdouble minChange;\n+\tdouble fastReduceThreshold;\n+\tdouble speedUpThreshold;\n+\tstd::string defaultMeteringMode;\n+\tstd::string defaultExposureMode;\n+\tstd::string defaultConstraintMode;\n+\tdouble baseEv;\n+\tlibcamera::utils::Duration defaultExposureTime;\n+\tdouble defaultAnalogueGain;\n+};\n+\n+class AgcChannel\n+{\n+public:\n+\tAgcChannel();\n+\tint read(const libcamera::YamlObject &params,\n+\t\t const Controller::HardwareConfig &hardwareConfig);\n+\tunsigned int getConvergenceFrames() const;\n+\tstd::vector<double> const &getWeights() const;\n+\tvoid setEv(double ev);\n+\tvoid setFlickerPeriod(libcamera::utils::Duration flickerPeriod);\n+\tvoid setMaxShutter(libcamera::utils::Duration maxShutter);\n+\tvoid setFixedShutter(libcamera::utils::Duration fixedShutter);\n+\tvoid setFixedAnalogueGain(double fixedAnalogueGain);\n+\tvoid setMeteringMode(std::string const &meteringModeName);\n+\tvoid setExposureMode(std::string const &exposureModeName);\n+\tvoid setConstraintMode(std::string const &contraintModeName);\n+\tvoid enableAuto();\n+\tvoid disableAuto();\n+\tvoid switchMode(CameraMode const &cameraMode, Metadata *metadata);\n+\tvoid prepare(Metadata *imageMetadata);\n+\tvoid process(StatisticsPtr &stats, Metadata *imageMetadata);\n+\n+private:\n+\tbool updateLockStatus(DeviceStatus const &deviceStatus);\n+\tAgcConfig config_;\n+\tvoid housekeepConfig();\n+\tvoid fetchCurrentExposure(Metadata *imageMetadata);\n+\tvoid fetchAwbStatus(Metadata *imageMetadata);\n+\tvoid computeGain(StatisticsPtr &statistics, Metadata *imageMetadata,\n+\t\t\t double &gain, double &targetY);\n+\tvoid computeTargetExposure(double gain);\n+\tvoid filterExposure();\n+\tbool applyDigitalGain(double gain, double targetY);\n+\tvoid divideUpExposure();\n+\tvoid writeAndFinish(Metadata *imageMetadata, bool desaturate);\n+\tlibcamera::utils::Duration limitShutter(libcamera::utils::Duration shutter);\n+\tdouble limitGain(double gain) const;\n+\tAgcMeteringMode *meteringMode_;\n+\tAgcExposureMode *exposureMode_;\n+\tAgcConstraintMode *constraintMode_;\n+\tCameraMode mode_;\n+\tuint64_t frameCount_;\n+\tAwbStatus awb_;\n+\tstruct ExposureValues {\n+\t\tExposureValues();\n+\n+\t\tlibcamera::utils::Duration shutter;\n+\t\tdouble analogueGain;\n+\t\tlibcamera::utils::Duration totalExposure;\n+\t\tlibcamera::utils::Duration totalExposureNoDG; /* without digital gain */\n+\t};\n+\tExposureValues current_; /* values for the current frame */\n+\tExposureValues target_; /* calculate the values we want here */\n+\tExposureValues filtered_; /* these values are filtered towards target */\n+\tAgcStatus status_;\n+\tint lockCount_;\n+\tDeviceStatus lastDeviceStatus_;\n+\tlibcamera::utils::Duration lastTargetExposure_;\n+\t/* Below here the \"settings\" that applications can change. */\n+\tstd::string meteringModeName_;\n+\tstd::string exposureModeName_;\n+\tstd::string constraintModeName_;\n+\tdouble ev_;\n+\tlibcamera::utils::Duration flickerPeriod_;\n+\tlibcamera::utils::Duration maxShutter_;\n+\tlibcamera::utils::Duration fixedShutter_;\n+\tdouble fixedAnalogueGain_;\n+};\n+\n+} /* namespace RPiController */\n",
    "prefixes": [
        "libcamera-devel",
        "v3",
        "2/5"
    ]
}