From patchwork Fri Sep 15 15:58:40 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: David Plowman X-Patchwork-Id: 19034 Return-Path: X-Original-To: parsemail@patchwork.libcamera.org Delivered-To: parsemail@patchwork.libcamera.org Received: from lancelot.ideasonboard.com (lancelot.ideasonboard.com [92.243.16.209]) by patchwork.libcamera.org (Postfix) with ESMTPS id 929BBBD160 for ; Fri, 15 Sep 2023 15:58:52 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 49E7A6291D; Fri, 15 Sep 2023 17:58:52 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=libcamera.org; s=mail; t=1694793532; bh=u61zsKeWhQAgxve5YcLlCpBT79AgLH4OcJpd3Ged9qE=; h=To:Date:In-Reply-To:References:Subject:List-Id:List-Unsubscribe: List-Archive:List-Post:List-Help:List-Subscribe:From:Reply-To:Cc: From; b=RdQ3kdZm62NGOydpXRvlvgOKi0pZI2mlemQoTYksBWvjdfllz0+6NpxajqLOvVphh rNt4KYAKz2BhUBYWx+kjScIrLOp5DQ7Z4AqQ3aPaxm9SiWTfpWIRc1ZKxYmAdPg+p4 5NmYAIOuEltYKQFwhwFkxuRqdMC3x4rbtsM5AYGTeS+SwmlYefo+nR/wK9aA8JvlGu z3yR9U+7QpRtUwW3lptmeDISaRAI4oPDgXT1TyUr1tauwvZxvFilh9+epD+oDb+jEl /yp3tWrqW9fLxH81apQn6gOuHkOP+TQJNHgPxOLyHa/SKxp9zJsuev3FqaMwUEv08L nqPDzTprAIS5g== Received: from mail-wm1-x32b.google.com (mail-wm1-x32b.google.com [IPv6:2a00:1450:4864:20::32b]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 42DA9628EC for ; Fri, 15 Sep 2023 17:58:51 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (2048-bit key; unprotected) header.d=raspberrypi.com header.i=@raspberrypi.com header.b="kes1vK9U"; dkim-atps=neutral Received: by mail-wm1-x32b.google.com with SMTP id 5b1f17b1804b1-40434d284f7so22809895e9.3 for ; Fri, 15 Sep 2023 08:58:51 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=raspberrypi.com; s=google; t=1694793530; x=1695398330; darn=lists.libcamera.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=PLzIHdZWYnWfcoP1tg/UVALNkMV3EEqa5nrqb1B3Op8=; b=kes1vK9Ui66o6hXXzrZOvNZ+lnEQS5P97c48etkxv8ush37OpspghZBFk8+o2cutk0 8h/VHOcAnHIyUnDPyJahjmpHa+5CAiaQeQiaikDNJEq5e02H9q4of/hFxN35OfQm04am 3pjCjvr6Mf4nOSvq6HSTZO8IpMWun3ikIfAlRUWoKXfgyOXlRgMwhkTwlT/wPrb5ETNc eO3L8G2GP0jqKUfAc+X+GJzjKmarK+h7Q1e0rgGMF5A2s2VjLyyDUcNHEkRSSpgOE9CM fLqJHqFDDRuHytB238RTxX9AHlX7E6gH9g8QRh4p3BiPRt9UWGMZrnPysIPnwg7jJkjx ysHw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1694793530; x=1695398330; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=PLzIHdZWYnWfcoP1tg/UVALNkMV3EEqa5nrqb1B3Op8=; b=tOXgX9T2pm1Ww1iHbc4dF6iOj6243OfgKU0LRhunuDe0IymI0c3RAP6G0KM4gpqqIw 5BAQag53qIgzp62LvmP1iqTwJBMTQdll2zLp8l8mfLxJUun739hyNVFMwN5zUIY+4j1R tH1kFEPYFhFWiKtYAst5ZOtWSdGOF1kGgGE2uiY+HKOqfz66ct8Zpf2eTL6iAevNeoCx If6rLqNGMPHwmiqE5TU0d0fRNbztbHN3sB/Dy/WpaKtsXmaHfBZ7LMnzyxt8JojY1eo0 5bFyO92HPuLRP0QRUpiqaRG8zLwTRFU/ixMGCoWkTVi1CaBhQRed/xaRpzCQ3GYJmnGt hNfA== X-Gm-Message-State: AOJu0Yx5bXY7eCQV8tIW1yITfcfyCJZnn46wemSl55tf1zqhNAYkAcjm VPSD29vVh36+GIoOh6N5q9GsiB1uwV5q9duHujU= X-Google-Smtp-Source: AGHT+IHRy+DMKozH3lm8b1nPEFOfpKKlhWRzDIxxODNP1GLolMLUmIObx6lEr3FTWwlkJWBORlLaRw== X-Received: by 2002:a7b:c4cb:0:b0:401:b53e:6c56 with SMTP id g11-20020a7bc4cb000000b00401b53e6c56mr2227815wmk.3.1694793530403; Fri, 15 Sep 2023 08:58:50 -0700 (PDT) Received: from localhost.localdomain ([195.180.61.40]) by smtp.gmail.com with ESMTPSA id l13-20020a7bc44d000000b00401c595fcc7sm7810618wmi.11.2023.09.15.08.58.47 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 15 Sep 2023 08:58:47 -0700 (PDT) To: libcamera-devel@lists.libcamera.org Date: Fri, 15 Sep 2023 16:58:40 +0100 Message-Id: <20230915155844.2388-2-david.plowman@raspberrypi.com> X-Mailer: git-send-email 2.30.2 In-Reply-To: <20230915155844.2388-1-david.plowman@raspberrypi.com> References: <20230915155844.2388-1-david.plowman@raspberrypi.com> MIME-Version: 1.0 Subject: [libcamera-devel] [PATCH v5 1/5] ipa: rpi: histogram: Add interBinMean() X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Patchwork-Original-From: David Plowman via libcamera-devel From: David Plowman Reply-To: David Plowman Cc: Jacopo Mondi Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" From: Naushir Patuck Add a new helper function Histogram::interBinMean() that essentially replaces the existing Histogram::interQuantileMean() logic but working on bins instead. Rework the interQuantileMean() to call into interBinMean() with the appropriate convertion from quatiles to bins. Signed-off-by: Naushir Patuck Reviewed-by: David Plowman Reviewed-by: Jacopo Mondi --- src/ipa/rpi/controller/histogram.cpp | 22 ++++++++++++++-------- src/ipa/rpi/controller/histogram.h | 2 ++ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/ipa/rpi/controller/histogram.cpp b/src/ipa/rpi/controller/histogram.cpp index 16a9207f..0a27ba2c 100644 --- a/src/ipa/rpi/controller/histogram.cpp +++ b/src/ipa/rpi/controller/histogram.cpp @@ -45,20 +45,26 @@ double Histogram::quantile(double q, int first, int last) const return first + frac; } -double Histogram::interQuantileMean(double qLo, double qHi) const +double Histogram::interBinMean(double binLo, double binHi) const { - assert(qHi > qLo); - double pLo = quantile(qLo); - double pHi = quantile(qHi, (int)pLo); + assert(binHi > binLo); double sumBinFreq = 0, cumulFreq = 0; - for (double pNext = floor(pLo) + 1.0; pNext <= ceil(pHi); - pLo = pNext, pNext += 1.0) { - int bin = floor(pLo); + for (double binNext = floor(binLo) + 1.0; binNext <= ceil(binHi); + binLo = binNext, binNext += 1.0) { + int bin = floor(binLo); double freq = (cumulative_[bin + 1] - cumulative_[bin]) * - (std::min(pNext, pHi) - pLo); + (std::min(binNext, binHi) - binLo); sumBinFreq += bin * freq; cumulFreq += freq; } /* add 0.5 to give an average for bin mid-points */ return sumBinFreq / cumulFreq + 0.5; } + +double Histogram::interQuantileMean(double qLo, double qHi) const +{ + assert(qHi > qLo); + double pLo = quantile(qLo); + double pHi = quantile(qHi, (int)pLo); + return interBinMean(pLo, pHi); +} diff --git a/src/ipa/rpi/controller/histogram.h b/src/ipa/rpi/controller/histogram.h index 6b3e3a9e..e2c5509b 100644 --- a/src/ipa/rpi/controller/histogram.h +++ b/src/ipa/rpi/controller/histogram.h @@ -38,6 +38,8 @@ public: uint64_t total() const { return cumulative_[cumulative_.size() - 1]; } /* Cumulative frequency up to a (fractional) point in a bin. */ uint64_t cumulativeFreq(double bin) const; + /* Return the mean value between two (fractional) bins. */ + double interBinMean(double binLo, double binHi) const; /* * Return the (fractional) bin of the point q (0 <= q <= 1) through the * histogram. Optionally provide limits to help. From patchwork Fri Sep 15 15:58:41 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: David Plowman X-Patchwork-Id: 19036 Return-Path: X-Original-To: parsemail@patchwork.libcamera.org Delivered-To: parsemail@patchwork.libcamera.org Received: from lancelot.ideasonboard.com (lancelot.ideasonboard.com [92.243.16.209]) by patchwork.libcamera.org (Postfix) with ESMTPS id E076DC3260 for ; Fri, 15 Sep 2023 15:58:57 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 83B2F628EC; Fri, 15 Sep 2023 17:58:57 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=libcamera.org; s=mail; t=1694793537; bh=TaqxXdeVvQaP6eO7IsHQcKVYKCdJYS8bToCTEt9fTuU=; h=To:Date:In-Reply-To:References:Subject:List-Id:List-Unsubscribe: List-Archive:List-Post:List-Help:List-Subscribe:From:Reply-To:Cc: From; b=pSfUF5pgwtBWgkhySysZJfRn9ZscMK6ZBfyvE0v+zPdvN18xvXDA3qNv4E8K8B4la XxXvSRBilhpsmYw6IpfXdDjkJmb/dahMv1eNamlQwvrBzGJEXrZ6xDA5/E2nzK9Xth fAlrgt9P3EgnG9OhzKIOO0DrBz4e2h5mArZv2L6hERWQkG+1vkvcmAnxBIS3zjytC2 M84jVNgZuZTz/YogGeNSOK8ivQwpq/IOPQLFlcePE0ZnKKg7lcGIeU5DzmUDWrhdcu eb4962kmE+VzARjcMe49BWuE9kNxYjTAh/6Qe75u8dCJi8KzEYA5eDi3EBUkhwJuXu 7wzYL6PqrTg8Q== Received: from mail-wm1-x333.google.com (mail-wm1-x333.google.com [IPv6:2a00:1450:4864:20::333]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 21A3162916 for ; Fri, 15 Sep 2023 17:58:55 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (2048-bit key; unprotected) header.d=raspberrypi.com header.i=@raspberrypi.com header.b="h0z5iJve"; dkim-atps=neutral Received: by mail-wm1-x333.google.com with SMTP id 5b1f17b1804b1-40472f9db24so20705485e9.2 for ; Fri, 15 Sep 2023 08:58:55 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=raspberrypi.com; s=google; t=1694793534; x=1695398334; darn=lists.libcamera.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=8yjhpMB1y63U7BN8aWl1A5Zw7GlWT6yLsKOyOU454do=; b=h0z5iJveDV0NjcEXygbkn9D13ekeJUrzKSNsFBHzHoxgKJU94djavRWdT3g4kUfP/Z GCAAoQbLpR56UH5ASz4YKgyGrzF5EjyNYT8htzlCFQOXrkgB7h3VGBU0qNNoVJ/4nkC7 2K5OZ8Bx9quvzRahGBhcXjz3IUP1g6EZTPzNvNMHN3nKOGnF9EJY6wVamcAU9ZFnpAov vgVPWM3fZZsS9jFrkpm2B25PjjDr8sMjot8OypfjEvGJEebXL8CfUt/a2p4BGvgggl5I HOtycrTn3Otf3di7trBVaOpGP988EiIAddEYWhN6G0kOR+k5B1ByHGJylaXYmg0O1NEm dZ9w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1694793534; x=1695398334; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=8yjhpMB1y63U7BN8aWl1A5Zw7GlWT6yLsKOyOU454do=; b=VGtKVzHjPr7PCW8utsoE9oVMPlaqtAZWBBNOdSF/feqY70OTQ/FgnsleV4k0KYPfLm wu9MPkQ6VAHYJgBCRO54FjZBBptaM5WVoWdQN2YsLcvzP3yb7zd0/OFkwpzsH3SXSQ+n xDsceSdbx4Xvoczlo1yv1r5xU/dRLXPXQEreg8rBhk0AkeTZvVetmzzcojlOhmO9lD0j p+N8UAAyxUb5tN/6yMfJ5bhKH/u6Zo3FIlXkPWoSBY10x8WY2PbzLKX8y+Wk5/CtZ0mk aAFvd572hWGdvGXfc7yTGyhppXy4tpNXbkq/EGWMchPrTRXYYRl1rON7G1bRa+dp8jI2 IcqQ== X-Gm-Message-State: AOJu0YwnlwrktoKYi80/pStvGX1zfc5HfwgSEzMyq3dG3yg9dCT3unjR mANoq4LBmp7YC7QfhSCZM5130h6JaiG2YVDbxYA= X-Google-Smtp-Source: AGHT+IE/xri016QDVQyNfPSuCW/Ef6bYTeP9BfQ2sI3Px2tZWyAhRU9h/t1WNs1xy82l+eCkT08f4g== X-Received: by 2002:a7b:ca5a:0:b0:402:e68f:8896 with SMTP id m26-20020a7bca5a000000b00402e68f8896mr1941481wml.0.1694793532882; Fri, 15 Sep 2023 08:58:52 -0700 (PDT) Received: from localhost.localdomain ([195.180.61.40]) by smtp.gmail.com with ESMTPSA id l13-20020a7bc44d000000b00401c595fcc7sm7810618wmi.11.2023.09.15.08.58.50 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 15 Sep 2023 08:58:51 -0700 (PDT) To: libcamera-devel@lists.libcamera.org Date: Fri, 15 Sep 2023 16:58:41 +0100 Message-Id: <20230915155844.2388-3-david.plowman@raspberrypi.com> X-Mailer: git-send-email 2.30.2 In-Reply-To: <20230915155844.2388-1-david.plowman@raspberrypi.com> References: <20230915155844.2388-1-david.plowman@raspberrypi.com> MIME-Version: 1.0 Subject: [libcamera-devel] [PATCH v5 2/5] ipa: rpi: agc: Reorganise code for multi-channel AGC X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Patchwork-Original-From: David Plowman via libcamera-devel From: David Plowman Reply-To: David Plowman Cc: Jacopo Mondi Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" This commit does the basic reorganisation of the code in order to implement multi-channel AGC. The main changes are: * The previous Agc class (in agc.cpp) has become the AgcChannel class in (agc_channel.cpp). * A new Agc class is introduced which is a wrapper round a number of AgcChannels. * The basic plumbing from ipa_base.cpp to Agc is updated to include a channel number. All the existing controls are hardwired to talk directly to channel 0. There are a couple of limitations which we expect to apply to multi-channel AGC. We're not allowing different frame durations to be applied to the channels, nor are we allowing separate metering modes. To be fair, supporting these things is not impossible, but there are reasons why it may be tricky so they remain "TBD" for now. This patch only includes the basic reorganisation and plumbing. It does not yet update the important methods (switchMode, prepare and process) to implement multi-channel AGC properly. This will appear in a subsequent commit. For now, these functions are hard-coded just to use channel 0, thereby preserving the existing behaviour. Signed-off-by: David Plowman Reviewed-by: Naushir Patuck Reviewed-by: Jacopo Mondi --- src/ipa/rpi/common/ipa_base.cpp | 20 +- src/ipa/rpi/controller/agc_algorithm.h | 19 +- src/ipa/rpi/controller/meson.build | 1 + src/ipa/rpi/controller/rpi/agc.cpp | 912 +++----------------- src/ipa/rpi/controller/rpi/agc.h | 120 +-- src/ipa/rpi/controller/rpi/agc_channel.cpp | 924 +++++++++++++++++++++ src/ipa/rpi/controller/rpi/agc_channel.h | 137 +++ 7 files changed, 1218 insertions(+), 915 deletions(-) create mode 100644 src/ipa/rpi/controller/rpi/agc_channel.cpp create mode 100644 src/ipa/rpi/controller/rpi/agc_channel.h diff --git a/src/ipa/rpi/common/ipa_base.cpp b/src/ipa/rpi/common/ipa_base.cpp index a47ae3a9..f7e7ad5e 100644 --- a/src/ipa/rpi/common/ipa_base.cpp +++ b/src/ipa/rpi/common/ipa_base.cpp @@ -699,9 +699,9 @@ void IpaBase::applyControls(const ControlList &controls) } if (ctrl.second.get() == false) - agc->disableAuto(); + agc->disableAuto(0); else - agc->enableAuto(); + agc->enableAuto(0); libcameraMetadata_.set(controls::AeEnable, ctrl.second.get()); break; @@ -717,7 +717,7 @@ void IpaBase::applyControls(const ControlList &controls) } /* The control provides units of microseconds. */ - agc->setFixedShutter(ctrl.second.get() * 1.0us); + agc->setFixedShutter(0, ctrl.second.get() * 1.0us); libcameraMetadata_.set(controls::ExposureTime, ctrl.second.get()); break; @@ -732,7 +732,7 @@ void IpaBase::applyControls(const ControlList &controls) break; } - agc->setFixedAnalogueGain(ctrl.second.get()); + agc->setFixedAnalogueGain(0, ctrl.second.get()); libcameraMetadata_.set(controls::AnalogueGain, ctrl.second.get()); @@ -770,7 +770,7 @@ void IpaBase::applyControls(const ControlList &controls) int32_t idx = ctrl.second.get(); if (ConstraintModeTable.count(idx)) { - agc->setConstraintMode(ConstraintModeTable.at(idx)); + agc->setConstraintMode(0, ConstraintModeTable.at(idx)); libcameraMetadata_.set(controls::AeConstraintMode, idx); } else { LOG(IPARPI, Error) << "Constraint mode " << idx @@ -790,7 +790,7 @@ void IpaBase::applyControls(const ControlList &controls) int32_t idx = ctrl.second.get(); if (ExposureModeTable.count(idx)) { - agc->setExposureMode(ExposureModeTable.at(idx)); + agc->setExposureMode(0, ExposureModeTable.at(idx)); libcameraMetadata_.set(controls::AeExposureMode, idx); } else { LOG(IPARPI, Error) << "Exposure mode " << idx @@ -813,7 +813,7 @@ void IpaBase::applyControls(const ControlList &controls) * So convert to 2^EV */ double ev = pow(2.0, ctrl.second.get()); - agc->setEv(ev); + agc->setEv(0, ev); libcameraMetadata_.set(controls::ExposureValue, ctrl.second.get()); break; @@ -833,12 +833,12 @@ void IpaBase::applyControls(const ControlList &controls) switch (mode) { case controls::FlickerOff: - agc->setFlickerPeriod(0us); + agc->setFlickerPeriod(0, 0us); break; case controls::FlickerManual: - agc->setFlickerPeriod(flickerState_.manualPeriod); + agc->setFlickerPeriod(0, flickerState_.manualPeriod); break; @@ -872,7 +872,7 @@ void IpaBase::applyControls(const ControlList &controls) * first, and the period updated after, or vice versa. */ if (flickerState_.mode == controls::FlickerManual) - agc->setFlickerPeriod(flickerState_.manualPeriod); + agc->setFlickerPeriod(0, flickerState_.manualPeriod); break; } diff --git a/src/ipa/rpi/controller/agc_algorithm.h b/src/ipa/rpi/controller/agc_algorithm.h index b6949daa..b8986560 100644 --- a/src/ipa/rpi/controller/agc_algorithm.h +++ b/src/ipa/rpi/controller/agc_algorithm.h @@ -21,16 +21,19 @@ public: /* An AGC algorithm must provide the following: */ virtual unsigned int getConvergenceFrames() const = 0; virtual std::vector const &getWeights() const = 0; - virtual void setEv(double ev) = 0; - virtual void setFlickerPeriod(libcamera::utils::Duration flickerPeriod) = 0; - virtual void setFixedShutter(libcamera::utils::Duration fixedShutter) = 0; + virtual void setEv(unsigned int channel, double ev) = 0; + virtual void setFlickerPeriod(unsigned int channel, + libcamera::utils::Duration flickerPeriod) = 0; + virtual void setFixedShutter(unsigned int channel, + libcamera::utils::Duration fixedShutter) = 0; virtual void setMaxShutter(libcamera::utils::Duration maxShutter) = 0; - virtual void setFixedAnalogueGain(double fixedAnalogueGain) = 0; + virtual void setFixedAnalogueGain(unsigned int channel, double fixedAnalogueGain) = 0; virtual void setMeteringMode(std::string const &meteringModeName) = 0; - virtual void setExposureMode(std::string const &exposureModeName) = 0; - virtual void setConstraintMode(std::string const &contraintModeName) = 0; - virtual void enableAuto() = 0; - virtual void disableAuto() = 0; + virtual void setExposureMode(unsigned int channel, std::string const &exposureModeName) = 0; + virtual void setConstraintMode(unsigned int channel, std::string const &contraintModeName) = 0; + virtual void enableAuto(unsigned int channel) = 0; + virtual void disableAuto(unsigned int channel) = 0; + virtual void setActiveChannels(const std::vector &activeChannels) = 0; }; } /* namespace RPiController */ diff --git a/src/ipa/rpi/controller/meson.build b/src/ipa/rpi/controller/meson.build index feb0334e..20b9cda9 100644 --- a/src/ipa/rpi/controller/meson.build +++ b/src/ipa/rpi/controller/meson.build @@ -8,6 +8,7 @@ rpi_ipa_controller_sources = files([ 'pwl.cpp', 'rpi/af.cpp', 'rpi/agc.cpp', + 'rpi/agc_channel.cpp', 'rpi/alsc.cpp', 'rpi/awb.cpp', 'rpi/black_level.cpp', diff --git a/src/ipa/rpi/controller/rpi/agc.cpp b/src/ipa/rpi/controller/rpi/agc.cpp index 7b02972a..598fc890 100644 --- a/src/ipa/rpi/controller/rpi/agc.cpp +++ b/src/ipa/rpi/controller/rpi/agc.cpp @@ -5,20 +5,12 @@ * agc.cpp - AGC/AEC control algorithm */ -#include -#include -#include +#include "agc.h" #include -#include "../awb_status.h" -#include "../device_status.h" -#include "../histogram.h" -#include "../lux_status.h" #include "../metadata.h" -#include "agc.h" - using namespace RPiController; using namespace libcamera; using libcamera::utils::Duration; @@ -28,881 +20,205 @@ LOG_DEFINE_CATEGORY(RPiAgc) #define NAME "rpi.agc" -int AgcMeteringMode::read(const libcamera::YamlObject ¶ms) +Agc::Agc(Controller *controller) + : AgcAlgorithm(controller), + activeChannels_({ 0 }) { - const YamlObject &yamlWeights = params["weights"]; - - for (const auto &p : yamlWeights.asList()) { - auto value = p.get(); - if (!value) - return -EINVAL; - weights.push_back(*value); - } - - return 0; } -static std::tuple -readMeteringModes(std::map &metering_modes, - const libcamera::YamlObject ¶ms) +char const *Agc::name() const { - std::string first; - int ret; - - for (const auto &[key, value] : params.asDict()) { - AgcMeteringMode meteringMode; - ret = meteringMode.read(value); - if (ret) - return { ret, {} }; - - metering_modes[key] = std::move(meteringMode); - if (first.empty()) - first = key; - } - - return { 0, first }; + return NAME; } -int AgcExposureMode::read(const libcamera::YamlObject ¶ms) +int Agc::read(const libcamera::YamlObject ¶ms) { - auto value = params["shutter"].getList(); - if (!value) - return -EINVAL; - std::transform(value->begin(), value->end(), std::back_inserter(shutter), - [](double v) { return v * 1us; }); - - value = params["gain"].getList(); - if (!value) - return -EINVAL; - gain = std::move(*value); - - if (shutter.size() < 2 || gain.size() < 2) { - LOG(RPiAgc, Error) - << "AgcExposureMode: must have at least two entries in exposure profile"; - return -EINVAL; - } - - if (shutter.size() != gain.size()) { - LOG(RPiAgc, Error) - << "AgcExposureMode: expect same number of exposure and gain entries in exposure profile"; - return -EINVAL; + /* + * When there is only a single channel we can read the old style syntax. + * Otherwise we expect a "channels" keyword followed by a list of configurations. + */ + if (!params.contains("channels")) { + LOG(RPiAgc, Debug) << "Single channel only"; + channelData_.emplace_back(); + return channelData_.back().channel.read(params, getHardwareConfig()); } - return 0; -} - -static std::tuple -readExposureModes(std::map &exposureModes, - const libcamera::YamlObject ¶ms) -{ - std::string first; - int ret; - - for (const auto &[key, value] : params.asDict()) { - AgcExposureMode exposureMode; - ret = exposureMode.read(value); + const auto &channels = params["channels"].asList(); + for (auto ch = channels.begin(); ch != channels.end(); ch++) { + LOG(RPiAgc, Debug) << "Read AGC channel"; + channelData_.emplace_back(); + int ret = channelData_.back().channel.read(*ch, getHardwareConfig()); if (ret) - return { ret, {} }; - - exposureModes[key] = std::move(exposureMode); - if (first.empty()) - first = key; + return ret; } - return { 0, first }; -} - -int AgcConstraint::read(const libcamera::YamlObject ¶ms) -{ - std::string boundString = params["bound"].get(""); - transform(boundString.begin(), boundString.end(), - boundString.begin(), ::toupper); - if (boundString != "UPPER" && boundString != "LOWER") { - LOG(RPiAgc, Error) << "AGC constraint type should be UPPER or LOWER"; - return -EINVAL; + LOG(RPiAgc, Debug) << "Read " << channelData_.size() << " channel(s)"; + if (channelData_.empty()) { + LOG(RPiAgc, Error) << "No AGC channels provided"; + return -1; } - bound = boundString == "UPPER" ? Bound::UPPER : Bound::LOWER; - - auto value = params["q_lo"].get(); - if (!value) - return -EINVAL; - qLo = *value; - - value = params["q_hi"].get(); - if (!value) - return -EINVAL; - qHi = *value; - - return yTarget.read(params["y_target"]); -} -static std::tuple -readConstraintMode(const libcamera::YamlObject ¶ms) -{ - AgcConstraintMode mode; - int ret; - - for (const auto &p : params.asList()) { - AgcConstraint constraint; - ret = constraint.read(p); - if (ret) - return { ret, {} }; - - mode.push_back(std::move(constraint)); - } - - return { 0, mode }; + return 0; } -static std::tuple -readConstraintModes(std::map &constraintModes, - const libcamera::YamlObject ¶ms) +int Agc::checkChannel(unsigned int channelIndex) const { - std::string first; - int ret; - - for (const auto &[key, value] : params.asDict()) { - std::tie(ret, constraintModes[key]) = readConstraintMode(value); - if (ret) - return { ret, {} }; - - if (first.empty()) - first = key; + if (channelIndex >= channelData_.size()) { + LOG(RPiAgc, Warning) << "AGC channel " << channelIndex << " not available"; + return -1; } - return { 0, first }; -} - -int AgcConfig::read(const libcamera::YamlObject ¶ms) -{ - LOG(RPiAgc, Debug) << "AgcConfig"; - int ret; - - std::tie(ret, defaultMeteringMode) = - readMeteringModes(meteringModes, params["metering_modes"]); - if (ret) - return ret; - std::tie(ret, defaultExposureMode) = - readExposureModes(exposureModes, params["exposure_modes"]); - if (ret) - return ret; - std::tie(ret, defaultConstraintMode) = - readConstraintModes(constraintModes, params["constraint_modes"]); - if (ret) - return ret; - - ret = yTarget.read(params["y_target"]); - if (ret) - return ret; - - speed = params["speed"].get(0.2); - startupFrames = params["startup_frames"].get(10); - convergenceFrames = params["convergence_frames"].get(6); - fastReduceThreshold = params["fast_reduce_threshold"].get(0.4); - baseEv = params["base_ev"].get(1.0); - - /* Start with quite a low value as ramping up is easier than ramping down. */ - defaultExposureTime = params["default_exposure_time"].get(1000) * 1us; - defaultAnalogueGain = params["default_analogue_gain"].get(1.0); - return 0; } -Agc::ExposureValues::ExposureValues() - : shutter(0s), analogueGain(0), - totalExposure(0s), totalExposureNoDG(0s) +void Agc::disableAuto(unsigned int channelIndex) { -} - -Agc::Agc(Controller *controller) - : AgcAlgorithm(controller), meteringMode_(nullptr), - exposureMode_(nullptr), constraintMode_(nullptr), - frameCount_(0), lockCount_(0), - lastTargetExposure_(0s), ev_(1.0), flickerPeriod_(0s), - maxShutter_(0s), fixedShutter_(0s), fixedAnalogueGain_(0.0) -{ - memset(&awb_, 0, sizeof(awb_)); - /* - * Setting status_.totalExposureValue_ to zero initially tells us - * it's not been calculated yet (i.e. Process hasn't yet run). - */ - status_ = {}; - status_.ev = ev_; -} + if (checkChannel(channelIndex)) + return; -char const *Agc::name() const -{ - return NAME; + LOG(RPiAgc, Debug) << "disableAuto for channel " << channelIndex; + channelData_[channelIndex].channel.disableAuto(); } -int Agc::read(const libcamera::YamlObject ¶ms) +void Agc::enableAuto(unsigned int channelIndex) { - LOG(RPiAgc, Debug) << "Agc"; - - int ret = config_.read(params); - if (ret) - return ret; - - const Size &size = getHardwareConfig().agcZoneWeights; - for (auto const &modes : config_.meteringModes) { - if (modes.second.weights.size() != size.width * size.height) { - LOG(RPiAgc, Error) << "AgcMeteringMode: Incorrect number of weights"; - return -EINVAL; - } - } + if (checkChannel(channelIndex)) + return; - /* - * Set the config's defaults (which are the first ones it read) as our - * current modes, until someone changes them. (they're all known to - * exist at this point) - */ - meteringModeName_ = config_.defaultMeteringMode; - meteringMode_ = &config_.meteringModes[meteringModeName_]; - exposureModeName_ = config_.defaultExposureMode; - exposureMode_ = &config_.exposureModes[exposureModeName_]; - constraintModeName_ = config_.defaultConstraintMode; - constraintMode_ = &config_.constraintModes[constraintModeName_]; - /* Set up the "last shutter/gain" values, in case AGC starts "disabled". */ - status_.shutterTime = config_.defaultExposureTime; - status_.analogueGain = config_.defaultAnalogueGain; - return 0; -} - -void Agc::disableAuto() -{ - fixedShutter_ = status_.shutterTime; - fixedAnalogueGain_ = status_.analogueGain; -} - -void Agc::enableAuto() -{ - fixedShutter_ = 0s; - fixedAnalogueGain_ = 0; + LOG(RPiAgc, Debug) << "enableAuto for channel " << channelIndex; + channelData_[channelIndex].channel.enableAuto(); } unsigned int Agc::getConvergenceFrames() const { - /* - * If shutter and gain have been explicitly set, there is no - * convergence to happen, so no need to drop any frames - return zero. - */ - if (fixedShutter_ && fixedAnalogueGain_) - return 0; - else - return config_.convergenceFrames; + /* If there are n channels, it presumably takes n times as long to converge. */ + return channelData_[0].channel.getConvergenceFrames() * activeChannels_.size(); } std::vector const &Agc::getWeights() const { /* - * In case someone calls setMeteringMode and then this before the - * algorithm has run and updated the meteringMode_ pointer. + * In future the metering weights may be determined differently, making it + * difficult to associate different sets of weight with different channels. + * Therefore we shall impose a limitation, at least for now, that all + * channels will use the same weights. */ - auto it = config_.meteringModes.find(meteringModeName_); - if (it == config_.meteringModes.end()) - return meteringMode_->weights; - return it->second.weights; + return channelData_[0].channel.getWeights(); } -void Agc::setEv(double ev) +void Agc::setEv(unsigned int channelIndex, double ev) { - ev_ = ev; -} + if (checkChannel(channelIndex)) + return; -void Agc::setFlickerPeriod(Duration flickerPeriod) -{ - flickerPeriod_ = flickerPeriod; + LOG(RPiAgc, Debug) << "setEv " << ev << " for channel " << channelIndex; + channelData_[channelIndex].channel.setEv(ev); } -void Agc::setMaxShutter(Duration maxShutter) +void Agc::setFlickerPeriod(unsigned int channelIndex, Duration flickerPeriod) { - maxShutter_ = maxShutter; -} + if (checkChannel(channelIndex)) + return; -void Agc::setFixedShutter(Duration fixedShutter) -{ - fixedShutter_ = fixedShutter; - /* Set this in case someone calls disableAuto() straight after. */ - status_.shutterTime = limitShutter(fixedShutter_); + LOG(RPiAgc, Debug) << "setFlickerPeriod " << flickerPeriod + << " for channel " << channelIndex; + channelData_[channelIndex].channel.setFlickerPeriod(flickerPeriod); } -void Agc::setFixedAnalogueGain(double fixedAnalogueGain) -{ - fixedAnalogueGain_ = fixedAnalogueGain; - /* Set this in case someone calls disableAuto() straight after. */ - status_.analogueGain = limitGain(fixedAnalogueGain); -} - -void Agc::setMeteringMode(std::string const &meteringModeName) -{ - meteringModeName_ = meteringModeName; -} - -void Agc::setExposureMode(std::string const &exposureModeName) -{ - exposureModeName_ = exposureModeName; -} - -void Agc::setConstraintMode(std::string const &constraintModeName) -{ - constraintModeName_ = constraintModeName; -} - -void Agc::switchMode(CameraMode const &cameraMode, - Metadata *metadata) +void Agc::setMaxShutter(Duration maxShutter) { - /* AGC expects the mode sensitivity always to be non-zero. */ - ASSERT(cameraMode.sensitivity); - - housekeepConfig(); - - /* - * Store the mode in the local state. We must cache the sensitivity of - * of the previous mode for the calculations below. - */ - double lastSensitivity = mode_.sensitivity; - mode_ = cameraMode; - - Duration fixedShutter = limitShutter(fixedShutter_); - if (fixedShutter && fixedAnalogueGain_) { - /* We're going to reset the algorithm here with these fixed values. */ - - fetchAwbStatus(metadata); - double minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 }); - ASSERT(minColourGain != 0.0); - - /* This is the equivalent of computeTargetExposure and applyDigitalGain. */ - target_.totalExposureNoDG = fixedShutter_ * fixedAnalogueGain_; - target_.totalExposure = target_.totalExposureNoDG / minColourGain; - - /* Equivalent of filterExposure. This resets any "history". */ - filtered_ = target_; - - /* Equivalent of divideUpExposure. */ - filtered_.shutter = fixedShutter; - filtered_.analogueGain = fixedAnalogueGain_; - } else if (status_.totalExposureValue) { - /* - * On a mode switch, various things could happen: - * - the exposure profile might change - * - a fixed exposure or gain might be set - * - the new mode's sensitivity might be different - * We cope with the last of these by scaling the target values. After - * that we just need to re-divide the exposure/gain according to the - * current exposure profile, which takes care of everything else. - */ - - double ratio = lastSensitivity / cameraMode.sensitivity; - target_.totalExposureNoDG *= ratio; - target_.totalExposure *= ratio; - filtered_.totalExposureNoDG *= ratio; - filtered_.totalExposure *= ratio; - - divideUpExposure(); - } else { - /* - * We come through here on startup, when at least one of the shutter - * or gain has not been fixed. We must still write those values out so - * that they will be applied immediately. We supply some arbitrary defaults - * for any that weren't set. - */ - - /* Equivalent of divideUpExposure. */ - filtered_.shutter = fixedShutter ? fixedShutter : config_.defaultExposureTime; - filtered_.analogueGain = fixedAnalogueGain_ ? fixedAnalogueGain_ : config_.defaultAnalogueGain; - } - - writeAndFinish(metadata, false); + /* Frame durations will be the same across all channels too. */ + for (auto &data : channelData_) + data.channel.setMaxShutter(maxShutter); } -void Agc::prepare(Metadata *imageMetadata) +void Agc::setFixedShutter(unsigned int channelIndex, Duration fixedShutter) { - Duration totalExposureValue = status_.totalExposureValue; - AgcStatus delayedStatus; - AgcPrepareStatus prepareStatus; - - if (!imageMetadata->get("agc.delayed_status", delayedStatus)) - totalExposureValue = delayedStatus.totalExposureValue; - - prepareStatus.digitalGain = 1.0; - prepareStatus.locked = false; - - if (status_.totalExposureValue) { - /* Process has run, so we have meaningful values. */ - DeviceStatus deviceStatus; - if (imageMetadata->get("device.status", deviceStatus) == 0) { - Duration actualExposure = deviceStatus.shutterSpeed * - deviceStatus.analogueGain; - if (actualExposure) { - double digitalGain = totalExposureValue / actualExposure; - LOG(RPiAgc, Debug) << "Want total exposure " << totalExposureValue; - /* - * Never ask for a gain < 1.0, and also impose - * some upper limit. Make it customisable? - */ - prepareStatus.digitalGain = std::max(1.0, std::min(digitalGain, 4.0)); - LOG(RPiAgc, Debug) << "Actual exposure " << actualExposure; - LOG(RPiAgc, Debug) << "Use digitalGain " << prepareStatus.digitalGain; - LOG(RPiAgc, Debug) << "Effective exposure " - << actualExposure * prepareStatus.digitalGain; - /* Decide whether AEC/AGC has converged. */ - prepareStatus.locked = updateLockStatus(deviceStatus); - } - } else - LOG(RPiAgc, Warning) << name() << ": no device metadata"; - imageMetadata->set("agc.prepare_status", prepareStatus); - } -} + if (checkChannel(channelIndex)) + return; -void Agc::process(StatisticsPtr &stats, Metadata *imageMetadata) -{ - frameCount_++; - /* - * First a little bit of housekeeping, fetching up-to-date settings and - * configuration, that kind of thing. - */ - housekeepConfig(); - /* Fetch the AWB status immediately, so that we can assume it's there. */ - fetchAwbStatus(imageMetadata); - /* Get the current exposure values for the frame that's just arrived. */ - fetchCurrentExposure(imageMetadata); - /* Compute the total gain we require relative to the current exposure. */ - double gain, targetY; - computeGain(stats, imageMetadata, gain, targetY); - /* Now compute the target (final) exposure which we think we want. */ - computeTargetExposure(gain); - /* The results have to be filtered so as not to change too rapidly. */ - filterExposure(); - /* - * Some of the exposure has to be applied as digital gain, so work out - * what that is. This function also tells us whether it's decided to - * "desaturate" the image more quickly. - */ - bool desaturate = applyDigitalGain(gain, targetY); - /* - * The last thing is to divide up the exposure value into a shutter time - * and analogue gain, according to the current exposure mode. - */ - divideUpExposure(); - /* Finally advertise what we've done. */ - writeAndFinish(imageMetadata, desaturate); + LOG(RPiAgc, Debug) << "setFixedShutter " << fixedShutter + << " for channel " << channelIndex; + channelData_[channelIndex].channel.setFixedShutter(fixedShutter); } -bool Agc::updateLockStatus(DeviceStatus const &deviceStatus) +void Agc::setFixedAnalogueGain(unsigned int channelIndex, double fixedAnalogueGain) { - const double errorFactor = 0.10; /* make these customisable? */ - const int maxLockCount = 5; - /* Reset "lock count" when we exceed this multiple of errorFactor */ - const double resetMargin = 1.5; + if (checkChannel(channelIndex)) + return; - /* Add 200us to the exposure time error to allow for line quantisation. */ - Duration exposureError = lastDeviceStatus_.shutterSpeed * errorFactor + 200us; - double gainError = lastDeviceStatus_.analogueGain * errorFactor; - Duration targetError = lastTargetExposure_ * errorFactor; - - /* - * Note that we don't know the exposure/gain limits of the sensor, so - * the values we keep requesting may be unachievable. For this reason - * we only insist that we're close to values in the past few frames. - */ - if (deviceStatus.shutterSpeed > lastDeviceStatus_.shutterSpeed - exposureError && - deviceStatus.shutterSpeed < lastDeviceStatus_.shutterSpeed + exposureError && - deviceStatus.analogueGain > lastDeviceStatus_.analogueGain - gainError && - deviceStatus.analogueGain < lastDeviceStatus_.analogueGain + gainError && - status_.targetExposureValue > lastTargetExposure_ - targetError && - status_.targetExposureValue < lastTargetExposure_ + targetError) - lockCount_ = std::min(lockCount_ + 1, maxLockCount); - else if (deviceStatus.shutterSpeed < lastDeviceStatus_.shutterSpeed - resetMargin * exposureError || - deviceStatus.shutterSpeed > lastDeviceStatus_.shutterSpeed + resetMargin * exposureError || - deviceStatus.analogueGain < lastDeviceStatus_.analogueGain - resetMargin * gainError || - deviceStatus.analogueGain > lastDeviceStatus_.analogueGain + resetMargin * gainError || - status_.targetExposureValue < lastTargetExposure_ - resetMargin * targetError || - status_.targetExposureValue > lastTargetExposure_ + resetMargin * targetError) - lockCount_ = 0; - - lastDeviceStatus_ = deviceStatus; - lastTargetExposure_ = status_.targetExposureValue; - - LOG(RPiAgc, Debug) << "Lock count updated to " << lockCount_; - return lockCount_ == maxLockCount; + LOG(RPiAgc, Debug) << "setFixedAnalogueGain " << fixedAnalogueGain + << " for channel " << channelIndex; + channelData_[channelIndex].channel.setFixedAnalogueGain(fixedAnalogueGain); } -void Agc::housekeepConfig() +void Agc::setMeteringMode(std::string const &meteringModeName) { - /* First fetch all the up-to-date settings, so no one else has to do it. */ - status_.ev = ev_; - status_.fixedShutter = limitShutter(fixedShutter_); - status_.fixedAnalogueGain = fixedAnalogueGain_; - status_.flickerPeriod = flickerPeriod_; - LOG(RPiAgc, Debug) << "ev " << status_.ev << " fixedShutter " - << status_.fixedShutter << " fixedAnalogueGain " - << status_.fixedAnalogueGain; - /* - * Make sure the "mode" pointers point to the up-to-date things, if - * they've changed. - */ - if (meteringModeName_ != status_.meteringMode) { - auto it = config_.meteringModes.find(meteringModeName_); - if (it == config_.meteringModes.end()) { - LOG(RPiAgc, Warning) << "No metering mode " << meteringModeName_; - meteringModeName_ = status_.meteringMode; - } else { - meteringMode_ = &it->second; - status_.meteringMode = meteringModeName_; - } - } - if (exposureModeName_ != status_.exposureMode) { - auto it = config_.exposureModes.find(exposureModeName_); - if (it == config_.exposureModes.end()) { - LOG(RPiAgc, Warning) << "No exposure profile " << exposureModeName_; - exposureModeName_ = status_.exposureMode; - } else { - exposureMode_ = &it->second; - status_.exposureMode = exposureModeName_; - } - } - if (constraintModeName_ != status_.constraintMode) { - auto it = config_.constraintModes.find(constraintModeName_); - if (it == config_.constraintModes.end()) { - LOG(RPiAgc, Warning) << "No constraint list " << constraintModeName_; - constraintModeName_ = status_.constraintMode; - } else { - constraintMode_ = &it->second; - status_.constraintMode = constraintModeName_; - } - } - LOG(RPiAgc, Debug) << "exposureMode " - << exposureModeName_ << " constraintMode " - << constraintModeName_ << " meteringMode " - << meteringModeName_; + /* Metering modes will be the same across all channels too. */ + for (auto &data : channelData_) + data.channel.setMeteringMode(meteringModeName); } -void Agc::fetchCurrentExposure(Metadata *imageMetadata) +void Agc::setExposureMode(unsigned int channelIndex, std::string const &exposureModeName) { - std::unique_lock lock(*imageMetadata); - DeviceStatus *deviceStatus = - imageMetadata->getLocked("device.status"); - if (!deviceStatus) - LOG(RPiAgc, Fatal) << "No device metadata"; - current_.shutter = deviceStatus->shutterSpeed; - current_.analogueGain = deviceStatus->analogueGain; - AgcStatus *agcStatus = - imageMetadata->getLocked("agc.status"); - current_.totalExposure = agcStatus ? agcStatus->totalExposureValue : 0s; - current_.totalExposureNoDG = current_.shutter * current_.analogueGain; -} + if (checkChannel(channelIndex)) + return; -void Agc::fetchAwbStatus(Metadata *imageMetadata) -{ - awb_.gainR = 1.0; /* in case not found in metadata */ - awb_.gainG = 1.0; - awb_.gainB = 1.0; - if (imageMetadata->get("awb.status", awb_) != 0) - LOG(RPiAgc, Debug) << "No AWB status found"; + LOG(RPiAgc, Debug) << "setExposureMode " << exposureModeName + << " for channel " << channelIndex; + channelData_[channelIndex].channel.setExposureMode(exposureModeName); } -static double computeInitialY(StatisticsPtr &stats, AwbStatus const &awb, - std::vector &weights, double gain) +void Agc::setConstraintMode(unsigned int channelIndex, std::string const &constraintModeName) { - constexpr uint64_t maxVal = 1 << Statistics::NormalisationFactorPow2; + if (checkChannel(channelIndex)) + return; - ASSERT(weights.size() == stats->agcRegions.numRegions()); - - /* - * Note that the weights are applied by the IPA to the statistics directly, - * before they are given to us here. - */ - double rSum = 0, gSum = 0, bSum = 0, pixelSum = 0; - for (unsigned int i = 0; i < stats->agcRegions.numRegions(); i++) { - auto ®ion = stats->agcRegions.get(i); - rSum += std::min(region.val.rSum * gain, (maxVal - 1) * region.counted); - gSum += std::min(region.val.gSum * gain, (maxVal - 1) * region.counted); - bSum += std::min(region.val.bSum * gain, (maxVal - 1) * region.counted); - pixelSum += region.counted; - } - if (pixelSum == 0.0) { - LOG(RPiAgc, Warning) << "computeInitialY: pixelSum is zero"; - return 0; - } - double ySum = rSum * awb.gainR * .299 + - gSum * awb.gainG * .587 + - bSum * awb.gainB * .114; - return ySum / pixelSum / maxVal; + channelData_[channelIndex].channel.setConstraintMode(constraintModeName); } -/* - * We handle extra gain through EV by adjusting our Y targets. However, you - * simply can't monitor histograms once they get very close to (or beyond!) - * saturation, so we clamp the Y targets to this value. It does mean that EV - * increases don't necessarily do quite what you might expect in certain - * (contrived) cases. - */ - -static constexpr double EvGainYTargetLimit = 0.9; - -static double constraintComputeGain(AgcConstraint &c, const Histogram &h, double lux, - double evGain, double &targetY) +template +std::ostream &operator<<(std::ostream &os, const std::vector &v) { - targetY = c.yTarget.eval(c.yTarget.domain().clip(lux)); - targetY = std::min(EvGainYTargetLimit, targetY * evGain); - double iqm = h.interQuantileMean(c.qLo, c.qHi); - return (targetY * h.bins()) / iqm; + os << "{"; + for (const auto &e : v) + os << " " << e; + os << " }"; + return os; } -void Agc::computeGain(StatisticsPtr &statistics, Metadata *imageMetadata, - double &gain, double &targetY) +void Agc::setActiveChannels(const std::vector &activeChannels) { - struct LuxStatus lux = {}; - lux.lux = 400; /* default lux level to 400 in case no metadata found */ - if (imageMetadata->get("lux.status", lux) != 0) - LOG(RPiAgc, Warning) << "No lux level found"; - const Histogram &h = statistics->yHist; - double evGain = status_.ev * config_.baseEv; - /* - * The initial gain and target_Y come from some of the regions. After - * that we consider the histogram constraints. - */ - targetY = config_.yTarget.eval(config_.yTarget.domain().clip(lux.lux)); - targetY = std::min(EvGainYTargetLimit, targetY * evGain); - - /* - * Do this calculation a few times as brightness increase can be - * non-linear when there are saturated regions. - */ - gain = 1.0; - for (int i = 0; i < 8; i++) { - double initialY = computeInitialY(statistics, awb_, meteringMode_->weights, gain); - double extraGain = std::min(10.0, targetY / (initialY + .001)); - gain *= extraGain; - LOG(RPiAgc, Debug) << "Initial Y " << initialY << " target " << targetY - << " gives gain " << gain; - if (extraGain < 1.01) /* close enough */ - break; - } - - for (auto &c : *constraintMode_) { - double newTargetY; - double newGain = constraintComputeGain(c, h, lux.lux, evGain, newTargetY); - LOG(RPiAgc, Debug) << "Constraint has target_Y " - << newTargetY << " giving gain " << newGain; - if (c.bound == AgcConstraint::Bound::LOWER && newGain > gain) { - LOG(RPiAgc, Debug) << "Lower bound constraint adopted"; - gain = newGain; - targetY = newTargetY; - } else if (c.bound == AgcConstraint::Bound::UPPER && newGain < gain) { - LOG(RPiAgc, Debug) << "Upper bound constraint adopted"; - gain = newGain; - targetY = newTargetY; - } + if (activeChannels.empty()) { + LOG(RPiAgc, Warning) << "No active AGC channels supplied"; + return; } - LOG(RPiAgc, Debug) << "Final gain " << gain << " (target_Y " << targetY << " ev " - << status_.ev << " base_ev " << config_.baseEv - << ")"; -} - -void Agc::computeTargetExposure(double gain) -{ - if (status_.fixedShutter && status_.fixedAnalogueGain) { - /* - * When ag and shutter are both fixed, we need to drive the - * total exposure so that we end up with a digital gain of at least - * 1/minColourGain. Otherwise we'd desaturate channels causing - * white to go cyan or magenta. - */ - double minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 }); - ASSERT(minColourGain != 0.0); - target_.totalExposure = - status_.fixedShutter * status_.fixedAnalogueGain / minColourGain; - } else { - /* - * The statistics reflect the image without digital gain, so the final - * total exposure we're aiming for is: - */ - target_.totalExposure = current_.totalExposureNoDG * gain; - /* The final target exposure is also limited to what the exposure mode allows. */ - Duration maxShutter = status_.fixedShutter - ? status_.fixedShutter - : exposureMode_->shutter.back(); - maxShutter = limitShutter(maxShutter); - Duration maxTotalExposure = - maxShutter * - (status_.fixedAnalogueGain != 0.0 - ? status_.fixedAnalogueGain - : exposureMode_->gain.back()); - target_.totalExposure = std::min(target_.totalExposure, maxTotalExposure); - } - LOG(RPiAgc, Debug) << "Target totalExposure " << target_.totalExposure; -} -bool Agc::applyDigitalGain(double gain, double targetY) -{ - double minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 }); - ASSERT(minColourGain != 0.0); - double dg = 1.0 / minColourGain; - /* - * I think this pipeline subtracts black level and rescales before we - * get the stats, so no need to worry about it. - */ - LOG(RPiAgc, Debug) << "after AWB, target dg " << dg << " gain " << gain - << " target_Y " << targetY; - /* - * Finally, if we're trying to reduce exposure but the target_Y is - * "close" to 1.0, then the gain computed for that constraint will be - * only slightly less than one, because the measured Y can never be - * larger than 1.0. When this happens, demand a large digital gain so - * that the exposure can be reduced, de-saturating the image much more - * quickly (and we then approach the correct value more quickly from - * below). - */ - bool desaturate = targetY > config_.fastReduceThreshold && - gain < sqrt(targetY); - if (desaturate) - dg /= config_.fastReduceThreshold; - LOG(RPiAgc, Debug) << "Digital gain " << dg << " desaturate? " << desaturate; - filtered_.totalExposureNoDG = filtered_.totalExposure / dg; - LOG(RPiAgc, Debug) << "Target totalExposureNoDG " << filtered_.totalExposureNoDG; - return desaturate; -} - -void Agc::filterExposure() -{ - double speed = config_.speed; - /* - * AGC adapts instantly if both shutter and gain are directly specified - * or we're in the startup phase. - */ - if ((status_.fixedShutter && status_.fixedAnalogueGain) || - frameCount_ <= config_.startupFrames) - speed = 1.0; - if (!filtered_.totalExposure) { - filtered_.totalExposure = target_.totalExposure; - } else { - /* - * If close to the result go faster, to save making so many - * micro-adjustments on the way. (Make this customisable?) - */ - if (filtered_.totalExposure < 1.2 * target_.totalExposure && - filtered_.totalExposure > 0.8 * target_.totalExposure) - speed = sqrt(speed); - filtered_.totalExposure = speed * target_.totalExposure + - filtered_.totalExposure * (1.0 - speed); - } - LOG(RPiAgc, Debug) << "After filtering, totalExposure " << filtered_.totalExposure - << " no dg " << filtered_.totalExposureNoDG; -} + for (auto index : activeChannels) + if (checkChannel(index)) + return; -void Agc::divideUpExposure() -{ - /* - * Sending the fixed shutter/gain cases through the same code may seem - * unnecessary, but it will make more sense when extend this to cover - * variable aperture. - */ - Duration exposureValue = filtered_.totalExposureNoDG; - Duration shutterTime; - double analogueGain; - shutterTime = status_.fixedShutter ? status_.fixedShutter - : exposureMode_->shutter[0]; - shutterTime = limitShutter(shutterTime); - analogueGain = status_.fixedAnalogueGain != 0.0 ? status_.fixedAnalogueGain - : exposureMode_->gain[0]; - analogueGain = limitGain(analogueGain); - if (shutterTime * analogueGain < exposureValue) { - for (unsigned int stage = 1; - stage < exposureMode_->gain.size(); stage++) { - if (!status_.fixedShutter) { - Duration stageShutter = - limitShutter(exposureMode_->shutter[stage]); - if (stageShutter * analogueGain >= exposureValue) { - shutterTime = exposureValue / analogueGain; - break; - } - shutterTime = stageShutter; - } - if (status_.fixedAnalogueGain == 0.0) { - if (exposureMode_->gain[stage] * shutterTime >= exposureValue) { - analogueGain = exposureValue / shutterTime; - break; - } - analogueGain = exposureMode_->gain[stage]; - analogueGain = limitGain(analogueGain); - } - } - } - LOG(RPiAgc, Debug) << "Divided up shutter and gain are " << shutterTime << " and " - << analogueGain; - /* - * Finally adjust shutter time for flicker avoidance (require both - * shutter and gain not to be fixed). - */ - if (!status_.fixedShutter && !status_.fixedAnalogueGain && - status_.flickerPeriod) { - int flickerPeriods = shutterTime / status_.flickerPeriod; - if (flickerPeriods) { - Duration newShutterTime = flickerPeriods * status_.flickerPeriod; - analogueGain *= shutterTime / newShutterTime; - /* - * We should still not allow the ag to go over the - * largest value in the exposure mode. Note that this - * may force more of the total exposure into the digital - * gain as a side-effect. - */ - analogueGain = std::min(analogueGain, exposureMode_->gain.back()); - analogueGain = limitGain(analogueGain); - shutterTime = newShutterTime; - } - LOG(RPiAgc, Debug) << "After flicker avoidance, shutter " - << shutterTime << " gain " << analogueGain; - } - filtered_.shutter = shutterTime; - filtered_.analogueGain = analogueGain; + LOG(RPiAgc, Debug) << "setActiveChannels " << activeChannels; + activeChannels_ = activeChannels; } -void Agc::writeAndFinish(Metadata *imageMetadata, bool desaturate) +void Agc::switchMode(CameraMode const &cameraMode, + Metadata *metadata) { - status_.totalExposureValue = filtered_.totalExposure; - status_.targetExposureValue = desaturate ? 0s : target_.totalExposureNoDG; - status_.shutterTime = filtered_.shutter; - status_.analogueGain = filtered_.analogueGain; - /* - * Write to metadata as well, in case anyone wants to update the camera - * immediately. - */ - imageMetadata->set("agc.status", status_); - LOG(RPiAgc, Debug) << "Output written, total exposure requested is " - << filtered_.totalExposure; - LOG(RPiAgc, Debug) << "Camera exposure update: shutter time " << filtered_.shutter - << " analogue gain " << filtered_.analogueGain; + LOG(RPiAgc, Debug) << "switchMode for channel 0"; + channelData_[0].channel.switchMode(cameraMode, metadata); } -Duration Agc::limitShutter(Duration shutter) +void Agc::prepare(Metadata *imageMetadata) { - /* - * shutter == 0 is a special case for fixed shutter values, and must pass - * through unchanged - */ - if (!shutter) - return shutter; - - shutter = std::clamp(shutter, mode_.minShutter, maxShutter_); - return shutter; + LOG(RPiAgc, Debug) << "prepare for channel 0"; + channelData_[0].channel.prepare(imageMetadata); } -double Agc::limitGain(double gain) const +void Agc::process(StatisticsPtr &stats, Metadata *imageMetadata) { - /* - * Only limit the lower bounds of the gain value to what the sensor limits. - * The upper bound on analogue gain will be made up with additional digital - * gain applied by the ISP. - * - * gain == 0.0 is a special case for fixed shutter values, and must pass - * through unchanged - */ - if (!gain) - return gain; - - gain = std::max(gain, mode_.minAnalogueGain); - return gain; + LOG(RPiAgc, Debug) << "process for channel 0"; + channelData_[0].channel.process(stats, imageMetadata); } /* Register algorithm with the system. */ diff --git a/src/ipa/rpi/controller/rpi/agc.h b/src/ipa/rpi/controller/rpi/agc.h index aaf77c8f..a476ea70 100644 --- a/src/ipa/rpi/controller/rpi/agc.h +++ b/src/ipa/rpi/controller/rpi/agc.h @@ -6,60 +6,17 @@ */ #pragma once +#include #include -#include - -#include #include "../agc_algorithm.h" -#include "../agc_status.h" -#include "../pwl.h" -/* This is our implementation of AGC. */ +#include "agc_channel.h" namespace RPiController { -struct AgcMeteringMode { - std::vector weights; - int read(const libcamera::YamlObject ¶ms); -}; - -struct AgcExposureMode { - std::vector shutter; - std::vector gain; - int read(const libcamera::YamlObject ¶ms); -}; - -struct AgcConstraint { - enum class Bound { LOWER = 0, UPPER = 1 }; - Bound bound; - double qLo; - double qHi; - Pwl yTarget; - int read(const libcamera::YamlObject ¶ms); -}; - -typedef std::vector AgcConstraintMode; - -struct AgcConfig { - int read(const libcamera::YamlObject ¶ms); - std::map meteringModes; - std::map exposureModes; - std::map constraintModes; - Pwl yTarget; - double speed; - uint16_t startupFrames; - unsigned int convergenceFrames; - double maxChange; - double minChange; - double fastReduceThreshold; - double speedUpThreshold; - std::string defaultMeteringMode; - std::string defaultExposureMode; - std::string defaultConstraintMode; - double baseEv; - libcamera::utils::Duration defaultExposureTime; - double defaultAnalogueGain; +struct AgcChannelData { + AgcChannel channel; }; class Agc : public AgcAlgorithm @@ -70,65 +27,30 @@ public: int read(const libcamera::YamlObject ¶ms) override; unsigned int getConvergenceFrames() const override; std::vector const &getWeights() const override; - void setEv(double ev) override; - void setFlickerPeriod(libcamera::utils::Duration flickerPeriod) override; + void setEv(unsigned int channel, double ev) override; + void setFlickerPeriod(unsigned int channelIndex, + libcamera::utils::Duration flickerPeriod) override; void setMaxShutter(libcamera::utils::Duration maxShutter) override; - void setFixedShutter(libcamera::utils::Duration fixedShutter) override; - void setFixedAnalogueGain(double fixedAnalogueGain) override; + void setFixedShutter(unsigned int channelIndex, + libcamera::utils::Duration fixedShutter) override; + void setFixedAnalogueGain(unsigned int channelIndex, + double fixedAnalogueGain) override; void setMeteringMode(std::string const &meteringModeName) override; - void setExposureMode(std::string const &exposureModeName) override; - void setConstraintMode(std::string const &contraintModeName) override; - void enableAuto() override; - void disableAuto() override; + void setExposureMode(unsigned int channelIndex, + std::string const &exposureModeName) override; + void setConstraintMode(unsigned int channelIndex, + std::string const &contraintModeName) override; + void enableAuto(unsigned int channelIndex) override; + void disableAuto(unsigned int channelIndex) override; void switchMode(CameraMode const &cameraMode, Metadata *metadata) override; void prepare(Metadata *imageMetadata) override; void process(StatisticsPtr &stats, Metadata *imageMetadata) override; + void setActiveChannels(const std::vector &activeChannels) override; private: - bool updateLockStatus(DeviceStatus const &deviceStatus); - AgcConfig config_; - void housekeepConfig(); - void fetchCurrentExposure(Metadata *imageMetadata); - void fetchAwbStatus(Metadata *imageMetadata); - void computeGain(StatisticsPtr &statistics, Metadata *imageMetadata, - double &gain, double &targetY); - void computeTargetExposure(double gain); - void filterExposure(); - bool applyDigitalGain(double gain, double targetY); - void divideUpExposure(); - void writeAndFinish(Metadata *imageMetadata, bool desaturate); - libcamera::utils::Duration limitShutter(libcamera::utils::Duration shutter); - double limitGain(double gain) const; - AgcMeteringMode *meteringMode_; - AgcExposureMode *exposureMode_; - AgcConstraintMode *constraintMode_; - CameraMode mode_; - uint64_t frameCount_; - AwbStatus awb_; - struct ExposureValues { - ExposureValues(); - - libcamera::utils::Duration shutter; - double analogueGain; - libcamera::utils::Duration totalExposure; - libcamera::utils::Duration totalExposureNoDG; /* without digital gain */ - }; - ExposureValues current_; /* values for the current frame */ - ExposureValues target_; /* calculate the values we want here */ - ExposureValues filtered_; /* these values are filtered towards target */ - AgcStatus status_; - int lockCount_; - DeviceStatus lastDeviceStatus_; - libcamera::utils::Duration lastTargetExposure_; - /* Below here the "settings" that applications can change. */ - std::string meteringModeName_; - std::string exposureModeName_; - std::string constraintModeName_; - double ev_; - libcamera::utils::Duration flickerPeriod_; - libcamera::utils::Duration maxShutter_; - libcamera::utils::Duration fixedShutter_; - double fixedAnalogueGain_; + int checkChannel(unsigned int channel) const; + std::vector channelData_; + std::vector activeChannels_; }; } /* namespace RPiController */ diff --git a/src/ipa/rpi/controller/rpi/agc_channel.cpp b/src/ipa/rpi/controller/rpi/agc_channel.cpp new file mode 100644 index 00000000..f180b848 --- /dev/null +++ b/src/ipa/rpi/controller/rpi/agc_channel.cpp @@ -0,0 +1,924 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* + * Copyright (C) 2023, Raspberry Pi Ltd + * + * agc_channel.cpp - AGC/AEC control algorithm + */ + +#include "agc_channel.h" + +#include +#include + +#include + +#include "../awb_status.h" +#include "../device_status.h" +#include "../histogram.h" +#include "../lux_status.h" +#include "../metadata.h" + +using namespace RPiController; +using namespace libcamera; +using libcamera::utils::Duration; +using namespace std::literals::chrono_literals; + +LOG_DECLARE_CATEGORY(RPiAgc) + +int AgcMeteringMode::read(const libcamera::YamlObject ¶ms) +{ + const YamlObject &yamlWeights = params["weights"]; + + for (const auto &p : yamlWeights.asList()) { + auto value = p.get(); + if (!value) + return -EINVAL; + weights.push_back(*value); + } + + return 0; +} + +static std::tuple +readMeteringModes(std::map &metering_modes, + const libcamera::YamlObject ¶ms) +{ + std::string first; + int ret; + + for (const auto &[key, value] : params.asDict()) { + AgcMeteringMode meteringMode; + ret = meteringMode.read(value); + if (ret) + return { ret, {} }; + + metering_modes[key] = std::move(meteringMode); + if (first.empty()) + first = key; + } + + return { 0, first }; +} + +int AgcExposureMode::read(const libcamera::YamlObject ¶ms) +{ + auto value = params["shutter"].getList(); + if (!value) + return -EINVAL; + std::transform(value->begin(), value->end(), std::back_inserter(shutter), + [](double v) { return v * 1us; }); + + value = params["gain"].getList(); + if (!value) + return -EINVAL; + gain = std::move(*value); + + if (shutter.size() < 2 || gain.size() < 2) { + LOG(RPiAgc, Error) + << "AgcExposureMode: must have at least two entries in exposure profile"; + return -EINVAL; + } + + if (shutter.size() != gain.size()) { + LOG(RPiAgc, Error) + << "AgcExposureMode: expect same number of exposure and gain entries in exposure profile"; + return -EINVAL; + } + + return 0; +} + +static std::tuple +readExposureModes(std::map &exposureModes, + const libcamera::YamlObject ¶ms) +{ + std::string first; + int ret; + + for (const auto &[key, value] : params.asDict()) { + AgcExposureMode exposureMode; + ret = exposureMode.read(value); + if (ret) + return { ret, {} }; + + exposureModes[key] = std::move(exposureMode); + if (first.empty()) + first = key; + } + + return { 0, first }; +} + +int AgcConstraint::read(const libcamera::YamlObject ¶ms) +{ + std::string boundString = params["bound"].get(""); + transform(boundString.begin(), boundString.end(), + boundString.begin(), ::toupper); + if (boundString != "UPPER" && boundString != "LOWER") { + LOG(RPiAgc, Error) << "AGC constraint type should be UPPER or LOWER"; + return -EINVAL; + } + bound = boundString == "UPPER" ? Bound::UPPER : Bound::LOWER; + + auto value = params["q_lo"].get(); + if (!value) + return -EINVAL; + qLo = *value; + + value = params["q_hi"].get(); + if (!value) + return -EINVAL; + qHi = *value; + + return yTarget.read(params["y_target"]); +} + +static std::tuple +readConstraintMode(const libcamera::YamlObject ¶ms) +{ + AgcConstraintMode mode; + int ret; + + for (const auto &p : params.asList()) { + AgcConstraint constraint; + ret = constraint.read(p); + if (ret) + return { ret, {} }; + + mode.push_back(std::move(constraint)); + } + + return { 0, mode }; +} + +static std::tuple +readConstraintModes(std::map &constraintModes, + const libcamera::YamlObject ¶ms) +{ + std::string first; + int ret; + + for (const auto &[key, value] : params.asDict()) { + std::tie(ret, constraintModes[key]) = readConstraintMode(value); + if (ret) + return { ret, {} }; + + if (first.empty()) + first = key; + } + + return { 0, first }; +} + +int AgcConfig::read(const libcamera::YamlObject ¶ms) +{ + LOG(RPiAgc, Debug) << "AgcConfig"; + int ret; + + std::tie(ret, defaultMeteringMode) = + readMeteringModes(meteringModes, params["metering_modes"]); + if (ret) + return ret; + std::tie(ret, defaultExposureMode) = + readExposureModes(exposureModes, params["exposure_modes"]); + if (ret) + return ret; + std::tie(ret, defaultConstraintMode) = + readConstraintModes(constraintModes, params["constraint_modes"]); + if (ret) + return ret; + + ret = yTarget.read(params["y_target"]); + if (ret) + return ret; + + speed = params["speed"].get(0.2); + startupFrames = params["startup_frames"].get(10); + convergenceFrames = params["convergence_frames"].get(6); + fastReduceThreshold = params["fast_reduce_threshold"].get(0.4); + baseEv = params["base_ev"].get(1.0); + + /* Start with quite a low value as ramping up is easier than ramping down. */ + defaultExposureTime = params["default_exposure_time"].get(1000) * 1us; + defaultAnalogueGain = params["default_analogue_gain"].get(1.0); + + return 0; +} + +AgcChannel::ExposureValues::ExposureValues() + : shutter(0s), analogueGain(0), + totalExposure(0s), totalExposureNoDG(0s) +{ +} + +AgcChannel::AgcChannel() + : meteringMode_(nullptr), exposureMode_(nullptr), constraintMode_(nullptr), + frameCount_(0), lockCount_(0), + lastTargetExposure_(0s), ev_(1.0), flickerPeriod_(0s), + maxShutter_(0s), fixedShutter_(0s), fixedAnalogueGain_(0.0) +{ + memset(&awb_, 0, sizeof(awb_)); + /* + * Setting status_.totalExposureValue_ to zero initially tells us + * it's not been calculated yet (i.e. Process hasn't yet run). + */ + status_ = {}; + status_.ev = ev_; +} + +int AgcChannel::read(const libcamera::YamlObject ¶ms, + const Controller::HardwareConfig &hardwareConfig) +{ + int ret = config_.read(params); + if (ret) + return ret; + + const Size &size = hardwareConfig.agcZoneWeights; + for (auto const &modes : config_.meteringModes) { + if (modes.second.weights.size() != size.width * size.height) { + LOG(RPiAgc, Error) << "AgcMeteringMode: Incorrect number of weights"; + return -EINVAL; + } + } + + /* + * Set the config's defaults (which are the first ones it read) as our + * current modes, until someone changes them. (they're all known to + * exist at this point) + */ + meteringModeName_ = config_.defaultMeteringMode; + meteringMode_ = &config_.meteringModes[meteringModeName_]; + exposureModeName_ = config_.defaultExposureMode; + exposureMode_ = &config_.exposureModes[exposureModeName_]; + constraintModeName_ = config_.defaultConstraintMode; + constraintMode_ = &config_.constraintModes[constraintModeName_]; + /* Set up the "last shutter/gain" values, in case AGC starts "disabled". */ + status_.shutterTime = config_.defaultExposureTime; + status_.analogueGain = config_.defaultAnalogueGain; + return 0; +} + +void AgcChannel::disableAuto() +{ + fixedShutter_ = status_.shutterTime; + fixedAnalogueGain_ = status_.analogueGain; +} + +void AgcChannel::enableAuto() +{ + fixedShutter_ = 0s; + fixedAnalogueGain_ = 0; +} + +unsigned int AgcChannel::getConvergenceFrames() const +{ + /* + * If shutter and gain have been explicitly set, there is no + * convergence to happen, so no need to drop any frames - return zero. + */ + if (fixedShutter_ && fixedAnalogueGain_) + return 0; + else + return config_.convergenceFrames; +} + +std::vector const &AgcChannel::getWeights() const +{ + /* + * In case someone calls setMeteringMode and then this before the + * algorithm has run and updated the meteringMode_ pointer. + */ + auto it = config_.meteringModes.find(meteringModeName_); + if (it == config_.meteringModes.end()) + return meteringMode_->weights; + return it->second.weights; +} + +void AgcChannel::setEv(double ev) +{ + ev_ = ev; +} + +void AgcChannel::setFlickerPeriod(Duration flickerPeriod) +{ + flickerPeriod_ = flickerPeriod; +} + +void AgcChannel::setMaxShutter(Duration maxShutter) +{ + maxShutter_ = maxShutter; +} + +void AgcChannel::setFixedShutter(Duration fixedShutter) +{ + fixedShutter_ = fixedShutter; + /* Set this in case someone calls disableAuto() straight after. */ + status_.shutterTime = limitShutter(fixedShutter_); +} + +void AgcChannel::setFixedAnalogueGain(double fixedAnalogueGain) +{ + fixedAnalogueGain_ = fixedAnalogueGain; + /* Set this in case someone calls disableAuto() straight after. */ + status_.analogueGain = limitGain(fixedAnalogueGain); +} + +void AgcChannel::setMeteringMode(std::string const &meteringModeName) +{ + meteringModeName_ = meteringModeName; +} + +void AgcChannel::setExposureMode(std::string const &exposureModeName) +{ + exposureModeName_ = exposureModeName; +} + +void AgcChannel::setConstraintMode(std::string const &constraintModeName) +{ + constraintModeName_ = constraintModeName; +} + +void AgcChannel::switchMode(CameraMode const &cameraMode, + Metadata *metadata) +{ + /* AGC expects the mode sensitivity always to be non-zero. */ + ASSERT(cameraMode.sensitivity); + + housekeepConfig(); + + /* + * Store the mode in the local state. We must cache the sensitivity of + * of the previous mode for the calculations below. + */ + double lastSensitivity = mode_.sensitivity; + mode_ = cameraMode; + + Duration fixedShutter = limitShutter(fixedShutter_); + if (fixedShutter && fixedAnalogueGain_) { + /* We're going to reset the algorithm here with these fixed values. */ + + fetchAwbStatus(metadata); + double minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 }); + ASSERT(minColourGain != 0.0); + + /* This is the equivalent of computeTargetExposure and applyDigitalGain. */ + target_.totalExposureNoDG = fixedShutter_ * fixedAnalogueGain_; + target_.totalExposure = target_.totalExposureNoDG / minColourGain; + + /* Equivalent of filterExposure. This resets any "history". */ + filtered_ = target_; + + /* Equivalent of divideUpExposure. */ + filtered_.shutter = fixedShutter; + filtered_.analogueGain = fixedAnalogueGain_; + } else if (status_.totalExposureValue) { + /* + * On a mode switch, various things could happen: + * - the exposure profile might change + * - a fixed exposure or gain might be set + * - the new mode's sensitivity might be different + * We cope with the last of these by scaling the target values. After + * that we just need to re-divide the exposure/gain according to the + * current exposure profile, which takes care of everything else. + */ + + double ratio = lastSensitivity / cameraMode.sensitivity; + target_.totalExposureNoDG *= ratio; + target_.totalExposure *= ratio; + filtered_.totalExposureNoDG *= ratio; + filtered_.totalExposure *= ratio; + + divideUpExposure(); + } else { + /* + * We come through here on startup, when at least one of the shutter + * or gain has not been fixed. We must still write those values out so + * that they will be applied immediately. We supply some arbitrary defaults + * for any that weren't set. + */ + + /* Equivalent of divideUpExposure. */ + filtered_.shutter = fixedShutter ? fixedShutter : config_.defaultExposureTime; + filtered_.analogueGain = fixedAnalogueGain_ ? fixedAnalogueGain_ : config_.defaultAnalogueGain; + } + + writeAndFinish(metadata, false); +} + +void AgcChannel::prepare(Metadata *imageMetadata) +{ + Duration totalExposureValue = status_.totalExposureValue; + AgcStatus delayedStatus; + AgcPrepareStatus prepareStatus; + + if (!imageMetadata->get("agc.delayed_status", delayedStatus)) + totalExposureValue = delayedStatus.totalExposureValue; + + prepareStatus.digitalGain = 1.0; + prepareStatus.locked = false; + + if (status_.totalExposureValue) { + /* Process has run, so we have meaningful values. */ + DeviceStatus deviceStatus; + if (imageMetadata->get("device.status", deviceStatus) == 0) { + Duration actualExposure = deviceStatus.shutterSpeed * + deviceStatus.analogueGain; + if (actualExposure) { + double digitalGain = totalExposureValue / actualExposure; + LOG(RPiAgc, Debug) << "Want total exposure " << totalExposureValue; + /* + * Never ask for a gain < 1.0, and also impose + * some upper limit. Make it customisable? + */ + prepareStatus.digitalGain = std::max(1.0, std::min(digitalGain, 4.0)); + LOG(RPiAgc, Debug) << "Actual exposure " << actualExposure; + LOG(RPiAgc, Debug) << "Use digitalGain " << prepareStatus.digitalGain; + LOG(RPiAgc, Debug) << "Effective exposure " + << actualExposure * prepareStatus.digitalGain; + /* Decide whether AEC/AGC has converged. */ + prepareStatus.locked = updateLockStatus(deviceStatus); + } + } else + LOG(RPiAgc, Warning) << "AgcChannel: no device metadata"; + imageMetadata->set("agc.prepare_status", prepareStatus); + } +} + +void AgcChannel::process(StatisticsPtr &stats, Metadata *imageMetadata) +{ + frameCount_++; + /* + * First a little bit of housekeeping, fetching up-to-date settings and + * configuration, that kind of thing. + */ + housekeepConfig(); + /* Fetch the AWB status immediately, so that we can assume it's there. */ + fetchAwbStatus(imageMetadata); + /* Get the current exposure values for the frame that's just arrived. */ + fetchCurrentExposure(imageMetadata); + /* Compute the total gain we require relative to the current exposure. */ + double gain, targetY; + computeGain(stats, imageMetadata, gain, targetY); + /* Now compute the target (final) exposure which we think we want. */ + computeTargetExposure(gain); + /* The results have to be filtered so as not to change too rapidly. */ + filterExposure(); + /* + * Some of the exposure has to be applied as digital gain, so work out + * what that is. This function also tells us whether it's decided to + * "desaturate" the image more quickly. + */ + bool desaturate = applyDigitalGain(gain, targetY); + /* + * The last thing is to divide up the exposure value into a shutter time + * and analogue gain, according to the current exposure mode. + */ + divideUpExposure(); + /* Finally advertise what we've done. */ + writeAndFinish(imageMetadata, desaturate); +} + +bool AgcChannel::updateLockStatus(DeviceStatus const &deviceStatus) +{ + const double errorFactor = 0.10; /* make these customisable? */ + const int maxLockCount = 5; + /* Reset "lock count" when we exceed this multiple of errorFactor */ + const double resetMargin = 1.5; + + /* Add 200us to the exposure time error to allow for line quantisation. */ + Duration exposureError = lastDeviceStatus_.shutterSpeed * errorFactor + 200us; + double gainError = lastDeviceStatus_.analogueGain * errorFactor; + Duration targetError = lastTargetExposure_ * errorFactor; + + /* + * Note that we don't know the exposure/gain limits of the sensor, so + * the values we keep requesting may be unachievable. For this reason + * we only insist that we're close to values in the past few frames. + */ + if (deviceStatus.shutterSpeed > lastDeviceStatus_.shutterSpeed - exposureError && + deviceStatus.shutterSpeed < lastDeviceStatus_.shutterSpeed + exposureError && + deviceStatus.analogueGain > lastDeviceStatus_.analogueGain - gainError && + deviceStatus.analogueGain < lastDeviceStatus_.analogueGain + gainError && + status_.targetExposureValue > lastTargetExposure_ - targetError && + status_.targetExposureValue < lastTargetExposure_ + targetError) + lockCount_ = std::min(lockCount_ + 1, maxLockCount); + else if (deviceStatus.shutterSpeed < lastDeviceStatus_.shutterSpeed - resetMargin * exposureError || + deviceStatus.shutterSpeed > lastDeviceStatus_.shutterSpeed + resetMargin * exposureError || + deviceStatus.analogueGain < lastDeviceStatus_.analogueGain - resetMargin * gainError || + deviceStatus.analogueGain > lastDeviceStatus_.analogueGain + resetMargin * gainError || + status_.targetExposureValue < lastTargetExposure_ - resetMargin * targetError || + status_.targetExposureValue > lastTargetExposure_ + resetMargin * targetError) + lockCount_ = 0; + + lastDeviceStatus_ = deviceStatus; + lastTargetExposure_ = status_.targetExposureValue; + + LOG(RPiAgc, Debug) << "Lock count updated to " << lockCount_; + return lockCount_ == maxLockCount; +} + +void AgcChannel::housekeepConfig() +{ + /* First fetch all the up-to-date settings, so no one else has to do it. */ + status_.ev = ev_; + status_.fixedShutter = limitShutter(fixedShutter_); + status_.fixedAnalogueGain = fixedAnalogueGain_; + status_.flickerPeriod = flickerPeriod_; + LOG(RPiAgc, Debug) << "ev " << status_.ev << " fixedShutter " + << status_.fixedShutter << " fixedAnalogueGain " + << status_.fixedAnalogueGain; + /* + * Make sure the "mode" pointers point to the up-to-date things, if + * they've changed. + */ + if (meteringModeName_ != status_.meteringMode) { + auto it = config_.meteringModes.find(meteringModeName_); + if (it == config_.meteringModes.end()) { + LOG(RPiAgc, Warning) << "No metering mode " << meteringModeName_; + meteringModeName_ = status_.meteringMode; + } else { + meteringMode_ = &it->second; + status_.meteringMode = meteringModeName_; + } + } + if (exposureModeName_ != status_.exposureMode) { + auto it = config_.exposureModes.find(exposureModeName_); + if (it == config_.exposureModes.end()) { + LOG(RPiAgc, Warning) << "No exposure profile " << exposureModeName_; + exposureModeName_ = status_.exposureMode; + } else { + exposureMode_ = &it->second; + status_.exposureMode = exposureModeName_; + } + } + if (constraintModeName_ != status_.constraintMode) { + auto it = config_.constraintModes.find(constraintModeName_); + if (it == config_.constraintModes.end()) { + LOG(RPiAgc, Warning) << "No constraint list " << constraintModeName_; + constraintModeName_ = status_.constraintMode; + } else { + constraintMode_ = &it->second; + status_.constraintMode = constraintModeName_; + } + } + LOG(RPiAgc, Debug) << "exposureMode " + << exposureModeName_ << " constraintMode " + << constraintModeName_ << " meteringMode " + << meteringModeName_; +} + +void AgcChannel::fetchCurrentExposure(Metadata *imageMetadata) +{ + std::unique_lock lock(*imageMetadata); + DeviceStatus *deviceStatus = + imageMetadata->getLocked("device.status"); + if (!deviceStatus) + LOG(RPiAgc, Fatal) << "No device metadata"; + current_.shutter = deviceStatus->shutterSpeed; + current_.analogueGain = deviceStatus->analogueGain; + AgcStatus *agcStatus = + imageMetadata->getLocked("agc.status"); + current_.totalExposure = agcStatus ? agcStatus->totalExposureValue : 0s; + current_.totalExposureNoDG = current_.shutter * current_.analogueGain; +} + +void AgcChannel::fetchAwbStatus(Metadata *imageMetadata) +{ + awb_.gainR = 1.0; /* in case not found in metadata */ + awb_.gainG = 1.0; + awb_.gainB = 1.0; + if (imageMetadata->get("awb.status", awb_) != 0) + LOG(RPiAgc, Debug) << "No AWB status found"; +} + +static double computeInitialY(StatisticsPtr &stats, AwbStatus const &awb, + std::vector &weights, double gain) +{ + constexpr uint64_t maxVal = 1 << Statistics::NormalisationFactorPow2; + + /* + * If we have no AGC region stats, but do have a a Y histogram, use that + * directly to caluclate the mean Y value of the image. + */ + if (!stats->agcRegions.numRegions() && stats->yHist.bins()) { + /* + * When the gain is applied to the histogram, anything below minBin + * will scale up directly with the gain, but anything above that + * will saturate into the top bin. + */ + auto &hist = stats->yHist; + double minBin = std::min(1.0, 1.0 / gain) * hist.bins(); + double binMean = hist.interBinMean(0.0, minBin); + double numUnsaturated = hist.cumulativeFreq(minBin); + /* This term is from all the pixels that won't saturate. */ + double ySum = binMean * gain * numUnsaturated; + /* And add the ones that will saturate. */ + ySum += (hist.total() - numUnsaturated) * hist.bins(); + return ySum / hist.total() / hist.bins(); + } + + ASSERT(weights.size() == stats->agcRegions.numRegions()); + + /* + * Note that the weights are applied by the IPA to the statistics directly, + * before they are given to us here. + */ + double rSum = 0, gSum = 0, bSum = 0, pixelSum = 0; + for (unsigned int i = 0; i < stats->agcRegions.numRegions(); i++) { + auto ®ion = stats->agcRegions.get(i); + rSum += std::min(region.val.rSum * gain, (maxVal - 1) * region.counted); + gSum += std::min(region.val.gSum * gain, (maxVal - 1) * region.counted); + bSum += std::min(region.val.bSum * gain, (maxVal - 1) * region.counted); + pixelSum += region.counted; + } + if (pixelSum == 0.0) { + LOG(RPiAgc, Warning) << "computeInitialY: pixelSum is zero"; + return 0; + } + + double ySum; + /* Factor in the AWB correction if needed. */ + if (stats->agcStatsPos == Statistics::AgcStatsPos::PreWb) { + ySum = rSum * awb.gainR * .299 + + gSum * awb.gainG * .587 + + bSum * awb.gainB * .114; + } else + ySum = rSum * .299 + gSum * .587 + bSum * .114; + + return ySum / pixelSum / (1 << 16); +} + +/* + * We handle extra gain through EV by adjusting our Y targets. However, you + * simply can't monitor histograms once they get very close to (or beyond!) + * saturation, so we clamp the Y targets to this value. It does mean that EV + * increases don't necessarily do quite what you might expect in certain + * (contrived) cases. + */ + +static constexpr double EvGainYTargetLimit = 0.9; + +static double constraintComputeGain(AgcConstraint &c, const Histogram &h, double lux, + double evGain, double &targetY) +{ + targetY = c.yTarget.eval(c.yTarget.domain().clip(lux)); + targetY = std::min(EvGainYTargetLimit, targetY * evGain); + double iqm = h.interQuantileMean(c.qLo, c.qHi); + return (targetY * h.bins()) / iqm; +} + +void AgcChannel::computeGain(StatisticsPtr &statistics, Metadata *imageMetadata, + double &gain, double &targetY) +{ + struct LuxStatus lux = {}; + lux.lux = 400; /* default lux level to 400 in case no metadata found */ + if (imageMetadata->get("lux.status", lux) != 0) + LOG(RPiAgc, Warning) << "No lux level found"; + const Histogram &h = statistics->yHist; + double evGain = status_.ev * config_.baseEv; + /* + * The initial gain and target_Y come from some of the regions. After + * that we consider the histogram constraints. + */ + targetY = config_.yTarget.eval(config_.yTarget.domain().clip(lux.lux)); + targetY = std::min(EvGainYTargetLimit, targetY * evGain); + + /* + * Do this calculation a few times as brightness increase can be + * non-linear when there are saturated regions. + */ + gain = 1.0; + for (int i = 0; i < 8; i++) { + double initialY = computeInitialY(statistics, awb_, meteringMode_->weights, gain); + double extraGain = std::min(10.0, targetY / (initialY + .001)); + gain *= extraGain; + LOG(RPiAgc, Debug) << "Initial Y " << initialY << " target " << targetY + << " gives gain " << gain; + if (extraGain < 1.01) /* close enough */ + break; + } + + for (auto &c : *constraintMode_) { + double newTargetY; + double newGain = constraintComputeGain(c, h, lux.lux, evGain, newTargetY); + LOG(RPiAgc, Debug) << "Constraint has target_Y " + << newTargetY << " giving gain " << newGain; + if (c.bound == AgcConstraint::Bound::LOWER && newGain > gain) { + LOG(RPiAgc, Debug) << "Lower bound constraint adopted"; + gain = newGain; + targetY = newTargetY; + } else if (c.bound == AgcConstraint::Bound::UPPER && newGain < gain) { + LOG(RPiAgc, Debug) << "Upper bound constraint adopted"; + gain = newGain; + targetY = newTargetY; + } + } + LOG(RPiAgc, Debug) << "Final gain " << gain << " (target_Y " << targetY << " ev " + << status_.ev << " base_ev " << config_.baseEv + << ")"; +} + +void AgcChannel::computeTargetExposure(double gain) +{ + if (status_.fixedShutter && status_.fixedAnalogueGain) { + /* + * When ag and shutter are both fixed, we need to drive the + * total exposure so that we end up with a digital gain of at least + * 1/minColourGain. Otherwise we'd desaturate channels causing + * white to go cyan or magenta. + */ + double minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 }); + ASSERT(minColourGain != 0.0); + target_.totalExposure = + status_.fixedShutter * status_.fixedAnalogueGain / minColourGain; + } else { + /* + * The statistics reflect the image without digital gain, so the final + * total exposure we're aiming for is: + */ + target_.totalExposure = current_.totalExposureNoDG * gain; + /* The final target exposure is also limited to what the exposure mode allows. */ + Duration maxShutter = status_.fixedShutter + ? status_.fixedShutter + : exposureMode_->shutter.back(); + maxShutter = limitShutter(maxShutter); + Duration maxTotalExposure = + maxShutter * + (status_.fixedAnalogueGain != 0.0 + ? status_.fixedAnalogueGain + : exposureMode_->gain.back()); + target_.totalExposure = std::min(target_.totalExposure, maxTotalExposure); + } + LOG(RPiAgc, Debug) << "Target totalExposure " << target_.totalExposure; +} + +bool AgcChannel::applyDigitalGain(double gain, double targetY) +{ + double minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 }); + ASSERT(minColourGain != 0.0); + double dg = 1.0 / minColourGain; + /* + * I think this pipeline subtracts black level and rescales before we + * get the stats, so no need to worry about it. + */ + LOG(RPiAgc, Debug) << "after AWB, target dg " << dg << " gain " << gain + << " target_Y " << targetY; + /* + * Finally, if we're trying to reduce exposure but the target_Y is + * "close" to 1.0, then the gain computed for that constraint will be + * only slightly less than one, because the measured Y can never be + * larger than 1.0. When this happens, demand a large digital gain so + * that the exposure can be reduced, de-saturating the image much more + * quickly (and we then approach the correct value more quickly from + * below). + */ + bool desaturate = targetY > config_.fastReduceThreshold && + gain < sqrt(targetY); + if (desaturate) + dg /= config_.fastReduceThreshold; + LOG(RPiAgc, Debug) << "Digital gain " << dg << " desaturate? " << desaturate; + filtered_.totalExposureNoDG = filtered_.totalExposure / dg; + LOG(RPiAgc, Debug) << "Target totalExposureNoDG " << filtered_.totalExposureNoDG; + return desaturate; +} + +void AgcChannel::filterExposure() +{ + double speed = config_.speed; + /* + * AGC adapts instantly if both shutter and gain are directly specified + * or we're in the startup phase. + */ + if ((status_.fixedShutter && status_.fixedAnalogueGain) || + frameCount_ <= config_.startupFrames) + speed = 1.0; + if (!filtered_.totalExposure) { + filtered_.totalExposure = target_.totalExposure; + } else { + /* + * If close to the result go faster, to save making so many + * micro-adjustments on the way. (Make this customisable?) + */ + if (filtered_.totalExposure < 1.2 * target_.totalExposure && + filtered_.totalExposure > 0.8 * target_.totalExposure) + speed = sqrt(speed); + filtered_.totalExposure = speed * target_.totalExposure + + filtered_.totalExposure * (1.0 - speed); + } + LOG(RPiAgc, Debug) << "After filtering, totalExposure " << filtered_.totalExposure + << " no dg " << filtered_.totalExposureNoDG; +} + +void AgcChannel::divideUpExposure() +{ + /* + * Sending the fixed shutter/gain cases through the same code may seem + * unnecessary, but it will make more sense when extend this to cover + * variable aperture. + */ + Duration exposureValue = filtered_.totalExposureNoDG; + Duration shutterTime; + double analogueGain; + shutterTime = status_.fixedShutter ? status_.fixedShutter + : exposureMode_->shutter[0]; + shutterTime = limitShutter(shutterTime); + analogueGain = status_.fixedAnalogueGain != 0.0 ? status_.fixedAnalogueGain + : exposureMode_->gain[0]; + analogueGain = limitGain(analogueGain); + if (shutterTime * analogueGain < exposureValue) { + for (unsigned int stage = 1; + stage < exposureMode_->gain.size(); stage++) { + if (!status_.fixedShutter) { + Duration stageShutter = + limitShutter(exposureMode_->shutter[stage]); + if (stageShutter * analogueGain >= exposureValue) { + shutterTime = exposureValue / analogueGain; + break; + } + shutterTime = stageShutter; + } + if (status_.fixedAnalogueGain == 0.0) { + if (exposureMode_->gain[stage] * shutterTime >= exposureValue) { + analogueGain = exposureValue / shutterTime; + break; + } + analogueGain = exposureMode_->gain[stage]; + analogueGain = limitGain(analogueGain); + } + } + } + LOG(RPiAgc, Debug) << "Divided up shutter and gain are " << shutterTime << " and " + << analogueGain; + /* + * Finally adjust shutter time for flicker avoidance (require both + * shutter and gain not to be fixed). + */ + if (!status_.fixedShutter && !status_.fixedAnalogueGain && + status_.flickerPeriod) { + int flickerPeriods = shutterTime / status_.flickerPeriod; + if (flickerPeriods) { + Duration newShutterTime = flickerPeriods * status_.flickerPeriod; + analogueGain *= shutterTime / newShutterTime; + /* + * We should still not allow the ag to go over the + * largest value in the exposure mode. Note that this + * may force more of the total exposure into the digital + * gain as a side-effect. + */ + analogueGain = std::min(analogueGain, exposureMode_->gain.back()); + analogueGain = limitGain(analogueGain); + shutterTime = newShutterTime; + } + LOG(RPiAgc, Debug) << "After flicker avoidance, shutter " + << shutterTime << " gain " << analogueGain; + } + filtered_.shutter = shutterTime; + filtered_.analogueGain = analogueGain; +} + +void AgcChannel::writeAndFinish(Metadata *imageMetadata, bool desaturate) +{ + status_.totalExposureValue = filtered_.totalExposure; + status_.targetExposureValue = desaturate ? 0s : target_.totalExposureNoDG; + status_.shutterTime = filtered_.shutter; + status_.analogueGain = filtered_.analogueGain; + /* + * Write to metadata as well, in case anyone wants to update the camera + * immediately. + */ + imageMetadata->set("agc.status", status_); + LOG(RPiAgc, Debug) << "Output written, total exposure requested is " + << filtered_.totalExposure; + LOG(RPiAgc, Debug) << "Camera exposure update: shutter time " << filtered_.shutter + << " analogue gain " << filtered_.analogueGain; +} + +Duration AgcChannel::limitShutter(Duration shutter) +{ + /* + * shutter == 0 is a special case for fixed shutter values, and must pass + * through unchanged + */ + if (!shutter) + return shutter; + + shutter = std::clamp(shutter, mode_.minShutter, maxShutter_); + return shutter; +} + +double AgcChannel::limitGain(double gain) const +{ + /* + * Only limit the lower bounds of the gain value to what the sensor limits. + * The upper bound on analogue gain will be made up with additional digital + * gain applied by the ISP. + * + * gain == 0.0 is a special case for fixed shutter values, and must pass + * through unchanged + */ + if (!gain) + return gain; + + gain = std::max(gain, mode_.minAnalogueGain); + return gain; +} diff --git a/src/ipa/rpi/controller/rpi/agc_channel.h b/src/ipa/rpi/controller/rpi/agc_channel.h new file mode 100644 index 00000000..aca79ef2 --- /dev/null +++ b/src/ipa/rpi/controller/rpi/agc_channel.h @@ -0,0 +1,137 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* + * Copyright (C) 2023, Raspberry Pi Ltd + * + * agc_channel.h - AGC/AEC control algorithm + */ +#pragma once + +#include +#include +#include + +#include + +#include "../agc_status.h" +#include "../awb_status.h" +#include "../controller.h" +#include "../pwl.h" + +/* This is our implementation of AGC. */ + +namespace RPiController { + +struct AgcMeteringMode { + std::vector weights; + int read(const libcamera::YamlObject ¶ms); +}; + +struct AgcExposureMode { + std::vector shutter; + std::vector gain; + int read(const libcamera::YamlObject ¶ms); +}; + +struct AgcConstraint { + enum class Bound { LOWER = 0, + UPPER = 1 }; + Bound bound; + double qLo; + double qHi; + Pwl yTarget; + int read(const libcamera::YamlObject ¶ms); +}; + +typedef std::vector AgcConstraintMode; + +struct AgcConfig { + int read(const libcamera::YamlObject ¶ms); + std::map meteringModes; + std::map exposureModes; + std::map constraintModes; + Pwl yTarget; + double speed; + uint16_t startupFrames; + unsigned int convergenceFrames; + double maxChange; + double minChange; + double fastReduceThreshold; + double speedUpThreshold; + std::string defaultMeteringMode; + std::string defaultExposureMode; + std::string defaultConstraintMode; + double baseEv; + libcamera::utils::Duration defaultExposureTime; + double defaultAnalogueGain; +}; + +class AgcChannel +{ +public: + AgcChannel(); + int read(const libcamera::YamlObject ¶ms, + const Controller::HardwareConfig &hardwareConfig); + unsigned int getConvergenceFrames() const; + std::vector const &getWeights() const; + void setEv(double ev); + void setFlickerPeriod(libcamera::utils::Duration flickerPeriod); + void setMaxShutter(libcamera::utils::Duration maxShutter); + void setFixedShutter(libcamera::utils::Duration fixedShutter); + void setFixedAnalogueGain(double fixedAnalogueGain); + void setMeteringMode(std::string const &meteringModeName); + void setExposureMode(std::string const &exposureModeName); + void setConstraintMode(std::string const &contraintModeName); + void enableAuto(); + void disableAuto(); + void switchMode(CameraMode const &cameraMode, Metadata *metadata); + void prepare(Metadata *imageMetadata); + void process(StatisticsPtr &stats, Metadata *imageMetadata); + +private: + bool updateLockStatus(DeviceStatus const &deviceStatus); + AgcConfig config_; + void housekeepConfig(); + void fetchCurrentExposure(Metadata *imageMetadata); + void fetchAwbStatus(Metadata *imageMetadata); + void computeGain(StatisticsPtr &statistics, Metadata *imageMetadata, + double &gain, double &targetY); + void computeTargetExposure(double gain); + void filterExposure(); + bool applyDigitalGain(double gain, double targetY); + void divideUpExposure(); + void writeAndFinish(Metadata *imageMetadata, bool desaturate); + libcamera::utils::Duration limitShutter(libcamera::utils::Duration shutter); + double limitGain(double gain) const; + AgcMeteringMode *meteringMode_; + AgcExposureMode *exposureMode_; + AgcConstraintMode *constraintMode_; + CameraMode mode_; + uint64_t frameCount_; + AwbStatus awb_; + struct ExposureValues { + ExposureValues(); + + libcamera::utils::Duration shutter; + double analogueGain; + libcamera::utils::Duration totalExposure; + libcamera::utils::Duration totalExposureNoDG; /* without digital gain */ + }; + ExposureValues current_; /* values for the current frame */ + ExposureValues target_; /* calculate the values we want here */ + ExposureValues filtered_; /* these values are filtered towards target */ + AgcStatus status_; + int lockCount_; + DeviceStatus lastDeviceStatus_; + libcamera::utils::Duration lastTargetExposure_; + /* Below here the "settings" that applications can change. */ + std::string meteringModeName_; + std::string exposureModeName_; + std::string constraintModeName_; + double ev_; + libcamera::utils::Duration flickerPeriod_; + libcamera::utils::Duration maxShutter_; + libcamera::utils::Duration fixedShutter_; + double fixedAnalogueGain_; +}; + +} /* namespace RPiController */ From patchwork Fri Sep 15 15:58:42 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: David Plowman X-Patchwork-Id: 19035 Return-Path: X-Original-To: parsemail@patchwork.libcamera.org Delivered-To: parsemail@patchwork.libcamera.org Received: from lancelot.ideasonboard.com (lancelot.ideasonboard.com [92.243.16.209]) by patchwork.libcamera.org (Postfix) with ESMTPS id 31F0CBD160 for ; Fri, 15 Sep 2023 15:58:57 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id EA48A62921; Fri, 15 Sep 2023 17:58:56 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=libcamera.org; s=mail; t=1694793536; bh=kDvFivpZq9caH0degRJnhUg+rglJdU5NoAnVjqFM6TM=; h=To:Date:In-Reply-To:References:Subject:List-Id:List-Unsubscribe: List-Archive:List-Post:List-Help:List-Subscribe:From:Reply-To:Cc: From; b=u0rZwK5OAp38pZmAIgX6HB9SnBLMbg3wKDbBDU+0PmuAIL3LPOJDIdj+EIdS1zXJW jaoHeDqvNNolOc3wHdHvVZQItQ0cynrkEbSkXc4oK9kYLT8jHljX2gD7BO/JS+6lFz qG8KF0OkGERromZWI47PB19KOvTGiLVds2iup5RYREeHMgRSVnXY6Ofp0EwiPOTGEb vVn3W+FGtY4rGoRuMykX+MJ0yyn/I1Qeaj3Q3y3u9H5p2ngE1Br+PlykNw5lz4MAbJ FvN9LKj0LbtjetbKvYALGiVvjDYrHiP+y5j/dG4aZVIaKkPSu8yZFZifP3J3bxS2fc zKZiVaYzQTtng== Received: from mail-wm1-x333.google.com (mail-wm1-x333.google.com [IPv6:2a00:1450:4864:20::333]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id EB73662911 for ; Fri, 15 Sep 2023 17:58:54 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (2048-bit key; unprotected) header.d=raspberrypi.com header.i=@raspberrypi.com header.b="snj5xgpf"; dkim-atps=neutral Received: by mail-wm1-x333.google.com with SMTP id 5b1f17b1804b1-403012f276dso25195645e9.0 for ; Fri, 15 Sep 2023 08:58:54 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=raspberrypi.com; s=google; t=1694793534; x=1695398334; darn=lists.libcamera.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=U/rHJIkqU9vIBuZ09yYrNreBBtCiFbyfxMTz9Zj09+Q=; b=snj5xgpf1QCLLXl3lo2eWZJVOulRN4JRPW9cF3obdvla32Bn/Pt/G9H+mb3HUXE4N8 H0owOpmV/sCXf6L7xoDD0yC22FOuwxMpWsBQKAdLGOdeUCuDKMAkYEl8oom7kLqZsrvb oKFOM9AzYRSZl7PHeRrj9OYF5qzZFc6P3MhnCxKzE9brxufYG4HrGtf3EgEhf6x/Tw7k /mBS17LzBnv5J2r15ABunCuTcEDg05ejZ3OKCAZVFGAFKgEd1t7Pcurlc5hml4qwqQGv Alj+Wq1O3qqXmbPdjKhPDYOB7XU8wADOmJq+RO6s+c4pal9c5jx0MRdHw61/brzn809M B7ag== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1694793534; x=1695398334; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=U/rHJIkqU9vIBuZ09yYrNreBBtCiFbyfxMTz9Zj09+Q=; b=NSeQJar8zCzF1F+p0TGq5yK656IwhJp9cJRp43Qd8wdYnoAWYVkFVaDo4odaiRfJSu RlFoOiusbAoAmPTLOrjlUE/kXQBcJzzAvoemjuVSi9azk1+ccaKv2AYu23xS6+PBd/vf aKEg22m6I+LlwI9Zw4RdzX8B8nV93a7EUcS2DK7aov3mSEQM2psBrvfch1BkLcGbu5/i eXgCzTnvE0Ylm/M58D4fRJUGBqwjWsafjep9RqygV42DMF0QgyUkKPzBTxwxfV54NIR6 VfUk2OJm9thkIxeNu+G0FCoJSKJ1/abKglv2c1YXv38yoRdST360wNhDkvRwKcdmTJWQ 3HBw== X-Gm-Message-State: AOJu0YyoWcj0c5dgbN9G9yEGF8gUsYjje1naQ9iFTYJPNAjfUCOURqGw a65feaeWoZjBMIUXY94zcB05AHjSol2l+IzRFPQ= X-Google-Smtp-Source: AGHT+IFYQeXhnPuOezE/u7DJXxRMy919Y4mshKkkWSLtF31KF23BpAgbbFRf2rKhhpuv7N3lzUyw/w== X-Received: by 2002:a05:600c:21cb:b0:401:bf87:9895 with SMTP id x11-20020a05600c21cb00b00401bf879895mr1973502wmj.22.1694793533946; Fri, 15 Sep 2023 08:58:53 -0700 (PDT) Received: from localhost.localdomain ([195.180.61.40]) by smtp.gmail.com with ESMTPSA id l13-20020a7bc44d000000b00401c595fcc7sm7810618wmi.11.2023.09.15.08.58.53 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 15 Sep 2023 08:58:53 -0700 (PDT) To: libcamera-devel@lists.libcamera.org Date: Fri, 15 Sep 2023 16:58:42 +0100 Message-Id: <20230915155844.2388-4-david.plowman@raspberrypi.com> X-Mailer: git-send-email 2.30.2 In-Reply-To: <20230915155844.2388-1-david.plowman@raspberrypi.com> References: <20230915155844.2388-1-david.plowman@raspberrypi.com> MIME-Version: 1.0 Subject: [libcamera-devel] [PATCH v5 3/5] ipa: rpi: agc: Implementation of multi-channel AGC X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Patchwork-Original-From: David Plowman via libcamera-devel From: David Plowman Reply-To: David Plowman Cc: Jacopo Mondi Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" The switchMode, prepare and process methods are updated to implement multi-channel AGC correctly: * switchMode now invokes switchMode on all the channels (whether active or not). * prepare must find what channel the current frame is, and run on behalf of that channel. * process updates the most recent DeviceStatus and statistics for the channel of the frame that has just arrived, but generates updated values working through the active channels in round-robin fashion. One minor detail in process is that we don't want to change the DeviceStatus metadata of the current frame, so we now pass this to the AgcChannel's process method, rather than letting it find the DeviceStatus in the metadata. Signed-off-by: David Plowman Reviewed-by: Naushir Patuck Reviewed-by: Jacopo Mondi --- src/ipa/rpi/controller/agc_status.h | 1 + src/ipa/rpi/controller/rpi/agc.cpp | 110 +++++++++++++++++++-- src/ipa/rpi/controller/rpi/agc.h | 4 + src/ipa/rpi/controller/rpi/agc_channel.cpp | 19 ++-- src/ipa/rpi/controller/rpi/agc_channel.h | 4 +- 5 files changed, 116 insertions(+), 22 deletions(-) diff --git a/src/ipa/rpi/controller/agc_status.h b/src/ipa/rpi/controller/agc_status.h index 597eddd7..e5c4ee22 100644 --- a/src/ipa/rpi/controller/agc_status.h +++ b/src/ipa/rpi/controller/agc_status.h @@ -36,6 +36,7 @@ struct AgcStatus { int floatingRegionEnable; libcamera::utils::Duration fixedShutter; double fixedAnalogueGain; + unsigned int channel; }; struct AgcPrepareStatus { diff --git a/src/ipa/rpi/controller/rpi/agc.cpp b/src/ipa/rpi/controller/rpi/agc.cpp index 598fc890..8b9d2026 100644 --- a/src/ipa/rpi/controller/rpi/agc.cpp +++ b/src/ipa/rpi/controller/rpi/agc.cpp @@ -22,7 +22,7 @@ LOG_DEFINE_CATEGORY(RPiAgc) Agc::Agc(Controller *controller) : AgcAlgorithm(controller), - activeChannels_({ 0 }) + activeChannels_({ 0 }), index_(0) { } @@ -205,20 +205,116 @@ void Agc::setActiveChannels(const std::vector &activeChannels) void Agc::switchMode(CameraMode const &cameraMode, Metadata *metadata) { - LOG(RPiAgc, Debug) << "switchMode for channel 0"; - channelData_[0].channel.switchMode(cameraMode, metadata); + /* + * We run switchMode on every channel, and then we're going to start over + * with the first active channel again which means that this channel's + * status needs to be the one we leave in the metadata. + */ + AgcStatus status; + + for (unsigned int channelIndex = 0; channelIndex < channelData_.size(); channelIndex++) { + LOG(RPiAgc, Debug) << "switchMode for channel " << channelIndex; + channelData_[channelIndex].channel.switchMode(cameraMode, metadata); + if (channelIndex == activeChannels_[0]) + metadata->get("agc.status", status); + } + + status.channel = activeChannels_[0]; + metadata->set("agc.status", status); + index_ = 0; +} + +static void getDelayedChannelIndex(Metadata *metadata, const char *message, unsigned int &channelIndex) +{ + std::unique_lock lock(*metadata); + AgcStatus *status = metadata->getLocked("agc.delayed_status"); + if (status) + channelIndex = status->channel; + else { + /* This does happen at startup, otherwise it would be a Warning or Error. */ + LOG(RPiAgc, Debug) << message; + } +} + +static void setCurrentChannelIndex(Metadata *metadata, const char *message, unsigned int channelIndex) +{ + std::unique_lock lock(*metadata); + AgcStatus *status = metadata->getLocked("agc.status"); + if (status) + status->channel = channelIndex; + else { + /* This does happen at startup, otherwise it would be a Warning or Error. */ + LOG(RPiAgc, Debug) << message; + } } void Agc::prepare(Metadata *imageMetadata) { - LOG(RPiAgc, Debug) << "prepare for channel 0"; - channelData_[0].channel.prepare(imageMetadata); + /* + * The DeviceStatus in the metadata should be correct for the image we + * are processing. The delayed status should tell us what channel this frame + * was from, so we will use that channel's prepare method. + * + * \todo To be honest, there's not much that's stateful in the prepare methods + * so we should perhaps re-evaluate whether prepare even needs to be done + * "per channel". + */ + unsigned int channelIndex = activeChannels_[0]; + getDelayedChannelIndex(imageMetadata, "prepare: no delayed status", channelIndex); + + LOG(RPiAgc, Debug) << "prepare for channel " << channelIndex; + channelData_[channelIndex].channel.prepare(imageMetadata); } void Agc::process(StatisticsPtr &stats, Metadata *imageMetadata) { - LOG(RPiAgc, Debug) << "process for channel 0"; - channelData_[0].channel.process(stats, imageMetadata); + /* + * We want to generate values for the next channel in round robin fashion + * (i.e. the channel at location index_ in the activeChannel list), even though + * the statistics we have will be for a different channel (which we find + * again from the delayed status). + */ + + /* Generate updated AGC values for channel for new channel that we are requesting. */ + unsigned int channelIndex = activeChannels_[index_]; + AgcChannelData &channelData = channelData_[channelIndex]; + /* The stats that arrived with this image correspond to the following channel. */ + unsigned int statsIndex = 0; + getDelayedChannelIndex(imageMetadata, "process: no delayed status for stats", statsIndex); + LOG(RPiAgc, Debug) << "process for channel " << channelIndex; + + /* + * We keep a cache of the most recent DeviceStatus and stats for each channel, + * so that we can invoke the next channel's process method with the most up to date + * values. + */ + LOG(RPiAgc, Debug) << "Save DeviceStatus and stats for channel " << statsIndex; + DeviceStatus deviceStatus; + if (imageMetadata->get("device.status", deviceStatus) == 0) + channelData_[statsIndex].deviceStatus = deviceStatus; + else + /* Every frame should have a DeviceStatus. */ + LOG(RPiAgc, Error) << "process: no device status found"; + channelData_[statsIndex].statistics = stats; + + /* + * Finally fetch the most recent DeviceStatus and stats for the new channel, if both + * exist, and call process(). We must make the agc.status metadata record correctly + * which channel this is. + */ + if (channelData.statistics && channelData.deviceStatus) { + deviceStatus = *channelData.deviceStatus; + stats = channelData.statistics; + } else { + /* Can also happen when new channels start. */ + LOG(RPiAgc, Debug) << "process: channel " << channelIndex << " not seen yet"; + } + + channelData.channel.process(stats, deviceStatus, imageMetadata); + setCurrentChannelIndex(imageMetadata, "process: no AGC status found", channelIndex); + + /* And onto the next channel for the next call. */ + index_ = (index_ + 1) % activeChannels_.size(); } /* Register algorithm with the system. */ diff --git a/src/ipa/rpi/controller/rpi/agc.h b/src/ipa/rpi/controller/rpi/agc.h index a476ea70..ee85c693 100644 --- a/src/ipa/rpi/controller/rpi/agc.h +++ b/src/ipa/rpi/controller/rpi/agc.h @@ -6,6 +6,7 @@ */ #pragma once +#include #include #include @@ -17,6 +18,8 @@ namespace RPiController { struct AgcChannelData { AgcChannel channel; + std::optional deviceStatus; + StatisticsPtr statistics; }; class Agc : public AgcAlgorithm @@ -51,6 +54,7 @@ private: int checkChannel(unsigned int channel) const; std::vector channelData_; std::vector activeChannels_; + unsigned int index_; /* index into the activeChannels_ */ }; } /* namespace RPiController */ diff --git a/src/ipa/rpi/controller/rpi/agc_channel.cpp b/src/ipa/rpi/controller/rpi/agc_channel.cpp index f180b848..84eafe7d 100644 --- a/src/ipa/rpi/controller/rpi/agc_channel.cpp +++ b/src/ipa/rpi/controller/rpi/agc_channel.cpp @@ -444,7 +444,7 @@ void AgcChannel::prepare(Metadata *imageMetadata) } } -void AgcChannel::process(StatisticsPtr &stats, Metadata *imageMetadata) +void AgcChannel::process(StatisticsPtr &stats, DeviceStatus const &deviceStatus, Metadata *imageMetadata) { frameCount_++; /* @@ -455,7 +455,7 @@ void AgcChannel::process(StatisticsPtr &stats, Metadata *imageMetadata) /* Fetch the AWB status immediately, so that we can assume it's there. */ fetchAwbStatus(imageMetadata); /* Get the current exposure values for the frame that's just arrived. */ - fetchCurrentExposure(imageMetadata); + fetchCurrentExposure(deviceStatus); /* Compute the total gain we require relative to the current exposure. */ double gain, targetY; computeGain(stats, imageMetadata, gain, targetY); @@ -567,18 +567,11 @@ void AgcChannel::housekeepConfig() << meteringModeName_; } -void AgcChannel::fetchCurrentExposure(Metadata *imageMetadata) +void AgcChannel::fetchCurrentExposure(DeviceStatus const &deviceStatus) { - std::unique_lock lock(*imageMetadata); - DeviceStatus *deviceStatus = - imageMetadata->getLocked("device.status"); - if (!deviceStatus) - LOG(RPiAgc, Fatal) << "No device metadata"; - current_.shutter = deviceStatus->shutterSpeed; - current_.analogueGain = deviceStatus->analogueGain; - AgcStatus *agcStatus = - imageMetadata->getLocked("agc.status"); - current_.totalExposure = agcStatus ? agcStatus->totalExposureValue : 0s; + current_.shutter = deviceStatus.shutterSpeed; + current_.analogueGain = deviceStatus.analogueGain; + current_.totalExposure = 0s; /* this value is unused */ current_.totalExposureNoDG = current_.shutter * current_.analogueGain; } diff --git a/src/ipa/rpi/controller/rpi/agc_channel.h b/src/ipa/rpi/controller/rpi/agc_channel.h index aca79ef2..b2f554db 100644 --- a/src/ipa/rpi/controller/rpi/agc_channel.h +++ b/src/ipa/rpi/controller/rpi/agc_channel.h @@ -85,13 +85,13 @@ public: void disableAuto(); void switchMode(CameraMode const &cameraMode, Metadata *metadata); void prepare(Metadata *imageMetadata); - void process(StatisticsPtr &stats, Metadata *imageMetadata); + void process(StatisticsPtr &stats, DeviceStatus const &deviceStatus, Metadata *imageMetadata); private: bool updateLockStatus(DeviceStatus const &deviceStatus); AgcConfig config_; void housekeepConfig(); - void fetchCurrentExposure(Metadata *imageMetadata); + void fetchCurrentExposure(DeviceStatus const &deviceStatus); void fetchAwbStatus(Metadata *imageMetadata); void computeGain(StatisticsPtr &statistics, Metadata *imageMetadata, double &gain, double &targetY); From patchwork Fri Sep 15 15:58:43 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: David Plowman X-Patchwork-Id: 19037 Return-Path: X-Original-To: parsemail@patchwork.libcamera.org Delivered-To: parsemail@patchwork.libcamera.org Received: from lancelot.ideasonboard.com (lancelot.ideasonboard.com [92.243.16.209]) by patchwork.libcamera.org (Postfix) with ESMTPS id 0C138BD160 for ; Fri, 15 Sep 2023 15:58:59 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 2FC1162922; Fri, 15 Sep 2023 17:58:58 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=libcamera.org; s=mail; t=1694793538; bh=5PzYmMOI5wAtHa3mMKkYWwZMOkHBy0H98iLwtngsCZI=; h=To:Date:In-Reply-To:References:Subject:List-Id:List-Unsubscribe: List-Archive:List-Post:List-Help:List-Subscribe:From:Reply-To:Cc: From; b=DFQsLOIpqqsFZ9/Z9bspGHH5olGi7KIwZ5vWmMT/UJ/3rGJSvj59frOkXXUGHXHmH cKBIbHIH5WFq1AS0FYiJrKxK4AimLz+rds1iemvnGHscfa/9UQ9JbzJythw8C9bslL NXNcsNcnKy5zD4eSFiAZoYLT6LeN1z8xrqMn+SYlbKG+XgQYPztmN9eUZNgh9Ox48p KvQnUavgxUQGagEoOqtffd1dug3nLS6bClVTnI6qfWDHf6hXmN5fAFxWdn3L8igsn+ SYFKntxSTMeI3bPThXc7pDidSsszxl00+eVgStqB0BSi3x57g5bMwnd5HA056ORQ18 krz0jJvbEWqWw== Received: from mail-wm1-x332.google.com (mail-wm1-x332.google.com [IPv6:2a00:1450:4864:20::332]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 7B7AF6291C for ; Fri, 15 Sep 2023 17:58:55 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (2048-bit key; unprotected) header.d=raspberrypi.com header.i=@raspberrypi.com header.b="C4KMXmcv"; dkim-atps=neutral Received: by mail-wm1-x332.google.com with SMTP id 5b1f17b1804b1-402d499580dso25007765e9.1 for ; Fri, 15 Sep 2023 08:58:55 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=raspberrypi.com; s=google; t=1694793535; x=1695398335; darn=lists.libcamera.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=L5ti10stfJGjHOx0NZCJZ7ipLRVCzaFb97PYLKAMgso=; b=C4KMXmcvDjDn1dQcfMhF5yqzECNpJoyzX4L0n116h/ZZO/Jm4X6foERnApE0OtJ+QL 1prY3OvNr9/7EdRzyXVCR3ydL2sCDcXfKIr+lh+1BTz2yd8V3IBATuFvVyp9LOgm2oT2 H6daYKS9JvD2aA+0WUl4VmDRPgiJcGrk9X/E7Nuc6UxDFe2fPjgmgOQof/wQZzGerEUH PF5qniIq6zT9Pm9nq5W5i3NDIDVuiL/QxfPPD8M0PUP35RmNm07vcnxARHc8YY/GhK1P /C0QuqW08BsN6rZniQm64HXFWfGf0zM9CnPQ2gcC2l2H4CPRDrHYNEk0MXXuasBcCZH9 9LxA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1694793535; x=1695398335; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=L5ti10stfJGjHOx0NZCJZ7ipLRVCzaFb97PYLKAMgso=; b=VVKj75qVJbaOFP5z1FyJdwxYLnxEgEuq6Z+R5eWF7ywmMyK53suzVfNX/0DHUSxgjV s9qt8zYrrrnYG7Yza5nNOYtz+X0moqKGtVYvorpi4JBvPO9JxAOpRYZ79bclg2Fltk0Z Ie+ZBAQCo6+d2E9cMVXsCuDVRMv/EEM6R8hKkUMGStx7iyZv4Lv61LikcD+mPIrp/RvX uypEMJRd9J7dQkUlSHqwxkIEsaOISII3EUCKJ5x68gOfgeNk6aG3r+DLjZDhit4K/E6m vD88LkjwJMnlL4VGs+DFzK5OYCShuu9pCxiRDAIUhpBXPDzU3SCfT/QExXxC6I90N5fO AbDg== X-Gm-Message-State: AOJu0YzpPSRIxBicEGMLgHIjWeh96bc6DjgKYCWZY70eW/96NMMr3QPD CXf4iV/K7GY5tedNuQc0BfMrTMzqV/tiVknuem8= X-Google-Smtp-Source: AGHT+IGLeC++Kp1wkV7LzaDbMCZwk9g48Mhc4qdfpHUbcG5BG1LnKTbcpoymWuEpg+ofjoRc274qjg== X-Received: by 2002:a1c:7706:0:b0:401:2ee0:754a with SMTP id t6-20020a1c7706000000b004012ee0754amr2109767wmi.13.1694793534728; Fri, 15 Sep 2023 08:58:54 -0700 (PDT) Received: from localhost.localdomain ([195.180.61.40]) by smtp.gmail.com with ESMTPSA id l13-20020a7bc44d000000b00401c595fcc7sm7810618wmi.11.2023.09.15.08.58.54 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 15 Sep 2023 08:58:54 -0700 (PDT) To: libcamera-devel@lists.libcamera.org Date: Fri, 15 Sep 2023 16:58:43 +0100 Message-Id: <20230915155844.2388-5-david.plowman@raspberrypi.com> X-Mailer: git-send-email 2.30.2 In-Reply-To: <20230915155844.2388-1-david.plowman@raspberrypi.com> References: <20230915155844.2388-1-david.plowman@raspberrypi.com> MIME-Version: 1.0 Subject: [libcamera-devel] [PATCH v5 4/5] ipa: rpi: agc: Add AgcChannelConstraint class X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Patchwork-Original-From: David Plowman via libcamera-devel From: David Plowman Reply-To: David Plowman Cc: Jacopo Mondi Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" A channel constraint is somewhat similar to the upper/lower bound constraints that we use elsewhere, but these constraints apply between multiple AGC channels. For example, it lets you say things like "don't let the channel 1 total exposure be more than 8x that of channel 0", and so on. By using both an upper and lower bound constraint, you could fix one AGC channel always to be a fixed ratio of another. Also read a vector of them (if present) when loading the tuning file. Signed-off-by: David Plowman Reviewed-by: Naushir Patuck Reviewed-by: Jacopo Mondi --- src/ipa/rpi/controller/rpi/agc_channel.cpp | 49 ++++++++++++++++++++++ src/ipa/rpi/controller/rpi/agc_channel.h | 10 +++++ 2 files changed, 59 insertions(+) diff --git a/src/ipa/rpi/controller/rpi/agc_channel.cpp b/src/ipa/rpi/controller/rpi/agc_channel.cpp index 84eafe7d..dfe363ff 100644 --- a/src/ipa/rpi/controller/rpi/agc_channel.cpp +++ b/src/ipa/rpi/controller/rpi/agc_channel.cpp @@ -170,6 +170,49 @@ readConstraintModes(std::map &constraintModes, return { 0, first }; } +int AgcChannelConstraint::read(const libcamera::YamlObject ¶ms) +{ + auto channelValue = params["channel"].get(); + if (!channelValue) { + LOG(RPiAgc, Error) << "AGC channel constraint must have a channel"; + return -EINVAL; + } + channel = *channelValue; + + std::string boundString = params["bound"].get(""); + transform(boundString.begin(), boundString.end(), + boundString.begin(), ::toupper); + if (boundString != "UPPER" && boundString != "LOWER") { + LOG(RPiAgc, Error) << "AGC channel constraint type should be UPPER or LOWER"; + return -EINVAL; + } + bound = boundString == "UPPER" ? Bound::UPPER : Bound::LOWER; + + auto factorValue = params["factor"].get(); + if (!factorValue) { + LOG(RPiAgc, Error) << "AGC channel constraint must have a factor"; + return -EINVAL; + } + factor = *factorValue; + + return 0; +} + +static int readChannelConstraints(std::vector &channelConstraints, + const libcamera::YamlObject ¶ms) +{ + for (const auto &p : params.asList()) { + AgcChannelConstraint constraint; + int ret = constraint.read(p); + if (ret) + return ret; + + channelConstraints.push_back(constraint); + } + + return 0; +} + int AgcConfig::read(const libcamera::YamlObject ¶ms) { LOG(RPiAgc, Debug) << "AgcConfig"; @@ -188,6 +231,12 @@ int AgcConfig::read(const libcamera::YamlObject ¶ms) if (ret) return ret; + if (params.contains("channel_constraints")) { + ret = readChannelConstraints(channelConstraints, params["channel_constraints"]); + if (ret) + return ret; + } + ret = yTarget.read(params["y_target"]); if (ret) return ret; diff --git a/src/ipa/rpi/controller/rpi/agc_channel.h b/src/ipa/rpi/controller/rpi/agc_channel.h index b2f554db..ceaab12f 100644 --- a/src/ipa/rpi/controller/rpi/agc_channel.h +++ b/src/ipa/rpi/controller/rpi/agc_channel.h @@ -44,11 +44,21 @@ struct AgcConstraint { typedef std::vector AgcConstraintMode; +struct AgcChannelConstraint { + enum class Bound { LOWER = 0, + UPPER = 1 }; + Bound bound; + unsigned int channel; + double factor; + int read(const libcamera::YamlObject ¶ms); +}; + struct AgcConfig { int read(const libcamera::YamlObject ¶ms); std::map meteringModes; std::map exposureModes; std::map constraintModes; + std::vector channelConstraints; Pwl yTarget; double speed; uint16_t startupFrames; From patchwork Fri Sep 15 15:58:44 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: David Plowman X-Patchwork-Id: 19038 Return-Path: X-Original-To: parsemail@patchwork.libcamera.org Delivered-To: parsemail@patchwork.libcamera.org Received: from lancelot.ideasonboard.com (lancelot.ideasonboard.com [92.243.16.209]) by patchwork.libcamera.org (Postfix) with ESMTPS id 0A949C32B0 for ; Fri, 15 Sep 2023 15:59:00 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id A196C6291C; Fri, 15 Sep 2023 17:58:59 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=libcamera.org; s=mail; t=1694793539; bh=Eo/H8q5i3+FT5oPUdT+DXN8pB6mxy+TQNhCh9E9Fw0k=; h=To:Date:In-Reply-To:References:Subject:List-Id:List-Unsubscribe: List-Archive:List-Post:List-Help:List-Subscribe:From:Reply-To:Cc: From; b=L0xe4GKgpiCl4KHX/1ozarwgQtsm+z4a/rEtv6mCOq1N3b74HT0cyAHHBDNxBeBJ/ MzR1IJWZa4+mFMzdU0/8gtn3El/HrrELtTSx3qe0ppdSNt+gz65/IiW38IPpi7uWCe 3HO8f0YuYbclsS4k87YneIK7o7IzkL3YzFbC3D29anc3zfK6Nm0vvkcSEVl5VH8OLm uoA8EnM6BZ1kDqlk9pwW2bXSRCv2ohQmCgIhRcVLo/zphW/bFLqaiyYiixPmuyt/Mu x58tzuqwe6hdhgylKdUtp8nzPIOuR8Ia3wPqCmuTaIqm3v42rKcNFWfWAWBKlTMHYf 0Cdry3XaomF+g== Received: from mail-wm1-x336.google.com (mail-wm1-x336.google.com [IPv6:2a00:1450:4864:20::336]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 74A7762916 for ; Fri, 15 Sep 2023 17:58:56 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (2048-bit key; unprotected) header.d=raspberrypi.com header.i=@raspberrypi.com header.b="necXUJas"; dkim-atps=neutral Received: by mail-wm1-x336.google.com with SMTP id 5b1f17b1804b1-403012f276dso25196005e9.0 for ; Fri, 15 Sep 2023 08:58:56 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=raspberrypi.com; s=google; t=1694793536; x=1695398336; darn=lists.libcamera.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=CWSOLadTJtKvYCIdSC1vIHqtxyxalOIgM1mgM1CtEyU=; b=necXUJas2zjLc9ffC2RyvFtrPr7wzxrG+zssWAlo8v7q/hp6Il4LVsFPlvlzEE9fGy ojxpw3fjK480ki/w/+EOdBZ2dOmSWsEPgp6kIk3bqCDYxq0O52H4Dm9DJDB9aIO/IZA+ E0Cy1H6E2If3zYsmGzkg9VpjGnbVMeqcVlfOTKyEEzKXpxin8ozj7uHKaTtXQsI2hPI6 P8wluqVjG5YI3cK1oADtpnWO7XSkcIiTtILO5EeS3nbUMSvXVCPQiDjlvwcRhp5G4gdS 20oLZh8eFe6fEaPukZHaMrmu1ZtCPU0xBDdg7mKI5cxmkSEPIUetiW22ddLsyfFT9Hp2 O8UA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1694793536; x=1695398336; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=CWSOLadTJtKvYCIdSC1vIHqtxyxalOIgM1mgM1CtEyU=; b=Y3v3DaUwvkCqp04RcVBqz/rF9uO50eWPpOKLXsVXtUX4O5FvYOFRt2cEffB+fO7wZh +Bg+8gE2LPqspAK4JHdwQGWTktYXMbAt6jUiiTvDTMZofUIYjho+6TZ0Sz2RVpTrG/6c 5+pdMIXYza4WnuEUr+6LKl+jOp7RbdKNZaNpaBYwlJjG2retfoTttcesWJMQn15420fF 3h7yxXGHwqq1uKlAC886XOr7+nPJOVluucGWqhoLB7C9imQF+ondkb/BZsXfytu0mKzL RPdWzy47I16mwnK/l5FRTbuzx3BCewjZKIO5dl3ZD3RmdDvG75hazb5Jp58qBxKPANoM 2j8A== X-Gm-Message-State: AOJu0YyeMShsxp2XMhHzDZMBPPtnXkI+QZRwweXxdJnrrOyfra4lEEx/ hE6ZtA1AMeLx4xlhfp1/vYTZLas3bwYKeSSVHhI= X-Google-Smtp-Source: AGHT+IGKSnYOg6OYaFozE1b/GNHwX42q7UjAGTjEM0ZApSFAWbe0g6XmZA4pD7nSYfYn77KVX3R7QQ== X-Received: by 2002:a05:600c:2209:b0:404:746e:c601 with SMTP id z9-20020a05600c220900b00404746ec601mr2104418wml.9.1694793535672; Fri, 15 Sep 2023 08:58:55 -0700 (PDT) Received: from localhost.localdomain ([195.180.61.40]) by smtp.gmail.com with ESMTPSA id l13-20020a7bc44d000000b00401c595fcc7sm7810618wmi.11.2023.09.15.08.58.54 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 15 Sep 2023 08:58:55 -0700 (PDT) To: libcamera-devel@lists.libcamera.org Date: Fri, 15 Sep 2023 16:58:44 +0100 Message-Id: <20230915155844.2388-6-david.plowman@raspberrypi.com> X-Mailer: git-send-email 2.30.2 In-Reply-To: <20230915155844.2388-1-david.plowman@raspberrypi.com> References: <20230915155844.2388-1-david.plowman@raspberrypi.com> MIME-Version: 1.0 Subject: [libcamera-devel] [PATCH v5 5/5] ipa: rpi: agc: Use channel constraints in the AGC algorithm X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Patchwork-Original-From: David Plowman via libcamera-devel From: David Plowman Reply-To: David Plowman Cc: Jacopo Mondi Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" Whenever we run Agc::process(), we store the most recent total exposure requested for each channel. With these values we can apply the channel constraints after time-filtering the requested total exposure, but before working out how much digital gain is needed. Signed-off-by: David Plowman Reviewed-by: Naushir Patuck Reviewed-by: Jacopo Mondi --- src/ipa/rpi/controller/rpi/agc.cpp | 22 ++++++-- src/ipa/rpi/controller/rpi/agc.h | 1 + src/ipa/rpi/controller/rpi/agc_channel.cpp | 58 +++++++++++++++++++--- src/ipa/rpi/controller/rpi/agc_channel.h | 8 ++- 4 files changed, 75 insertions(+), 14 deletions(-) diff --git a/src/ipa/rpi/controller/rpi/agc.cpp b/src/ipa/rpi/controller/rpi/agc.cpp index 8b9d2026..870cb431 100644 --- a/src/ipa/rpi/controller/rpi/agc.cpp +++ b/src/ipa/rpi/controller/rpi/agc.cpp @@ -39,6 +39,7 @@ int Agc::read(const libcamera::YamlObject ¶ms) */ if (!params.contains("channels")) { LOG(RPiAgc, Debug) << "Single channel only"; + channelTotalExposures_.resize(1, 0s); channelData_.emplace_back(); return channelData_.back().channel.read(params, getHardwareConfig()); } @@ -58,6 +59,8 @@ int Agc::read(const libcamera::YamlObject ¶ms) return -1; } + channelTotalExposures_.resize(channelData_.size(), 0s); + return 0; } @@ -236,16 +239,22 @@ static void getDelayedChannelIndex(Metadata *metadata, const char *message, unsi } } -static void setCurrentChannelIndex(Metadata *metadata, const char *message, unsigned int channelIndex) +static libcamera::utils::Duration +setCurrentChannelIndexGetExposure(Metadata *metadata, const char *message, unsigned int channelIndex) { std::unique_lock lock(*metadata); AgcStatus *status = metadata->getLocked("agc.status"); - if (status) + libcamera::utils::Duration dur = 0s; + + if (status) { status->channel = channelIndex; - else { + dur = status->totalExposureValue; + } else { /* This does happen at startup, otherwise it would be a Warning or Error. */ LOG(RPiAgc, Debug) << message; } + + return dur; } void Agc::prepare(Metadata *imageMetadata) @@ -310,8 +319,11 @@ void Agc::process(StatisticsPtr &stats, Metadata *imageMetadata) LOG(RPiAgc, Debug) << "process: channel " << channelIndex << " not seen yet"; } - channelData.channel.process(stats, deviceStatus, imageMetadata); - setCurrentChannelIndex(imageMetadata, "process: no AGC status found", channelIndex); + channelData.channel.process(stats, deviceStatus, imageMetadata, channelTotalExposures_); + auto dur = setCurrentChannelIndexGetExposure(imageMetadata, "process: no AGC status found", + channelIndex); + if (dur) + channelTotalExposures_[channelIndex] = dur; /* And onto the next channel for the next call. */ index_ = (index_ + 1) % activeChannels_.size(); diff --git a/src/ipa/rpi/controller/rpi/agc.h b/src/ipa/rpi/controller/rpi/agc.h index ee85c693..90890439 100644 --- a/src/ipa/rpi/controller/rpi/agc.h +++ b/src/ipa/rpi/controller/rpi/agc.h @@ -55,6 +55,7 @@ private: std::vector channelData_; std::vector activeChannels_; unsigned int index_; /* index into the activeChannels_ */ + AgcChannelTotalExposures channelTotalExposures_; }; } /* namespace RPiController */ diff --git a/src/ipa/rpi/controller/rpi/agc_channel.cpp b/src/ipa/rpi/controller/rpi/agc_channel.cpp index dfe363ff..3957dbc3 100644 --- a/src/ipa/rpi/controller/rpi/agc_channel.cpp +++ b/src/ipa/rpi/controller/rpi/agc_channel.cpp @@ -493,7 +493,9 @@ void AgcChannel::prepare(Metadata *imageMetadata) } } -void AgcChannel::process(StatisticsPtr &stats, DeviceStatus const &deviceStatus, Metadata *imageMetadata) +void AgcChannel::process(StatisticsPtr &stats, DeviceStatus const &deviceStatus, + Metadata *imageMetadata, + const AgcChannelTotalExposures &channelTotalExposures) { frameCount_++; /* @@ -512,12 +514,17 @@ void AgcChannel::process(StatisticsPtr &stats, DeviceStatus const &deviceStatus, computeTargetExposure(gain); /* The results have to be filtered so as not to change too rapidly. */ filterExposure(); + /* + * We may be asked to limit the exposure using other channels. If another channel + * determines our upper bound we may want to know this later. + */ + bool channelBound = applyChannelConstraints(channelTotalExposures); /* * Some of the exposure has to be applied as digital gain, so work out - * what that is. This function also tells us whether it's decided to - * "desaturate" the image more quickly. + * what that is. It also tells us whether it's trying to desaturate the image + * more quickly, which can only happen when another channel is not limiting us. */ - bool desaturate = applyDigitalGain(gain, targetY); + bool desaturate = applyDigitalGain(gain, targetY, channelBound); /* * The last thing is to divide up the exposure value into a shutter time * and analogue gain, according to the current exposure mode. @@ -794,7 +801,44 @@ void AgcChannel::computeTargetExposure(double gain) LOG(RPiAgc, Debug) << "Target totalExposure " << target_.totalExposure; } -bool AgcChannel::applyDigitalGain(double gain, double targetY) +bool AgcChannel::applyChannelConstraints(const AgcChannelTotalExposures &channelTotalExposures) +{ + bool channelBound = false; + LOG(RPiAgc, Debug) + << "Total exposure before channel constraints " << filtered_.totalExposure; + + for (const auto &constraint : config_.channelConstraints) { + LOG(RPiAgc, Debug) + << "Check constraint: channel " << constraint.channel << " bound " + << (constraint.bound == AgcChannelConstraint::Bound::UPPER ? "UPPER" : "LOWER") + << " factor " << constraint.factor; + if (constraint.channel >= channelTotalExposures.size() || + !channelTotalExposures[constraint.channel]) { + LOG(RPiAgc, Debug) << "no such channel or no exposure available- skipped"; + continue; + } + + libcamera::utils::Duration limitExposure = + channelTotalExposures[constraint.channel] * constraint.factor; + LOG(RPiAgc, Debug) << "Limit exposure " << limitExposure; + if ((constraint.bound == AgcChannelConstraint::Bound::UPPER && + filtered_.totalExposure > limitExposure) || + (constraint.bound == AgcChannelConstraint::Bound::LOWER && + filtered_.totalExposure < limitExposure)) { + filtered_.totalExposure = limitExposure; + LOG(RPiAgc, Debug) << "Constraint applies"; + channelBound = true; + } else + LOG(RPiAgc, Debug) << "Constraint does not apply"; + } + + LOG(RPiAgc, Debug) + << "Total exposure after channel constraints " << filtered_.totalExposure; + + return channelBound; +} + +bool AgcChannel::applyDigitalGain(double gain, double targetY, bool channelBound) { double minColourGain = std::min({ awb_.gainR, awb_.gainG, awb_.gainB, 1.0 }); ASSERT(minColourGain != 0.0); @@ -814,8 +858,8 @@ bool AgcChannel::applyDigitalGain(double gain, double targetY) * quickly (and we then approach the correct value more quickly from * below). */ - bool desaturate = targetY > config_.fastReduceThreshold && - gain < sqrt(targetY); + bool desaturate = !channelBound && + targetY > config_.fastReduceThreshold && gain < sqrt(targetY); if (desaturate) dg /= config_.fastReduceThreshold; LOG(RPiAgc, Debug) << "Digital gain " << dg << " desaturate? " << desaturate; diff --git a/src/ipa/rpi/controller/rpi/agc_channel.h b/src/ipa/rpi/controller/rpi/agc_channel.h index ceaab12f..ae826fa8 100644 --- a/src/ipa/rpi/controller/rpi/agc_channel.h +++ b/src/ipa/rpi/controller/rpi/agc_channel.h @@ -21,6 +21,8 @@ namespace RPiController { +using AgcChannelTotalExposures = std::vector; + struct AgcMeteringMode { std::vector weights; int read(const libcamera::YamlObject ¶ms); @@ -95,7 +97,8 @@ public: void disableAuto(); void switchMode(CameraMode const &cameraMode, Metadata *metadata); void prepare(Metadata *imageMetadata); - void process(StatisticsPtr &stats, DeviceStatus const &deviceStatus, Metadata *imageMetadata); + void process(StatisticsPtr &stats, DeviceStatus const &deviceStatus, Metadata *imageMetadata, + const AgcChannelTotalExposures &channelTotalExposures); private: bool updateLockStatus(DeviceStatus const &deviceStatus); @@ -107,7 +110,8 @@ private: double &gain, double &targetY); void computeTargetExposure(double gain); void filterExposure(); - bool applyDigitalGain(double gain, double targetY); + bool applyChannelConstraints(const AgcChannelTotalExposures &channelTotalExposures); + bool applyDigitalGain(double gain, double targetY, bool channelBound); void divideUpExposure(); void writeAndFinish(Metadata *imageMetadata, bool desaturate); libcamera::utils::Duration limitShutter(libcamera::utils::Duration shutter);