From patchwork Fri Aug 8 14:12:39 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24072 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 B86ADBDCC1 for ; Fri, 8 Aug 2025 14:13:48 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 70DBF69221; Fri, 8 Aug 2025 16:13:48 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="OvoigyfA"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id B7C0C6084D for ; Fri, 8 Aug 2025 16:13:46 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id C4D04208E; Fri, 8 Aug 2025 16:12:56 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662376; bh=O3YCOdIp/FITALSPLxXJFxV5XEz9RPzmDENFFqoXdSU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=OvoigyfAv6Tbs3kudpFnM5T+Akb5hEZdoIH001oBqN1xEv7jg0rnaZgNYF0OsRYtf 2vnPi3rvefovZz6LelLwOzZJ6mw4wPRiiH/wNCuDbdPftXlRmzzxPbSC6+mPLWnOgr xU+xXTDzVmQMyrLw95Cpzv/fiPwgUdqiteTcUVhM= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug Subject: [PATCH v2 01/16] ipa: rkisp1: Add basic compression algorithm Date: Fri, 8 Aug 2025 16:12:39 +0200 Message-ID: <20250808141315.413839-2-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" The i.MX8 M Plus has a compression curve inside the compand block. This curve is necessary to process HDR stitched data and is useful for other aspects like applying a digital gain to the incoming sensor data. Add a basic algorithm for the compression curve. This algorithm has a hardcoded input width of 20bit and output width of 12bit which matches the imx8mp pipeline. Only a static gain is supported in this version. Signed-off-by: Stefan Klug --- src/ipa/rkisp1/algorithms/compress.cpp | 100 +++++++++++++++++++++++++ src/ipa/rkisp1/algorithms/compress.h | 33 ++++++++ src/ipa/rkisp1/algorithms/meson.build | 1 + src/ipa/rkisp1/ipa_context.h | 9 +++ 4 files changed, 143 insertions(+) create mode 100644 src/ipa/rkisp1/algorithms/compress.cpp create mode 100644 src/ipa/rkisp1/algorithms/compress.h diff --git a/src/ipa/rkisp1/algorithms/compress.cpp b/src/ipa/rkisp1/algorithms/compress.cpp new file mode 100644 index 000000000000..b2fad02404d6 --- /dev/null +++ b/src/ipa/rkisp1/algorithms/compress.cpp @@ -0,0 +1,100 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2025, Ideas On Board + * + * RkISP1 Compression curve + */ +#include "compress.h" + +#include + +#include +#include + +#include "libcamera/internal/yaml_parser.h" + +#include "linux/rkisp1-config.h" + +/** + * \file compress.h + */ + +namespace libcamera { + +namespace ipa::rkisp1::algorithms { + +/** + * \class Compress + * \brief RkISP1 Compress curve + * + * This algorithm implements support for the compressions curve in the compand + * block available in the i.MX8 M Plus + * + * In its current version it only supports a static gain. This is useful for + * the agc algorithm to compensate for exposure/gain quantization effects. + * + * This algorithm doesn't have any configuration options. It needs to be + * configured per frame by other algorithms. + * + * Other algorithms can check activeState.compress.supported to see if + * compression is available. If it is available they can configure it per frame + * using frameContext.compress.enable and frameContext.compress.gain. + */ + +LOG_DEFINE_CATEGORY(RkISP1Compress) + +constexpr static int kRkISP1CompressInBits = 20; +constexpr static int kRkISP1CompressOutBits = 12; + +/** + * \copydoc libcamera::ipa::Algorithm::configure + */ +int Compress::configure(IPAContext &context, + [[maybe_unused]] const IPACameraSensorInfo &configInfo) +{ + if (context.configuration.paramFormat != V4L2_META_FMT_RK_ISP1_EXT_PARAMS || + !context.hw->compand) + LOG(RkISP1Compress, Warning) + << "Compression is not supported by the hardware or kernel."; + + context.activeState.compress.supported = true; + return 0; +} + +/** + * \copydoc libcamera::ipa::Algorithm::prepare + */ +void Compress::prepare([[maybe_unused]] IPAContext &context, + [[maybe_unused]] const uint32_t frame, + IPAFrameContext &frameContext, + RkISP1Params *params) +{ + auto comp = params->block(); + comp.setEnabled(frameContext.compress.enable); + + if (!frameContext.compress.enable) + return; + + int xmax = (1 << kRkISP1CompressInBits); + int ymax = (1 << kRkISP1CompressOutBits); + int inLogStep = std::log2(xmax / 64); + + for (unsigned int i = 0; i < RKISP1_CIF_ISP_COMPAND_NUM_POINTS; i++) { + double x = (i + 1) * (1.0 / RKISP1_CIF_ISP_COMPAND_NUM_POINTS); + double y = x * frameContext.compress.gain; + + comp->px[i] = inLogStep; + comp->x[i] = std::min(x * xmax, xmax - 1); + comp->y[i] = std::min(y * ymax, ymax - 1); + } + + LOG(RkISP1Compress, Debug) << "Compression: " << kRkISP1CompressInBits + << " bits to " << kRkISP1CompressOutBits + << " bits gain: " << frameContext.compress.gain; +} + +REGISTER_IPA_ALGORITHM(Compress, "Compress") + +} /* namespace ipa::rkisp1::algorithms */ + +} /* namespace libcamera */ diff --git a/src/ipa/rkisp1/algorithms/compress.h b/src/ipa/rkisp1/algorithms/compress.h new file mode 100644 index 000000000000..3006508b2b32 --- /dev/null +++ b/src/ipa/rkisp1/algorithms/compress.h @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2024, Ideas On Board + * + * RkISP1 Gamma out control + */ + +#pragma once + +#include "algorithm.h" + +namespace libcamera { + +namespace ipa::rkisp1::algorithms { + +class Compress : public Algorithm +{ +public: + Compress() = default; + ~Compress() = default; + + int configure(IPAContext &context, + const IPACameraSensorInfo &configInfo) override; + void prepare(IPAContext &context, const uint32_t frame, + IPAFrameContext &frameContext, + RkISP1Params *params) override; + +private: + float defaultGamma_; +}; + +} /* namespace ipa::rkisp1::algorithms */ +} /* namespace libcamera */ diff --git a/src/ipa/rkisp1/algorithms/meson.build b/src/ipa/rkisp1/algorithms/meson.build index c66b0b70b82f..2e42a80cf99d 100644 --- a/src/ipa/rkisp1/algorithms/meson.build +++ b/src/ipa/rkisp1/algorithms/meson.build @@ -5,6 +5,7 @@ rkisp1_ipa_algorithms = files([ 'awb.cpp', 'blc.cpp', 'ccm.cpp', + 'compress.cpp', 'cproc.cpp', 'dpcc.cpp', 'dpf.cpp', diff --git a/src/ipa/rkisp1/ipa_context.h b/src/ipa/rkisp1/ipa_context.h index 7ccc7b501aff..37a74215ce19 100644 --- a/src/ipa/rkisp1/ipa_context.h +++ b/src/ipa/rkisp1/ipa_context.h @@ -106,6 +106,10 @@ struct IPAActiveState { Matrix automatic; } ccm; + struct { + bool supported; + } compress; + struct { int8_t brightness; uint8_t contrast; @@ -158,6 +162,11 @@ struct IPAFrameContext : public FrameContext { bool update; } cproc; + struct { + bool enable; + double gain; + } compress; + struct { bool denoise; bool update; From patchwork Fri Aug 8 14:12:40 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24073 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 4AB62BDCC1 for ; Fri, 8 Aug 2025 14:13:51 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id F13B06921E; Fri, 8 Aug 2025 16:13:50 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="NVhPF3tZ"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 389D16921C for ; Fri, 8 Aug 2025 16:13:49 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id 4FEEB185B; Fri, 8 Aug 2025 16:12:59 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662379; bh=JgKttNo9fEG/16f2qfps5qeDX6g6D/VKfdQQEJwSkFo=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=NVhPF3tZlp4khi2cgRgW/8aoIL5RR3KiP6DO/xq9CmSva0sQjB25sLS5EQRVB0sy2 GTClWEw7D6xlvTb58lMWj0E+9vr2k1q3djPh1x8UbCl5qWt92gljY3MTaQHGCTXrbN EBEC7HMBfXK9SnqyGu4SBoNVTVmPc9cJlQRpZuIQ= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug Subject: [PATCH v2 02/16] tuning: rksip1: Add a static Compress entry Date: Fri, 8 Aug 2025 16:12:40 +0200 Message-ID: <20250808141315.413839-3-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" Add a static Compress entry that gets added by default. Signed-off-by: Stefan Klug Reviewed-by: Daniel Scally --- utils/tuning/rkisp1.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/utils/tuning/rkisp1.py b/utils/tuning/rkisp1.py index 207b717a029c..179d920c05df 100755 --- a/utils/tuning/rkisp1.py +++ b/utils/tuning/rkisp1.py @@ -27,6 +27,7 @@ awb = AWBRkISP1(debug=[lt.Debug.Plot]) blc = StaticModule('BlackLevelCorrection') ccm = CCMRkISP1(debug=[lt.Debug.Plot]) color_processing = StaticModule('ColorProcessing') +compress = StaticModule('Compress') filter = StaticModule('Filter') gamma_out = StaticModule('GammaOutCorrection', {'gamma': 2.2}) lsc = LSCRkISP1(debug=[lt.Debug.Plot], @@ -49,13 +50,14 @@ lsc = LSCRkISP1(debug=[lt.Debug.Plot], lux = LuxRkISP1(debug=[lt.Debug.Plot]) tuner = lt.Tuner('RkISP1') -tuner.add([agc, awb, blc, ccm, color_processing, filter, gamma_out, lsc, lux]) +tuner.add([agc, awb, blc, ccm, color_processing, filter, gamma_out, lsc, lux, compress]) tuner.set_input_parser(YamlParser()) tuner.set_output_formatter(YamlOutput()) # Bayesian AWB uses the lux value, so insert the lux algorithm before AWB. +# Compress is parameterized by others, so add it at the end. tuner.set_output_order([agc, lux, awb, blc, ccm, color_processing, - filter, gamma_out, lsc]) + filter, gamma_out, lsc, compress]) if __name__ == '__main__': sys.exit(tuner.run(sys.argv)) From patchwork Fri Aug 8 14:12:41 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24074 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 C1968BDCC1 for ; Fri, 8 Aug 2025 14:13:53 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 7D1F869221; Fri, 8 Aug 2025 16:13:53 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="wfl++2kv"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 176CF6921C for ; Fri, 8 Aug 2025 16:13:52 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id 314CF42D0; Fri, 8 Aug 2025 16:13:02 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662382; bh=iT03ipL+lnvUK0FZKqO3DvtO5ANT+3w79AyDtnbnQEs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=wfl++2kvSplL8Strj2CPkAC9VEsQxlkZQITuhqw7sCFPQY/yZZiCtz5W2uHeo4h/g OYIOC9geLEiteiYKvg4/NPJE6D7fv40Ci4hOwyDn8hWBWY61cJuDyK0o6C8KyEB4Px gH5gGgPD57q8jVbics3sMEiJiGm1V/euBTGbXoz8= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug Subject: [PATCH v2 03/16] libipa: camera_sensor_helper: Add quantizeGain() function Date: Fri, 8 Aug 2025 16:12:41 +0200 Message-ID: <20250808141315.413839-4-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" Add a small utility function that calculates the quantized gain that gets applied by a sensor when the gain code is set to gainCode(gain). This is needed by algorithms to calculate a digital correction gain that gets applied to mitigate the error introduce by quantization. Signed-off-by: Stefan Klug Reviewed-by: Daniel Scally --- src/ipa/libipa/camera_sensor_helper.cpp | 23 +++++++++++++++++++++++ src/ipa/libipa/camera_sensor_helper.h | 1 + 2 files changed, 24 insertions(+) diff --git a/src/ipa/libipa/camera_sensor_helper.cpp b/src/ipa/libipa/camera_sensor_helper.cpp index dcd69d9f2bbb..0a7b66cd003a 100644 --- a/src/ipa/libipa/camera_sensor_helper.cpp +++ b/src/ipa/libipa/camera_sensor_helper.cpp @@ -131,6 +131,29 @@ double CameraSensorHelper::gain(uint32_t gainCode) const } } +/** + * \brief Quantize the given gain value + * \param[in] _gain The real gain + * \param[out] quantizationGain The gain that is lost due to quantization + * + * This function returns the actual gain that get's applied when the sensors + * gain is set to gainCode(gain). + * + * It shall be guaranteed that gainCode(gain) == gainCode(quantizeGain(gain)). + * + * If \a quantizationGain is provided it is filled with the gain that is lost + * due to quantization. + * + * \return The quantized real gain + */ +double CameraSensorHelper::quantizeGain(double _gain, double *quantizationGain) const +{ + double g = gain(gainCode(_gain)); + if (quantizationGain) + *quantizationGain = _gain / g; + return g; +} + /** * \struct CameraSensorHelper::AnalogueGainLinear * \brief Analogue gain constants for the linear gain model diff --git a/src/ipa/libipa/camera_sensor_helper.h b/src/ipa/libipa/camera_sensor_helper.h index a9300a64f1e7..42bdb3c5550f 100644 --- a/src/ipa/libipa/camera_sensor_helper.h +++ b/src/ipa/libipa/camera_sensor_helper.h @@ -29,6 +29,7 @@ public: std::optional blackLevel() const { return blackLevel_; } virtual uint32_t gainCode(double gain) const; virtual double gain(uint32_t gainCode) const; + virtual double quantizeGain(double gain, double *quantizationGain) const; protected: struct AnalogueGainLinear { From patchwork Fri Aug 8 14:12:42 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24075 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 5A110BDCC1 for ; Fri, 8 Aug 2025 14:13:56 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 081EE69227; Fri, 8 Aug 2025 16:13:56 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="DDsUnPmx"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [IPv6:2001:4b98:dc2:55:216:3eff:fef7:d647]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id E11C66921A for ; Fri, 8 Aug 2025 16:13:54 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id F281F42D0; Fri, 8 Aug 2025 16:13:04 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662385; bh=rcAPl7FLQ/9uSo2Qf9fn+WlLmij6pbv6z6EzGHNyjCY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DDsUnPmx678zQNaBPJqPmZ59B01US8Br+ssY+m4vyhgxk2d5zoG0O1vFQZw8GJvQv nkJ0XtdJWtt+OZVpoJI4R8qqsJwsA6yqvJF4qslb9Gr2B8IGXoyFX84AmRm3Lr5o+2 lGgEi9yisad4MMYU3Gep3ANhlCU0ctazj+0k6zW4= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug Subject: [PATCH v2 04/16] libipa: exposure_mode_helper: Take exposure/gain quantization into account Date: Fri, 8 Aug 2025 16:12:42 +0200 Message-ID: <20250808141315.413839-5-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" In ExposureModeHelper::splitExposure() the quantization of exposure time and gain is not taken into account. This can lead to visible flicker when the quantization steps are too big. As a preparation to fixing that, add a function to set the sensor line length and the current sensor mode helper and extend the clampXXX functions to return the quantization error. By default the exposure time quantization is assumed to be 1us and gain is assumed to not be quantized at all. This patch doesn't introduce any functional changes. Signed-off-by: Stefan Klug Reviewed-by: Kieran Bingham Reviewed-by: Daniel Scally --- src/ipa/libipa/exposure_mode_helper.cpp | 49 ++++++++++++++++++++----- src/ipa/libipa/exposure_mode_helper.h | 10 ++++- 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/src/ipa/libipa/exposure_mode_helper.cpp b/src/ipa/libipa/exposure_mode_helper.cpp index 0c1e99e31a47..d0a61908c966 100644 --- a/src/ipa/libipa/exposure_mode_helper.cpp +++ b/src/ipa/libipa/exposure_mode_helper.cpp @@ -70,18 +70,37 @@ namespace ipa { * the runtime limits set through setLimits() instead. */ ExposureModeHelper::ExposureModeHelper(const Span> stages) + : lineLength_(1us), minExposureTime_(0us), maxExposureTime_(0us), + minGain_(0), maxGain_(0), sensorHelper_(nullptr) { - minExposureTime_ = 0us; - maxExposureTime_ = 0us; - minGain_ = 0; - maxGain_ = 0; - for (const auto &[s, g] : stages) { exposureTimes_.push_back(s); gains_.push_back(g); } } +/** + * \brief Configure sensor details + * \param[in] lineLength The current line length of the sensor + * \param[in] sensorHelper The sensor helper + * + * This function sets the line length and sensor helper. These are used in + * splitExposure() to take the quantization of the exposure and gain into + * account. + * + * When this is not called, is is assumed that exposure is in micro second + * granularity and gain has no quantization at all. + * + * The caller has to ensure that sensorHelper is valid for the lifetime of + * ExposureModeHelper or the next call to configure. + */ +void ExposureModeHelper::configure(utils::Duration lineLength, + const CameraSensorHelper *sensorHelper) +{ + lineLength_ = lineLength; + sensorHelper_ = sensorHelper; +} + /** * \brief Set the exposure time and gain limits * \param[in] minExposureTime The minimum exposure time supported @@ -108,14 +127,26 @@ void ExposureModeHelper::setLimits(utils::Duration minExposureTime, maxGain_ = maxGain; } -utils::Duration ExposureModeHelper::clampExposureTime(utils::Duration exposureTime) const +utils::Duration ExposureModeHelper::clampExposureTime(utils::Duration exposureTime, + double *quantizationGain) const { - return std::clamp(exposureTime, minExposureTime_, maxExposureTime_); + utils::Duration clamped; + utils::Duration exp; + + clamped = std::clamp(exposureTime, minExposureTime_, maxExposureTime_); + exp = static_cast(clamped / lineLength_) * lineLength_; + if (quantizationGain) + *quantizationGain = clamped / exp; + + return exp; } -double ExposureModeHelper::clampGain(double gain) const +double ExposureModeHelper::clampGain(double gain, double *quantizationGain) const { - return std::clamp(gain, minGain_, maxGain_); + double clamped = std::clamp(gain, minGain_, maxGain_); + if (!sensorHelper_) + return clamped; + return sensorHelper_->quantizeGain(clamped, quantizationGain); } /** diff --git a/src/ipa/libipa/exposure_mode_helper.h b/src/ipa/libipa/exposure_mode_helper.h index c5be1b6703a8..8701fae9a26e 100644 --- a/src/ipa/libipa/exposure_mode_helper.h +++ b/src/ipa/libipa/exposure_mode_helper.h @@ -14,6 +14,8 @@ #include #include +#include "camera_sensor_helper.h" + namespace libcamera { namespace ipa { @@ -24,6 +26,7 @@ public: ExposureModeHelper(const Span> stages); ~ExposureModeHelper() = default; + void configure(utils::Duration lineLength, const CameraSensorHelper *sensorHelper); void setLimits(utils::Duration minExposureTime, utils::Duration maxExposureTime, double minGain, double maxGain); @@ -36,16 +39,19 @@ public: double maxGain() const { return maxGain_; } private: - utils::Duration clampExposureTime(utils::Duration exposureTime) const; - double clampGain(double gain) const; + utils::Duration clampExposureTime(utils::Duration exposureTime, + double *quantizationGain = nullptr) const; + double clampGain(double gain, double *quantizationGain = nullptr) const; std::vector exposureTimes_; std::vector gains_; + utils::Duration lineLength_; utils::Duration minExposureTime_; utils::Duration maxExposureTime_; double minGain_; double maxGain_; + const CameraSensorHelper *sensorHelper_; }; } /* namespace ipa */ From patchwork Fri Aug 8 14:12:43 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24076 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 E2D91BDCC1 for ; Fri, 8 Aug 2025 14:13:58 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 9C67A6922A; Fri, 8 Aug 2025 16:13:58 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="g2aKZd+0"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id BAEBC6921C for ; Fri, 8 Aug 2025 16:13:57 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id CCC7342D0; Fri, 8 Aug 2025 16:13:07 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662387; bh=jaSaTylteAf9BebnDZq8p7FGkbu3Unqpfr99GXpMpc8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=g2aKZd+0oqrqcPH1Mwum3Z3uIZIi1neI2/zw28mRxe9WVXAbbvsXc2bdoF48CZ7nn TklueD9Qxt8oGK3080WtwbIpsVE25GoBeohs9Nayq7yw87wf0mmnsLzjpTyzjlK0zy ZtfBUIlaUenY72NMDjgENQYC4/b5xX9E8GRXhFK4= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug Subject: [PATCH v2 05/16] libipa: exposure_mode_helper: Remove double calculation of lastStageGain Date: Fri, 8 Aug 2025 16:12:43 +0200 Message-ID: <20250808141315.413839-6-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" lastStageGain gets recalculated unconditionally even though it is the stageGain of the last stage. Refactor for increased simplicity and efficiency. Signed-off-by: Stefan Klug Reviewed-by: Kieran Bingham Reviewed-by: Daniel Scally --- src/ipa/libipa/exposure_mode_helper.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ipa/libipa/exposure_mode_helper.cpp b/src/ipa/libipa/exposure_mode_helper.cpp index d0a61908c966..3c758851679f 100644 --- a/src/ipa/libipa/exposure_mode_helper.cpp +++ b/src/ipa/libipa/exposure_mode_helper.cpp @@ -198,10 +198,10 @@ ExposureModeHelper::splitExposure(utils::Duration exposure) const utils::Duration exposureTime; double stageGain = 1.0; + double lastStageGain = 1.0; double gain; for (unsigned int stage = 0; stage < gains_.size(); stage++) { - double lastStageGain = stage == 0 ? 1.0 : clampGain(gains_[stage - 1]); utils::Duration stageExposureTime = clampExposureTime(exposureTimes_[stage]); stageGain = clampGain(gains_[stage]); @@ -228,6 +228,8 @@ ExposureModeHelper::splitExposure(utils::Duration exposure) const return { exposureTime, gain, exposure / (exposureTime * gain) }; } + + lastStageGain = stageGain; } /* From patchwork Fri Aug 8 14:12:44 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24077 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 75ACDBDCC1 for ; Fri, 8 Aug 2025 14:14:02 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 2FFDD69227; Fri, 8 Aug 2025 16:14:02 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="I0gAJqlD"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [IPv6:2001:4b98:dc2:55:216:3eff:fef7:d647]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id AE91C6921C for ; Fri, 8 Aug 2025 16:14:00 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id C4C61208E; Fri, 8 Aug 2025 16:13:10 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662390; bh=CZ2QmmW4YG3+wEmQDrVYfaBbRzCZtHwuimMvhTR7CMA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=I0gAJqlDLLttRK7T9lVEd1j6lFYqJx0HXQh1u80TTIslcENLUpGIhBqTTgxErQW4k sKC7Uv5q2JVXfz6ZW/ctMhyl391ufUBIfiqWn0c5FyWmFsUGawFomiVlgdnZtVPx3q fxTtx79ZSqvHMa9FZc2z3x+sjRWjGMiJSbRi7xB0= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug Subject: [PATCH v2 06/16] libipa: exposure_mode_helper: Remove unnecessary clamp calls Date: Fri, 8 Aug 2025 16:12:44 +0200 Message-ID: <20250808141315.413839-7-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" Except for the first iteration of the loop and in the case of an empty gains_ vector, the values were run through clamp two times which is unnecessary. Remove that by clamping the initial value. Signed-off-by: Stefan Klug Reviewed-by: Daniel Scally --- src/ipa/libipa/exposure_mode_helper.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/ipa/libipa/exposure_mode_helper.cpp b/src/ipa/libipa/exposure_mode_helper.cpp index 3c758851679f..7d470ebe487c 100644 --- a/src/ipa/libipa/exposure_mode_helper.cpp +++ b/src/ipa/libipa/exposure_mode_helper.cpp @@ -197,8 +197,8 @@ ExposureModeHelper::splitExposure(utils::Duration exposure) const return { minExposureTime_, minGain_, exposure / (minExposureTime_ * minGain_) }; utils::Duration exposureTime; - double stageGain = 1.0; - double lastStageGain = 1.0; + double stageGain = clampGain(1.0); + double lastStageGain = stageGain; double gain; for (unsigned int stage = 0; stage < gains_.size(); stage++) { @@ -215,7 +215,7 @@ ExposureModeHelper::splitExposure(utils::Duration exposure) const /* Clamp the gain to lastStageGain and regulate exposureTime. */ if (stageExposureTime * lastStageGain >= exposure) { - exposureTime = clampExposureTime(exposure / clampGain(lastStageGain)); + exposureTime = clampExposureTime(exposure / lastStageGain); gain = clampGain(exposure / exposureTime); return { exposureTime, gain, exposure / (exposureTime * gain) }; @@ -223,7 +223,7 @@ ExposureModeHelper::splitExposure(utils::Duration exposure) const /* Clamp the exposureTime to stageExposureTime and regulate gain. */ if (stageExposureTime * stageGain >= exposure) { - exposureTime = clampExposureTime(stageExposureTime); + exposureTime = stageExposureTime; gain = clampGain(exposure / exposureTime); return { exposureTime, gain, exposure / (exposureTime * gain) }; @@ -239,7 +239,7 @@ ExposureModeHelper::splitExposure(utils::Duration exposure) const * stages to use then the default stageGain of 1.0 is used so that * exposure time is maxed before gain is touched at all. */ - exposureTime = clampExposureTime(exposure / clampGain(stageGain)); + exposureTime = clampExposureTime(exposure / stageGain); gain = clampGain(exposure / exposureTime); return { exposureTime, gain, exposure / (exposureTime * gain) }; From patchwork Fri Aug 8 14:12:45 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24078 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 40A53BDCC1 for ; Fri, 8 Aug 2025 14:14:05 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id EF90669227; Fri, 8 Aug 2025 16:14:04 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="XrG2rMgV"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 7467269221 for ; Fri, 8 Aug 2025 16:14:03 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id 822B3208E; Fri, 8 Aug 2025 16:13:13 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662393; bh=kgAL0wYC4ybpEhOj80FIQaZ838qoD/KbaGZkQmdfubY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=XrG2rMgVaLo2jx/pNVVnFmCHhe7otZ+jq6jcWJufIA79wIJa07X78b6Bg5C2SeUJS Ku3OIHJpVHijv3UUvP8wqv/nB3BpUja7pInVOwJKN2saUTv0Q/7jcOJ14b1KGKb1WE t5GmrZNKG32zAE7ZunCR0/QEkO5sgkf5PAmCWS/M= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug Subject: [PATCH v2 07/16] libipa: agc_mean_luminance: Configure the exposure mode helpers Date: Fri, 8 Aug 2025 16:12:45 +0200 Message-ID: <20250808141315.413839-8-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" Add a function to configure the exposure mode helpers with the line length and sensor helper to take quantization effects into account. Signed-off-by: Stefan Klug Reviewed-by: Daniel Scally --- src/ipa/libipa/agc_mean_luminance.cpp | 15 +++++++++++++++ src/ipa/libipa/agc_mean_luminance.h | 1 + 2 files changed, 16 insertions(+) diff --git a/src/ipa/libipa/agc_mean_luminance.cpp b/src/ipa/libipa/agc_mean_luminance.cpp index ff96a381ffce..58c4dfc9add2 100644 --- a/src/ipa/libipa/agc_mean_luminance.cpp +++ b/src/ipa/libipa/agc_mean_luminance.cpp @@ -311,6 +311,21 @@ int AgcMeanLuminance::parseExposureModes(const YamlObject &tuningData) return 0; } +/** + * \brief Configure the exposure mode helpers + * \param[in] lineLength The sensor line length + * \param[in] sensorHelper The sensor helper + * + * This function configures the exposure mode helpers so they can correctly + * take quantization effects into account. + */ +void AgcMeanLuminance::configure(utils::Duration lineLength, + const CameraSensorHelper *sensorHelper) +{ + for (auto &[id, helper] : exposureModeHelpers_) + helper->configure(lineLength, sensorHelper); +} + /** * \brief Parse tuning data for AeConstraintMode and AeExposureMode controls * \param[in] tuningData the YamlObject representing the tuning data diff --git a/src/ipa/libipa/agc_mean_luminance.h b/src/ipa/libipa/agc_mean_luminance.h index cad7ef845487..a7c7e006af42 100644 --- a/src/ipa/libipa/agc_mean_luminance.h +++ b/src/ipa/libipa/agc_mean_luminance.h @@ -42,6 +42,7 @@ public: double yTarget; }; + void configure(utils::Duration lineLength, const CameraSensorHelper *sensorHelper); int parseTuningData(const YamlObject &tuningData); void setExposureCompensation(double gain) From patchwork Fri Aug 8 14:12:46 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24079 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 B6CAFBDCC1 for ; Fri, 8 Aug 2025 14:14:08 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 7174769221; Fri, 8 Aug 2025 16:14:08 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="i4uRovtf"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id D779F6921E for ; Fri, 8 Aug 2025 16:14:06 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id EE3C8208E; Fri, 8 Aug 2025 16:13:16 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662397; bh=YWAo715sOGCFW3ImcQFI4ZffXYRkbNiSP01cyq3p3hg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=i4uRovtf6oOfSqocOpGCYnIh1VZQhSbg86ePdysKJgmcWOidIKr45LeY8I2IePf7X uhOLcjrXdApcdMqIr+8JIv9JD+oiC3GdjoFuqLSkIiiVzoa5bfsd0loz7QnDOkuE/H aFoEHNfOOqOPgRmK5vtdu/UEI/KwL7z6SyGUQwro= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug Subject: [PATCH v2 08/16] libipa: exposure_mode_helper: Calculate quantization gain in splitExposure() Date: Fri, 8 Aug 2025 16:12:46 +0200 Message-ID: <20250808141315.413839-9-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" Calculate the error introduced by quantization as "quantization gain" and return it separately from splitExposure(). It is not included in the digital gain, to not silently ignore the limits imposed by the AGC configuration. Signed-off-by: Stefan Klug --- src/ipa/ipu3/algorithms/agc.cpp | 4 +-- src/ipa/libipa/agc_mean_luminance.cpp | 7 ++-- src/ipa/libipa/agc_mean_luminance.h | 2 +- src/ipa/libipa/exposure_mode_helper.cpp | 46 +++++++++++++++++-------- src/ipa/libipa/exposure_mode_helper.h | 2 +- src/ipa/rkisp1/algorithms/agc.cpp | 9 ++--- 6 files changed, 44 insertions(+), 26 deletions(-) diff --git a/src/ipa/ipu3/algorithms/agc.cpp b/src/ipa/ipu3/algorithms/agc.cpp index 39d0aebb0838..da045640d569 100644 --- a/src/ipa/ipu3/algorithms/agc.cpp +++ b/src/ipa/ipu3/algorithms/agc.cpp @@ -222,8 +222,8 @@ void Agc::process(IPAContext &context, [[maybe_unused]] const uint32_t frame, utils::Duration effectiveExposureValue = exposureTime * analogueGain; utils::Duration newExposureTime; - double aGain, dGain; - std::tie(newExposureTime, aGain, dGain) = + double aGain, qGain, dGain; + std::tie(newExposureTime, aGain, qGain, dGain) = calculateNewEv(context.activeState.agc.constraintMode, context.activeState.agc.exposureMode, hist, effectiveExposureValue); diff --git a/src/ipa/libipa/agc_mean_luminance.cpp b/src/ipa/libipa/agc_mean_luminance.cpp index 58c4dfc9add2..695453e7ceea 100644 --- a/src/ipa/libipa/agc_mean_luminance.cpp +++ b/src/ipa/libipa/agc_mean_luminance.cpp @@ -566,11 +566,12 @@ utils::Duration AgcMeanLuminance::filterExposure(utils::Duration exposureValue) * * Calculate a new exposure value to try to obtain the target. The calculated * exposure value is filtered to prevent rapid changes from frame to frame, and - * divided into exposure time, analogue and digital gain. + * divided into exposure time, analogue, quantization and digital gain. * - * \return Tuple of exposure time, analogue gain, and digital gain + * \return Tuple of exposure time, analogue gain, quantization gain and digital + * gain */ -std::tuple +std::tuple AgcMeanLuminance::calculateNewEv(uint32_t constraintModeIndex, uint32_t exposureModeIndex, const Histogram &yHist, diff --git a/src/ipa/libipa/agc_mean_luminance.h b/src/ipa/libipa/agc_mean_luminance.h index a7c7e006af42..741ccf986625 100644 --- a/src/ipa/libipa/agc_mean_luminance.h +++ b/src/ipa/libipa/agc_mean_luminance.h @@ -68,7 +68,7 @@ public: return controls_; } - std::tuple + std::tuple calculateNewEv(uint32_t constraintModeIndex, uint32_t exposureModeIndex, const Histogram &yHist, utils::Duration effectiveExposureValue); diff --git a/src/ipa/libipa/exposure_mode_helper.cpp b/src/ipa/libipa/exposure_mode_helper.cpp index 7d470ebe487c..79b8e6758faf 100644 --- a/src/ipa/libipa/exposure_mode_helper.cpp +++ b/src/ipa/libipa/exposure_mode_helper.cpp @@ -178,14 +178,23 @@ double ExposureModeHelper::clampGain(double gain, double *quantizationGain) cons * required exposure, the helper falls-back to simply maximising the exposure * time first, followed by analogue gain, followed by digital gain. * - * \return Tuple of exposure time, analogue gain, and digital gain + * During the calculations the gain missed due to quantization is recorded and + * returned as quantization gain. The quantization gain is not included in the + * digital gain. So to exactly apply the given exposure, both quantization gain + * and digital gain must be applied. + * + * \return Tuple of exposure time, analogue gain, quantization gain and digital + * gain */ -std::tuple +std::tuple ExposureModeHelper::splitExposure(utils::Duration exposure) const { ASSERT(maxExposureTime_); ASSERT(maxGain_); + utils::Duration exposureTime; + double gain; + double quantGain; bool gainFixed = minGain_ == maxGain_; bool exposureTimeFixed = minExposureTime_ == maxExposureTime_; @@ -193,16 +202,20 @@ ExposureModeHelper::splitExposure(utils::Duration exposure) const * There's no point entering the loop if we cannot change either gain * nor exposure time anyway. */ - if (exposureTimeFixed && gainFixed) - return { minExposureTime_, minGain_, exposure / (minExposureTime_ * minGain_) }; + if (exposureTimeFixed && gainFixed) { + exposureTime = clampExposureTime(minExposureTime_, &quantGain); + gain = clampGain(minGain_ * quantGain, &quantGain); + + return { exposureTime, gain, quantGain, + exposure / (minExposureTime_ * minGain_ * quantGain) }; + } - utils::Duration exposureTime; double stageGain = clampGain(1.0); double lastStageGain = stageGain; - double gain; for (unsigned int stage = 0; stage < gains_.size(); stage++) { - utils::Duration stageExposureTime = clampExposureTime(exposureTimes_[stage]); + utils::Duration stageExposureTime = clampExposureTime(exposureTimes_[stage], + &quantGain); stageGain = clampGain(gains_[stage]); /* @@ -215,18 +228,20 @@ ExposureModeHelper::splitExposure(utils::Duration exposure) const /* Clamp the gain to lastStageGain and regulate exposureTime. */ if (stageExposureTime * lastStageGain >= exposure) { - exposureTime = clampExposureTime(exposure / lastStageGain); - gain = clampGain(exposure / exposureTime); + exposureTime = clampExposureTime(exposure / lastStageGain, &quantGain); + gain = clampGain((exposure / exposureTime) * quantGain, &quantGain); - return { exposureTime, gain, exposure / (exposureTime * gain) }; + return { exposureTime, gain, quantGain, + exposure / (exposureTime * gain * quantGain) }; } /* Clamp the exposureTime to stageExposureTime and regulate gain. */ if (stageExposureTime * stageGain >= exposure) { exposureTime = stageExposureTime; - gain = clampGain(exposure / exposureTime); + gain = clampGain((exposure / exposureTime) * quantGain, &quantGain); - return { exposureTime, gain, exposure / (exposureTime * gain) }; + return { exposureTime, gain, quantGain, + exposure / (exposureTime * gain * quantGain) }; } lastStageGain = stageGain; @@ -239,10 +254,11 @@ ExposureModeHelper::splitExposure(utils::Duration exposure) const * stages to use then the default stageGain of 1.0 is used so that * exposure time is maxed before gain is touched at all. */ - exposureTime = clampExposureTime(exposure / stageGain); - gain = clampGain(exposure / exposureTime); + exposureTime = clampExposureTime(exposure / stageGain, &quantGain); + gain = clampGain((exposure / exposureTime) * quantGain, &quantGain); - return { exposureTime, gain, exposure / (exposureTime * gain) }; + return { exposureTime, gain, quantGain, + exposure / (exposureTime * gain * quantGain) }; } /** diff --git a/src/ipa/libipa/exposure_mode_helper.h b/src/ipa/libipa/exposure_mode_helper.h index 8701fae9a26e..cc811e9fde18 100644 --- a/src/ipa/libipa/exposure_mode_helper.h +++ b/src/ipa/libipa/exposure_mode_helper.h @@ -30,7 +30,7 @@ public: void setLimits(utils::Duration minExposureTime, utils::Duration maxExposureTime, double minGain, double maxGain); - std::tuple + std::tuple splitExposure(utils::Duration exposure) const; utils::Duration minExposureTime() const { return minExposureTime_; } diff --git a/src/ipa/rkisp1/algorithms/agc.cpp b/src/ipa/rkisp1/algorithms/agc.cpp index 35440b67e999..0a29326841fb 100644 --- a/src/ipa/rkisp1/algorithms/agc.cpp +++ b/src/ipa/rkisp1/algorithms/agc.cpp @@ -567,15 +567,16 @@ void Agc::process(IPAContext &context, [[maybe_unused]] const uint32_t frame, setExposureCompensation(pow(2.0, frameContext.agc.exposureValue)); utils::Duration newExposureTime; - double aGain, dGain; - std::tie(newExposureTime, aGain, dGain) = + double aGain, qGain, dGain; + std::tie(newExposureTime, aGain, qGain, dGain) = calculateNewEv(frameContext.agc.constraintMode, frameContext.agc.exposureMode, hist, effectiveExposureValue); LOG(RkISP1Agc, Debug) - << "Divided up exposure time, analogue gain and digital gain are " - << newExposureTime << ", " << aGain << " and " << dGain; + << "Divided up exposure time, analogue gain, quantization gain" + << " and digital gain are " << newExposureTime << ", " << aGain + << ", " << qGain << " and " << dGain; IPAActiveState &activeState = context.activeState; /* Update the estimated exposure and gain. */ From patchwork Fri Aug 8 14:12:47 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24080 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 65CE8BDCC1 for ; Fri, 8 Aug 2025 14:14:12 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 1EF2069230; Fri, 8 Aug 2025 16:14:12 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="guKc8LFl"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 20F0C6921E for ; Fri, 8 Aug 2025 16:14:10 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id 2C936208E; Fri, 8 Aug 2025 16:13:20 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662400; bh=AZBECBfp5wAEJjuKXVy2zSaRSaqp6qqt7J1e6gBu4I4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=guKc8LFlRyIuZx/Pn0q7LxavfC6NkocyGIlgQHGVa56tFtVAc/Q2rTTthqPdbwal7 5uh89AkrI5nIenhmch1E9dL96HAiocCplsPHg3SjRxbyA2C5PP7FrfCK2QWyl2gvin kGOZn83TetXUUIcZZuoQF30Kd/WvFqYYwG9WR/Jw= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug Subject: [PATCH v2 09/16] ipa: rkisp1: agc: Add correction for exposure quantization Date: Fri, 8 Aug 2025 16:12:47 +0200 Message-ID: <20250808141315.413839-10-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" There are several occations where quantization can lead to visible effects. In WDR mode it can happen that exposure times get set to very low values (Sometimes 2-3 lines). This intentionally introduced underexposure is corrected by the GWDR module. As exposure time is quantized by lines, the smallest possible change in exposure time now results in a quite visible change in perceived brightness. Sometimes the possible gain steps are also quite large leading to visible jumps if e.g. if the exposure time is fixed. Mitigate that by applying a global gain to account for the error introduced by the exposure quantization. ToDo: This needs perfect frame synchronous control of the sensor to work properly which is not guaranteed in all cases. It still improves the behavior with the current regulation and can easily be skipped, when there is no compress algorithm. Signed-off-by: Stefan Klug Reviewed-by: Kieran Bingham Reviewed-by: Daniel Scally --- src/ipa/rkisp1/algorithms/agc.cpp | 24 +++++++++++++++++++++--- src/ipa/rkisp1/ipa_context.h | 2 ++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/ipa/rkisp1/algorithms/agc.cpp b/src/ipa/rkisp1/algorithms/agc.cpp index 0a29326841fb..d34c041f9fe1 100644 --- a/src/ipa/rkisp1/algorithms/agc.cpp +++ b/src/ipa/rkisp1/algorithms/agc.cpp @@ -199,6 +199,9 @@ int Agc::configure(IPAContext &context, const IPACameraSensorInfo &configInfo) context.configuration.agc.measureWindow.h_size = configInfo.outputSize.width; context.configuration.agc.measureWindow.v_size = configInfo.outputSize.height; + AgcMeanLuminance::configure(context.configuration.sensor.lineDuration, + context.camHelper.get()); + setLimits(context.configuration.sensor.minExposureTime, context.configuration.sensor.maxExposureTime, context.configuration.sensor.minAnalogueGain, @@ -283,6 +286,10 @@ void Agc::queueRequest(IPAContext &context, if (!frameContext.agc.autoGainEnabled) frameContext.agc.gain = agc.manual.gain; + if (!frameContext.agc.autoExposureEnabled && + !frameContext.agc.autoGainEnabled) + frameContext.agc.quantizationGain = 1.0; + const auto &meteringMode = controls.get(controls::AeMeteringMode); if (meteringMode) { frameContext.agc.updateMetering = agc.meteringMode != *meteringMode; @@ -336,12 +343,17 @@ void Agc::prepare(IPAContext &context, const uint32_t frame, { uint32_t activeAutoExposure = context.activeState.agc.automatic.exposure; double activeAutoGain = context.activeState.agc.automatic.gain; + double activeAutoQGain = context.activeState.agc.automatic.quantizationGain; /* Populate exposure and gain in auto mode */ - if (frameContext.agc.autoExposureEnabled) + if (frameContext.agc.autoExposureEnabled) { frameContext.agc.exposure = activeAutoExposure; - if (frameContext.agc.autoGainEnabled) + frameContext.agc.quantizationGain = activeAutoQGain; + } + if (frameContext.agc.autoGainEnabled) { frameContext.agc.gain = activeAutoGain; + frameContext.agc.quantizationGain = activeAutoQGain; + } /* * Populate manual exposure and gain from the active auto values when @@ -354,6 +366,12 @@ void Agc::prepare(IPAContext &context, const uint32_t frame, if (!frameContext.agc.autoGainEnabled && frameContext.agc.autoGainModeChange) { context.activeState.agc.manual.gain = activeAutoGain; frameContext.agc.gain = activeAutoGain; + frameContext.agc.quantizationGain = activeAutoQGain; + } + + if (context.activeState.compress.supported) { + frameContext.compress.enable = true; + frameContext.compress.gain = frameContext.agc.quantizationGain; } if (frame > 0 && !frameContext.agc.updateMetering) @@ -582,7 +600,7 @@ void Agc::process(IPAContext &context, [[maybe_unused]] const uint32_t frame, /* Update the estimated exposure and gain. */ activeState.agc.automatic.exposure = newExposureTime / lineDuration; activeState.agc.automatic.gain = aGain; - + activeState.agc.automatic.quantizationGain = qGain; /* * Expand the target frame duration so that we do not run faster than * the minimum frame duration when we have short exposures. diff --git a/src/ipa/rkisp1/ipa_context.h b/src/ipa/rkisp1/ipa_context.h index 37a74215ce19..362ab2fda5fe 100644 --- a/src/ipa/rkisp1/ipa_context.h +++ b/src/ipa/rkisp1/ipa_context.h @@ -77,6 +77,7 @@ struct IPAActiveState { struct { uint32_t exposure; double gain; + double quantizationGain; } automatic; bool autoExposureEnabled; @@ -135,6 +136,7 @@ struct IPAFrameContext : public FrameContext { uint32_t exposure; double gain; double exposureValue; + double quantizationGain; uint32_t vblank; bool autoExposureEnabled; bool autoGainEnabled; From patchwork Fri Aug 8 14:12:48 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24081 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 08F32BDCC1 for ; Fri, 8 Aug 2025 14:14:15 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id B627269227; Fri, 8 Aug 2025 16:14:14 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="mAUKwrGp"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [IPv6:2001:4b98:dc2:55:216:3eff:fef7:d647]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 1F3E469221 for ; Fri, 8 Aug 2025 16:14:13 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id 2499C185B; Fri, 8 Aug 2025 16:13:23 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662403; bh=nOvzFXaNpsdqSZiKH6UrWYHEak/kLAo46+DfYL22M/A=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=mAUKwrGpesNE6g8kzp/v5lbccDz/vWG+JffyRA/LotwKL87RDVbR8n6hoWaOVhe2y 4DrNjZJ2lgdxQ0HnyQU9CR1ZwzR1F08v1ImdAPYXJ0boB7NA1/Hyy497ExCeQTPwy5 TmlTe+iGRXhjFj5Yv0A9ZlRw+yGMJdSxiKogxhAI= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug , Kieran Bingham , Paul Elder Subject: [PATCH v2 10/16] pipeline: rkisp1: Add error log when parameter queuing fails Date: Fri, 8 Aug 2025 16:12:48 +0200 Message-ID: <20250808141315.413839-11-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" When the extensible parameters queued to the kernel contain an unknown block type it fails with -EINVAL. This should not happen as user land is supposed to check for the supported parameter types. But it took a while to figure out where things went wrong. Add a error statement when queuing of the parameter buffer fails for whatever reason. Signed-off-by: Stefan Klug Reviewed-by: Kieran Bingham Reviewed-by: Paul Elder Reviewed-by: Daniel Scally --- Changes in v4: - Improved commit message Changes in v3: - Collected tags - Removed hint regarding unsupported parameter types as this will be handled using the now upstreamed RKISP1_CID_SUPPORTED_PARAMS_BLOCKS. Changes in v2: - Also print the error code in case of failure --- src/libcamera/pipeline/rkisp1/rkisp1.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/libcamera/pipeline/rkisp1/rkisp1.cpp b/src/libcamera/pipeline/rkisp1/rkisp1.cpp index 8b434a56ea04..06785cb2fd57 100644 --- a/src/libcamera/pipeline/rkisp1/rkisp1.cpp +++ b/src/libcamera/pipeline/rkisp1/rkisp1.cpp @@ -429,7 +429,14 @@ void RkISP1CameraData::paramsComputed(unsigned int frame, unsigned int bytesused return; info->paramBuffer->_d()->metadata().planes()[0].bytesused = bytesused; - pipe->param_->queueBuffer(info->paramBuffer); + + int ret = pipe->param_->queueBuffer(info->paramBuffer); + if (ret < 0) { + LOG(RkISP1, Error) << "Failed to queue parameter buffer: " + << strerror(-ret); + return; + } + pipe->stat_->queueBuffer(info->statBuffer); if (info->mainPathBuffer) From patchwork Fri Aug 8 14:12:49 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24082 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 9CA81BDCC1 for ; Fri, 8 Aug 2025 14:14:17 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 5000A69234; Fri, 8 Aug 2025 16:14:17 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="HeoeGsJc"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [IPv6:2001:4b98:dc2:55:216:3eff:fef7:d647]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id CDBB569232 for ; Fri, 8 Aug 2025 16:14:15 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id E0E95208E; Fri, 8 Aug 2025 16:13:25 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662406; bh=XFTWEkGkyqYGTfqhC6w4yCohY2TSg7Hb0bYBuc4aUfE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=HeoeGsJciLcu+iA6XZBjE//oQ5FvzWCuzMR/mjj+KniNoivm+VlcdtyJ65kViYRBj 8g/+bEwvOGVI9d7sHA2EK8mZLA6dLj3pj/JmC6GEmpizoUrScJ2rXEWWImMVNUq7VP I+1juRn8U+WQBW1mpnl6v8cxRu0fx8iZ58hM4S+E= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug Subject: [PATCH v2 11/16] include: linux: Partially update linux headers from v6.16-rc1-310-gd968e50b5c26 Date: Fri, 8 Aug 2025 16:12:49 +0200 Message-ID: <20250808141315.413839-12-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" Update rkisp1-config.h and v4l2-controls.h from the next branch of https://gitlab.freedesktop.org/linux-media/media-committers.git to include the WDR related updates. The rest was left as is to minimize the risk of issues due to last minute changes in the upstream process. Signed-off-by: Stefan Klug --- Changes in v2: - Updated headers from linux-media next branch --- include/linux/rkisp1-config.h | 108 +++++++++++++++++++++++++++++++++- include/linux/v4l2-controls.h | 17 ++++-- 2 files changed, 119 insertions(+), 6 deletions(-) diff --git a/include/linux/rkisp1-config.h b/include/linux/rkisp1-config.h index edbc6cb65d1c..d323bfa72d8e 100644 --- a/include/linux/rkisp1-config.h +++ b/include/linux/rkisp1-config.h @@ -169,6 +169,13 @@ */ #define RKISP1_CIF_ISP_COMPAND_NUM_POINTS 64 +/* + * Wide Dynamic Range + */ +#define RKISP1_CIF_ISP_WDR_CURVE_NUM_INTERV 32 +#define RKISP1_CIF_ISP_WDR_CURVE_NUM_COEFF (RKISP1_CIF_ISP_WDR_CURVE_NUM_INTERV + 1) +#define RKISP1_CIF_ISP_WDR_CURVE_NUM_DY_REGS 4 + /* * Measurement types */ @@ -889,6 +896,72 @@ struct rkisp1_cif_isp_compand_curve_config { __u32 y[RKISP1_CIF_ISP_COMPAND_NUM_POINTS]; }; +/** + * struct rkisp1_cif_isp_wdr_tone_curve - Tone mapping curve definition for WDR. + * + * @dY: the dYn increments for horizontal (input) axis of the tone curve. + * each 3-bit dY value represents an increment of 2**(value+3). + * dY[0] bits 0:2 is increment dY1, bit 3 unused + * dY[0] bits 4:6 is increment dY2, bit 7 unused + * ... + * dY[0] bits 28:30 is increment dY8, bit 31 unused + * ... and so on till dY[3] bits 28:30 is increment dY32, bit 31 unused. + * @ym: the Ym values for the vertical (output) axis of the tone curve. + * each value is 13 bit. + */ +struct rkisp1_cif_isp_wdr_tone_curve { + __u32 dY[RKISP1_CIF_ISP_WDR_CURVE_NUM_DY_REGS]; + __u16 ym[RKISP1_CIF_ISP_WDR_CURVE_NUM_COEFF]; +}; + +/** + * struct rkisp1_cif_isp_wdr_iref_config - Illumination reference config for WDR. + * + * Use illumination reference value as described below, instead of only the + * luminance (Y) value for tone mapping and gain calculations: + * IRef = (rgb_factor * RGBMax_tr + (8 - rgb_factor) * Y)/8 + * + * @rgb_factor: defines how much influence the RGBmax approach has in + * comparison to Y (valid values are 0..8). + * @use_y9_8: use Y*9/8 for maximum value calculation along with the + * default of R, G, B for noise reduction. + * @use_rgb7_8: decrease RGBMax by 7/8 for noise reduction. + * @disable_transient: disable transient calculation between Y and RGBY_max. + */ +struct rkisp1_cif_isp_wdr_iref_config { + __u8 rgb_factor; + __u8 use_y9_8; + __u8 use_rgb7_8; + __u8 disable_transient; +}; + +/** + * struct rkisp1_cif_isp_wdr_config - Configuration for wide dynamic range. + * + * @tone_curve: tone mapping curve. + * @iref_config: illumination reference configuration. (when use_iref is true) + * @rgb_offset: RGB offset value for RGB operation mode. (12 bits) + * @luma_offset: luminance offset value for RGB operation mode. (12 bits) + * @dmin_thresh: lower threshold for deltaMin value. (12 bits) + * @dmin_strength: strength factor for deltaMin. (valid range is 0x00..0x10) + * @use_rgb_colorspace: use RGB instead of luminance/chrominance colorspace. + * @bypass_chroma_mapping: disable chrominance mapping (only valid if + * use_rgb_colorspace = 0) + * @use_iref: use illumination reference instead of Y for tone mapping + * and gain calculations. + */ +struct rkisp1_cif_isp_wdr_config { + struct rkisp1_cif_isp_wdr_tone_curve tone_curve; + struct rkisp1_cif_isp_wdr_iref_config iref_config; + __u16 rgb_offset; + __u16 luma_offset; + __u16 dmin_thresh; + __u8 dmin_strength; + __u8 use_rgb_colorspace; + __u8 bypass_chroma_mapping; + __u8 use_iref; +}; + /*---------- PART2: Measurement Statistics ------------*/ /** @@ -1059,6 +1132,7 @@ struct rkisp1_stat_buffer { * @RKISP1_EXT_PARAMS_BLOCK_TYPE_COMPAND_BLS: BLS in the compand block * @RKISP1_EXT_PARAMS_BLOCK_TYPE_COMPAND_EXPAND: Companding expand curve * @RKISP1_EXT_PARAMS_BLOCK_TYPE_COMPAND_COMPRESS: Companding compress curve + * @RKISP1_EXT_PARAMS_BLOCK_TYPE_WDR: Wide dynamic range */ enum rkisp1_ext_params_block_type { RKISP1_EXT_PARAMS_BLOCK_TYPE_BLS, @@ -1081,11 +1155,15 @@ enum rkisp1_ext_params_block_type { RKISP1_EXT_PARAMS_BLOCK_TYPE_COMPAND_BLS, RKISP1_EXT_PARAMS_BLOCK_TYPE_COMPAND_EXPAND, RKISP1_EXT_PARAMS_BLOCK_TYPE_COMPAND_COMPRESS, + RKISP1_EXT_PARAMS_BLOCK_TYPE_WDR, }; #define RKISP1_EXT_PARAMS_FL_BLOCK_DISABLE (1U << 0) #define RKISP1_EXT_PARAMS_FL_BLOCK_ENABLE (1U << 1) +/* A bitmask of parameters blocks supported on the current hardware. */ +#define RKISP1_CID_SUPPORTED_PARAMS_BLOCKS (V4L2_CID_USER_RKISP1_BASE + 0x01) + /** * struct rkisp1_ext_params_block_header - RkISP1 extensible parameters block * header @@ -1460,6 +1538,23 @@ struct rkisp1_ext_params_compand_curve_config { struct rkisp1_cif_isp_compand_curve_config config; } __attribute__((aligned(8))); +/** + * struct rkisp1_ext_params_wdr_config - RkISP1 extensible params + * Wide dynamic range config + * + * RkISP1 extensible parameters WDR block. + * Identified by :c:type:`RKISP1_EXT_PARAMS_BLOCK_TYPE_WDR` + * + * @header: The RkISP1 extensible parameters header, see + * :c:type:`rkisp1_ext_params_block_header` + * @config: WDR configuration, see + * :c:type:`rkisp1_cif_isp_wdr_config` + */ +struct rkisp1_ext_params_wdr_config { + struct rkisp1_ext_params_block_header header; + struct rkisp1_cif_isp_wdr_config config; +} __attribute__((aligned(8))); + /* * The rkisp1_ext_params_compand_curve_config structure is counted twice as it * is used for both the COMPAND_EXPAND and COMPAND_COMPRESS block types. @@ -1484,7 +1579,8 @@ struct rkisp1_ext_params_compand_curve_config { sizeof(struct rkisp1_ext_params_afc_config) +\ sizeof(struct rkisp1_ext_params_compand_bls_config) +\ sizeof(struct rkisp1_ext_params_compand_curve_config) +\ - sizeof(struct rkisp1_ext_params_compand_curve_config)) + sizeof(struct rkisp1_ext_params_compand_curve_config) +\ + sizeof(struct rkisp1_ext_params_wdr_config)) /** * enum rksip1_ext_param_buffer_version - RkISP1 extensible parameters version @@ -1520,6 +1616,14 @@ enum rksip1_ext_param_buffer_version { * V4L2 control. If such control is not available, userspace should assume only * RKISP1_EXT_PARAM_BUFFER_V1 is supported by the driver. * + * The read-only V4L2 control ``RKISP1_CID_SUPPORTED_PARAMS_BLOCKS`` can be used + * to query the blocks supported by the device. It contains a bitmask where each + * bit represents the availability of the corresponding entry from the + * :c:type:`rkisp1_ext_params_block_type` enum. The current and default values + * of the control represents the blocks supported by the device instance, while + * the maximum value represents the blocks supported by the kernel driver, + * independently of the device instance. + * * For each ISP block that userspace wants to configure, a block-specific * structure is appended to the @data buffer, one after the other without gaps * in between nor overlaps. Userspace shall populate the @data_size field with @@ -1528,7 +1632,7 @@ enum rksip1_ext_param_buffer_version { * The expected memory layout of the parameters buffer is:: * * +-------------------- struct rkisp1_ext_params_cfg -------------------+ - * | version = RKISP_EXT_PARAMS_BUFFER_V1; | + * | version = RKISP1_EXT_PARAM_BUFFER_V1; | * | data_size = sizeof(struct rkisp1_ext_params_bls_config) | * | + sizeof(struct rkisp1_ext_params_dpcc_config); | * | +------------------------- data ---------------------------------+ | diff --git a/include/linux/v4l2-controls.h b/include/linux/v4l2-controls.h index 882a81805783..fc43bb09efe3 100644 --- a/include/linux/v4l2-controls.h +++ b/include/linux/v4l2-controls.h @@ -177,10 +177,6 @@ enum v4l2_colorfx { * We reserve 128 controls for this driver. */ #define V4L2_CID_USER_CCS_BASE (V4L2_CID_USER_BASE + 0x10f0) - -/* The base for the bcm2835-isp driver controls. - * We reserve 16 controls for this driver. */ -#define V4L2_CID_USER_BCM2835_ISP_BASE (V4L2_CID_USER_BASE + 0x10e0) /* * The base for Allegro driver controls. * We reserve 16 controls for this driver. @@ -217,6 +213,19 @@ enum v4l2_colorfx { */ #define V4L2_CID_USER_THP7312_BASE (V4L2_CID_USER_BASE + 0x11c0) +/* + * The base for the uvc driver controls. + * See linux/uvcvideo.h for the list of controls. + * We reserve 64 controls for this driver. + */ +#define V4L2_CID_USER_UVC_BASE (V4L2_CID_USER_BASE + 0x11e0) + +/* + * The base for Rockchip ISP1 driver controls. + * We reserve 16 controls for this driver. + */ +#define V4L2_CID_USER_RKISP1_BASE (V4L2_CID_USER_BASE + 0x1220) + /* MPEG-class control IDs */ /* The MPEG controls are applicable to all codec controls * and the 'MPEG' part of the define is historical */ From patchwork Fri Aug 8 14:12:50 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24083 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 54438BDCC1 for ; Fri, 8 Aug 2025 14:14:20 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 1594E69237; Fri, 8 Aug 2025 16:14:20 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="WczthZf+"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 38EE669227 for ; Fri, 8 Aug 2025 16:14:19 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id 4F61C208E; Fri, 8 Aug 2025 16:13:29 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662409; bh=sTIEc/0QGr/bX2YAqYMQGdoogbsGmOTnAoiP0E7dHGU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=WczthZf+OAW3iD+cTP5zQGwnazdiTTA1qudgHbTbh1+A0tVpgtK/ZQofUMZ1m67Bx MhW+l04tVuKqarOr9D9y8s3nYtT3EMFM4ZO8ozuAX4fYwQt2jDVIkoMVQbjPht0asq 8Ljv4fmFsMmfZU1uerSb5ewZzUt9Oizlc21sR3o8= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug , Paul Elder Subject: [PATCH v2 12/16] libcamera: Add PID controller class Date: Fri, 8 Aug 2025 16:12:50 +0200 Message-ID: <20250808141315.413839-13-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" A PID controller is a practical and proven solution for many regulation tasks. This implementation can be parameterized either using the standard form or normal form [1]. Additionally output limits can be specified that are used to clamp the output and to prevent integrator windup. [1]: https://en.wikipedia.org/wiki/Proportional-integral-derivative_controller Signed-off-by: Stefan Klug Reviewed-by: Paul Elder Reviewed-by: Kieran Bingham --- Changes in v2: - Collected tag - Fix default min limit to be numeric_limits::lowest() instead of numeric_limits::min() - Added debug log for anti-windup --- include/libcamera/internal/meson.build | 1 + include/libcamera/internal/pid_controller.h | 46 ++++++ src/libcamera/meson.build | 1 + src/libcamera/pid_controller.cpp | 172 ++++++++++++++++++++ 4 files changed, 220 insertions(+) create mode 100644 include/libcamera/internal/pid_controller.h create mode 100644 src/libcamera/pid_controller.cpp diff --git a/include/libcamera/internal/meson.build b/include/libcamera/internal/meson.build index 5c80a28c4cbe..adbd665ec77b 100644 --- a/include/libcamera/internal/meson.build +++ b/include/libcamera/internal/meson.build @@ -34,6 +34,7 @@ libcamera_internal_headers = files([ 'media_device.h', 'media_object.h', 'media_pipeline.h', + 'pid_controller.h', 'pipeline_handler.h', 'process.h', 'pub_key.h', diff --git a/include/libcamera/internal/pid_controller.h b/include/libcamera/internal/pid_controller.h new file mode 100644 index 000000000000..6c2c4d3c4565 --- /dev/null +++ b/include/libcamera/internal/pid_controller.h @@ -0,0 +1,46 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2025, Ideas On Board Oy + * + * PID Controller + */ +#pragma once + +#include + +#include + +namespace libcamera { + +LOG_DECLARE_CATEGORY(PidController) +class PidController +{ +public: + PidController(double Kp = 1.0, double Ki = 1e6, double Kd = 0.0, + double min = std::numeric_limits::lowest(), + double max = std::numeric_limits::max()); + + void setNormalParameters(double Kp = 1.0, double Ki = 1e6, double Kd = 0.0); + void setStandardParameters(double Kp = 1.0, double Ti = 1e6, double Td = 0.0); + void setOutputLimits(double min = std::numeric_limits::lowest(), + double max = std::numeric_limits::max()); + void reset(); + + void setTarget(double target); + double process(double value, double dt = 1.0); + +private: + double Kp_; + double Ki_; + double Kd_; + double max_; + double min_; + double target_; + + bool clamped_bottom_; + bool clamped_top_; + double integral_; + double last_error_; +}; + +} /* namespace libcamera */ diff --git a/src/libcamera/meson.build b/src/libcamera/meson.build index de1eb99b28fd..a821eff2a29b 100644 --- a/src/libcamera/meson.build +++ b/src/libcamera/meson.build @@ -45,6 +45,7 @@ libcamera_internal_sources = files([ 'media_device.cpp', 'media_object.cpp', 'media_pipeline.cpp', + 'pid_controller.cpp', 'pipeline_handler.cpp', 'process.cpp', 'pub_key.cpp', diff --git a/src/libcamera/pid_controller.cpp b/src/libcamera/pid_controller.cpp new file mode 100644 index 000000000000..3ade02051902 --- /dev/null +++ b/src/libcamera/pid_controller.cpp @@ -0,0 +1,172 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2025, Ideas on Board Oy + * + * PID controller + */ + +#include "libcamera/internal/pid_controller.h" + +#include + +#include + +/** + * \file pid_controller.h + * \brief PID controller class + */ + +namespace libcamera { + +LOG_DEFINE_CATEGORY(PidController) +/** + * \class PidController + * \brief Implementation of a PID controller + * + * Implementation of a Proportional Integral Derivative controller. + * See https://en.wikipedia.org/wiki/Proportional-integral-derivative_controller + * for the underlying details. + * + */ + +/** + * \brief Construct a PidController with optional normal parameters + * \param[in] Kp Proportional gain + * \param[in] Ki Integral gain + * \param[in] Kd Derivative gain + * \param[in] min Minimum output value + * \param[in] max Maximum output value + * + * For the parameters \see setNormalParameters() and \see setOutputLimits(). + */ +PidController::PidController(double Kp, double Ki, double Kd, double min, double max) +{ + reset(); + setNormalParameters(Kp, Ki, Kd); + setOutputLimits(min, max); +} + +/** + * \brief Set the normal parameters + * \param[in] Kp Proportional gain + * \param[in] Ki Integral gain + * \param[in] Kd Derivative gain + * + * Set the normal parameters of the PID controller. + */ +void PidController::setNormalParameters(double Kp, double Ki, double Kd) +{ + Kp_ = Kp; + Ki_ = Ki; + Kd_ = Kd; +} + +/** + * \brief Set the standard parameters + * \param[in] Kp Proportional gain + * \param[in] Ti Integration time constant + * \param[in] Td Derivative time constant + * + * Set the standard parameters of the PID controller. Functionally it is + * identical to the normal parameters but has the added benefit that it is + * easier to understand the values. The \a Ti parameter specifies the time the + * controller will tolerate the output value to be away from the target. Td is + * the time in which the controller tries to approach the target value. + * + * \see https://en.wikipedia.org/wiki/Proportional-integral-derivative_controller#Standard_form + */ +void PidController::setStandardParameters(double Kp, double Ti, double Td) +{ + Kp_ = Kp; + Ki_ = Kp / Ti; + Kd_ = Kp / Td; +} + +/** + * \brief Set the output limits + * \param[in] min Minimum output value + * \param[in] max Maximum output value + * + * Set the minimum and maximum output values of the controller. The controller + * will clamp the output to these values and ensure that no windup of the + * integral part occurs. + */ +void PidController::setOutputLimits(double min, double max) +{ + min_ = min; + max_ = max; +} + +/** + * \brief Reset the controller + * + * Reset the internal state of the controller. + */ +void PidController::reset() +{ + last_error_ = 0; + integral_ = 0; + clamped_bottom_ = false; + clamped_top_ = false; +} + +/** + * \brief Set the target value + * \param[in] target Target value + * + * Set the target value the controller shall reach. In controller theory this is + * usually called the set point. + */ +void PidController::setTarget(double target) +{ + target_ = target; +} + +/** + * \brief Run a regulation step + * \param[in] value Measured value + * \param[in] dt Time since last call + * \return Output value + * + * Process the last measurement (also called process variable PV) and return the + * new regulation value. The \a dt parameter specifies the time since the last + * call. It defaults to 1.0, so in cases that are not time but frame based, it + * can be left out. + */ +double PidController::process(double value, double dt) +{ + double error = target_ - value; + double derivative = (error - last_error_) / dt; + + /* If we hit a limit disable the integrative part in that direction */ + if ((error * Ki_ > 0 && !clamped_top_) || + (error * Ki_ < 0 && !clamped_bottom_)) + integral_ += error * dt; + else + LOG(PidController, Debug) << "Disable integrative part: " + << ", clamped_top_: " << clamped_top_ + << ", clamped_bottom_: " << clamped_bottom_; + double ret = Kp_ * error + Ki_ * integral_ + Kd_ * derivative; + + clamped_top_ = false; + if (ret >= max_) { + clamped_top_ = true; + ret = max_; + } + + clamped_bottom_ = false; + if (ret <= min_) { + clamped_bottom_ = true; + ret = min_; + } + + LOG(PidController, Debug) << "Value: " << value << ", Target: " << target_ + << ", Error: " << error << ", Integral: " << integral_ + << ", Derivative: " << derivative << ", Output: " << ret; + + last_error_ = error; + + return ret; +} + +} /* namespace libcamera */ From patchwork Fri Aug 8 14:12:51 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24084 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 F06B0BDCC1 for ; Fri, 8 Aug 2025 14:14:24 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id AED5069232; Fri, 8 Aug 2025 16:14:24 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="R5k7m6wd"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [IPv6:2001:4b98:dc2:55:216:3eff:fef7:d647]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 321A569227 for ; Fri, 8 Aug 2025 16:14:22 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id 4979E185B; Fri, 8 Aug 2025 16:13:32 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662412; bh=xPxMkPGumdL56UfZRC/HPYUQFQ5qqJ1DhuZq9STAE9U=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=R5k7m6wdnrvWkpb4L29UKTWLLxzq+trSVLpAPqXlq1+R7XnBdmr7LsIgcEIzWzD1H 1cGc180h199bFdOGoFqNIvUQDYgDjCY9xDzvx/ffwyJTopH8h7MsJ+fmIPuQDkp+iY Y5YRYasDECD7blNp1sbm5h68HgE0DDpn16+5DgSI= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug , Paul Elder Subject: [PATCH v2 13/16] ipa: rkisp1: Switch histogram to RGB combined mode Date: Fri, 8 Aug 2025 16:12:51 +0200 Message-ID: <20250808141315.413839-14-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" The Y mode of the histogram gets captured at the ISP output, before the output formatter. This has the side effect that the first and the last bins are empty in case of limited YUV range. Another side effect is that gamma and GWDR processing is included in the histogram which makes algorithm development very difficult. In RGB mode the histogram is taken after xtalk (CCM) and is therefore independent of gamma and WDR. The limited range issue also does not apply. In the ISP reference it is however stated that "it is not possible to calculate a luminance or grayscale histogram from an RGB histogram since the position information is lost during its generation". During testing the RGB histogram provided good data and better algorithmic stability at a possible (but not measured) inaccuracy. Another option would be to pass the color space information into the IPA and strip the histogram accordingly. For ease of implementation switch to the RGB mode. Signed-off-by: Stefan Klug Reviewed-by: Paul Elder --- src/ipa/rkisp1/algorithms/agc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ipa/rkisp1/algorithms/agc.cpp b/src/ipa/rkisp1/algorithms/agc.cpp index d34c041f9fe1..8227d60213c2 100644 --- a/src/ipa/rkisp1/algorithms/agc.cpp +++ b/src/ipa/rkisp1/algorithms/agc.cpp @@ -396,7 +396,7 @@ void Agc::prepare(IPAContext &context, const uint32_t frame, hstConfig.setEnabled(true); hstConfig->meas_window = context.configuration.agc.measureWindow; - hstConfig->mode = RKISP1_CIF_ISP_HISTOGRAM_MODE_Y_HISTOGRAM; + hstConfig->mode = RKISP1_CIF_ISP_HISTOGRAM_MODE_RGB_COMBINED; Span weights{ hstConfig->hist_weight, From patchwork Fri Aug 8 14:12:52 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24085 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 6AAE2BDCC1 for ; Fri, 8 Aug 2025 14:14:27 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 2FDAE6923B; Fri, 8 Aug 2025 16:14:27 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="awNS7bAD"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id BD6F869236 for ; Fri, 8 Aug 2025 16:14:25 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id CFE18208E; Fri, 8 Aug 2025 16:13:35 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662415; bh=rHLRW8tsxo92xq06cMILer0SZh0C4g1B7Gozbfd/pTU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=awNS7bADIWP0rLLXFs+h9SVI4NMN+kOzj/zM8NVNFVbw953/vg1GoU0FyS3+evUY2 043t6aOY6pjyo/Eh+MlbRriPZZ8b4iTvis/8n3rwTDQ1NgUAPudpON3EJTztxXTs/m hoHbH3GmYXonOk7p/MqehitAJzH0X/FnWb6gC7BE= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug Subject: [PATCH v2 14/16] pipeline: rkisp1: Query kernel for available params blocks Date: Fri, 8 Aug 2025 16:12:52 +0200 Message-ID: <20250808141315.413839-15-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" Query the params device for RKISP1_CID_SUPPORTED_PARAMS_BLOCKS and inject the information into the IPA hardware context for use by the algorithms. Signed-off-by: Stefan Klug Reviewed-by: Kieran Bingham Reviewed-by: Daniel Scally --- include/libcamera/ipa/rkisp1.mojom | 2 +- src/ipa/rkisp1/ipa_context.h | 1 + src/ipa/rkisp1/rkisp1.cpp | 20 +++++++++++----- src/libcamera/pipeline/rkisp1/rkisp1.cpp | 29 ++++++++++++++++++++---- 4 files changed, 41 insertions(+), 11 deletions(-) diff --git a/include/libcamera/ipa/rkisp1.mojom b/include/libcamera/ipa/rkisp1.mojom index 043ad27ea199..068e898848c4 100644 --- a/include/libcamera/ipa/rkisp1.mojom +++ b/include/libcamera/ipa/rkisp1.mojom @@ -16,7 +16,7 @@ struct IPAConfigInfo { interface IPARkISP1Interface { init(libcamera.IPASettings settings, - uint32 hwRevision, + uint32 hwRevision, uint32 supportedBlocks, libcamera.IPACameraSensorInfo sensorInfo, libcamera.ControlInfoMap sensorControls) => (int32 ret, libcamera.ControlInfoMap ipaControls); diff --git a/src/ipa/rkisp1/ipa_context.h b/src/ipa/rkisp1/ipa_context.h index 362ab2fda5fe..60cfab228edf 100644 --- a/src/ipa/rkisp1/ipa_context.h +++ b/src/ipa/rkisp1/ipa_context.h @@ -36,6 +36,7 @@ struct IPAHwSettings { unsigned int numHistogramBins; unsigned int numHistogramWeights; unsigned int numGammaOutSamples; + uint32_t supportedBlocks; bool compand; }; diff --git a/src/ipa/rkisp1/rkisp1.cpp b/src/ipa/rkisp1/rkisp1.cpp index cf66d5553dcd..9ba0f0e6eb9d 100644 --- a/src/ipa/rkisp1/rkisp1.cpp +++ b/src/ipa/rkisp1/rkisp1.cpp @@ -52,6 +52,7 @@ public: IPARkISP1(); int init(const IPASettings &settings, unsigned int hwRevision, + uint32_t supportedBlocks, const IPACameraSensorInfo &sensorInfo, const ControlInfoMap &sensorControls, ControlInfoMap *ipaControls) override; @@ -89,27 +90,30 @@ private: namespace { -const IPAHwSettings ipaHwSettingsV10{ +IPAHwSettings ipaHwSettingsV10{ RKISP1_CIF_ISP_AE_MEAN_MAX_V10, RKISP1_CIF_ISP_HIST_BIN_N_MAX_V10, RKISP1_CIF_ISP_HISTOGRAM_WEIGHT_GRIDS_SIZE_V10, RKISP1_CIF_ISP_GAMMA_OUT_MAX_SAMPLES_V10, + 0, false, }; -const IPAHwSettings ipaHwSettingsIMX8MP{ +IPAHwSettings ipaHwSettingsIMX8MP{ RKISP1_CIF_ISP_AE_MEAN_MAX_V10, RKISP1_CIF_ISP_HIST_BIN_N_MAX_V10, RKISP1_CIF_ISP_HISTOGRAM_WEIGHT_GRIDS_SIZE_V10, RKISP1_CIF_ISP_GAMMA_OUT_MAX_SAMPLES_V10, + 0, true, }; -const IPAHwSettings ipaHwSettingsV12{ +IPAHwSettings ipaHwSettingsV12{ RKISP1_CIF_ISP_AE_MEAN_MAX_V12, RKISP1_CIF_ISP_HIST_BIN_N_MAX_V12, RKISP1_CIF_ISP_HISTOGRAM_WEIGHT_GRIDS_SIZE_V12, RKISP1_CIF_ISP_GAMMA_OUT_MAX_SAMPLES_V12, + 0, false, }; @@ -132,20 +136,22 @@ std::string IPARkISP1::logPrefix() const } int IPARkISP1::init(const IPASettings &settings, unsigned int hwRevision, + uint32_t supportedBlocks, const IPACameraSensorInfo &sensorInfo, const ControlInfoMap &sensorControls, ControlInfoMap *ipaControls) { + IPAHwSettings *hw = nullptr; /* \todo Add support for other revisions */ switch (hwRevision) { case RKISP1_V10: - context_.hw = &ipaHwSettingsV10; + hw = &ipaHwSettingsV10; break; case RKISP1_V_IMX8MP: - context_.hw = &ipaHwSettingsIMX8MP; + hw = &ipaHwSettingsIMX8MP; break; case RKISP1_V12: - context_.hw = &ipaHwSettingsV12; + hw = &ipaHwSettingsV12; break; default: LOG(IPARkISP1, Error) @@ -153,6 +159,8 @@ int IPARkISP1::init(const IPASettings &settings, unsigned int hwRevision, << " is currently not supported"; return -ENODEV; } + hw->supportedBlocks = supportedBlocks; + context_.hw = hw; LOG(IPARkISP1, Debug) << "Hardware revision is " << hwRevision; diff --git a/src/libcamera/pipeline/rkisp1/rkisp1.cpp b/src/libcamera/pipeline/rkisp1/rkisp1.cpp index 06785cb2fd57..435c618731a2 100644 --- a/src/libcamera/pipeline/rkisp1/rkisp1.cpp +++ b/src/libcamera/pipeline/rkisp1/rkisp1.cpp @@ -100,7 +100,7 @@ public: PipelineHandlerRkISP1 *pipe(); const PipelineHandlerRkISP1 *pipe() const; - int loadIPA(unsigned int hwRevision); + int loadIPA(unsigned int hwRevision, uint32_t supportedBlocks); Stream mainPathStream_; Stream selfPathStream_; @@ -390,7 +390,7 @@ const PipelineHandlerRkISP1 *RkISP1CameraData::pipe() const return static_cast(Camera::Private::pipe()); } -int RkISP1CameraData::loadIPA(unsigned int hwRevision) +int RkISP1CameraData::loadIPA(unsigned int hwRevision, uint32_t supportedBlocks) { ipa_ = IPAManager::createIPA(pipe(), 1, 1); if (!ipa_) @@ -412,7 +412,8 @@ int RkISP1CameraData::loadIPA(unsigned int hwRevision) } ret = ipa_->init({ ipaTuningFile, sensor_->model() }, hwRevision, - sensorInfo, sensor_->controls(), &ipaControls_); + supportedBlocks, sensorInfo, sensor_->controls(), + &ipaControls_); if (ret < 0) { LOG(RkISP1, Error) << "IPA initialization failure"; return ret; @@ -1318,6 +1319,12 @@ int PipelineHandlerRkISP1::updateControls(RkISP1CameraData *data) return 0; } +/* + * By default we assume all the blocks that were included in the first + * extensible parameters series are available. That is the lower 20bits. + */ +const uint32_t kDefaultExtParamsBlocks = 0xfffff; + int PipelineHandlerRkISP1::createCamera(MediaEntity *sensor) { int ret; @@ -1355,7 +1362,21 @@ int PipelineHandlerRkISP1::createCamera(MediaEntity *sensor) isp_->frameStart.connect(data->delayedCtrls_.get(), &DelayedControls::applyControls); - ret = data->loadIPA(media_->hwRevision()); + uint32_t supportedBlocks = kDefaultExtParamsBlocks; + + auto &controls = param_->controls(); + if (controls.find(RKISP1_CID_SUPPORTED_PARAMS_BLOCKS) != controls.end()) { + auto ctrl = param_->getControls({ RKISP1_CID_SUPPORTED_PARAMS_BLOCKS }); + supportedBlocks = static_cast( + ctrl.get(RKISP1_CID_SUPPORTED_PARAMS_BLOCKS).get()); + } else { + LOG(RkISP1, Error) + << "Failed to query supported params blocks. Falling back to defaults."; + } + + LOG(RkISP1, Error) << "Supported params blocks: " << supportedBlocks; + + ret = data->loadIPA(media_->hwRevision(), supportedBlocks); if (ret) return ret; From patchwork Fri Aug 8 14:12:53 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24086 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 2DDF7BDCC1 for ; Fri, 8 Aug 2025 14:14:31 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id D6CD669227; Fri, 8 Aug 2025 16:14:30 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="oupTLE1g"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 94AB469227 for ; Fri, 8 Aug 2025 16:14:28 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id 95380208E; Fri, 8 Aug 2025 16:13:38 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662418; bh=Nxhy8qr/HeMjXj5c5iy41ahMuGcKi0n8iqFE2R7Qa2s=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=oupTLE1gQJRyfbapmC2yYI6yGdFuCdp9ruFFpSLaQEdN4f99vSY6zvMPMVtUTcTaz 7kcTiBN/1eeMCr44R39iMwNsuhz/W+zJSRJTgSWu6m4mY1GG4mqLuVkvI7cGe+HjMO QHCNAfQ2CKOA7Vyi4iZdJmKunwSuEI5wsQKAm0u8= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug Subject: [PATCH v2 15/16] ipa: rkisp1: Add WDR algorithm Date: Fri, 8 Aug 2025 16:12:53 +0200 Message-ID: <20250808141315.413839-16-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" Add a WDR algorithm to do global tone mapping. Global tone mapping is used to increase the perceived dynamic range of an image. The typical effect is that in areas that are normally overexposed, additional structure becomes visible. The overall idea is that the algorithm applies an exposure value correction to underexpose the image to the point where only a small number of saturated pixels is left. This artificial underexposure is then mitigated by applying a tone mapping curve. This algorithm implements 4 tone mapping strategies: - Linear - Power - Exponential - Histogram equalization Signed-off-by: Stefan Klug --- Changes in v2: - Fixed default value for min bright pixels - Added check for supported params type - Reset PID controller - Various fixes from Pauls review --- src/ipa/rkisp1/algorithms/meson.build | 1 + src/ipa/rkisp1/algorithms/wdr.cpp | 510 ++++++++++++++++++++++++++ src/ipa/rkisp1/algorithms/wdr.h | 64 ++++ src/ipa/rkisp1/ipa_context.h | 11 + src/ipa/rkisp1/params.cpp | 1 + src/ipa/rkisp1/params.h | 2 + src/libcamera/control_ids_debug.yaml | 7 +- src/libcamera/control_ids_draft.yaml | 70 ++++ 8 files changed, 665 insertions(+), 1 deletion(-) create mode 100644 src/ipa/rkisp1/algorithms/wdr.cpp create mode 100644 src/ipa/rkisp1/algorithms/wdr.h diff --git a/src/ipa/rkisp1/algorithms/meson.build b/src/ipa/rkisp1/algorithms/meson.build index 2e42a80cf99d..d329dbfb432d 100644 --- a/src/ipa/rkisp1/algorithms/meson.build +++ b/src/ipa/rkisp1/algorithms/meson.build @@ -14,4 +14,5 @@ rkisp1_ipa_algorithms = files([ 'gsl.cpp', 'lsc.cpp', 'lux.cpp', + 'wdr.cpp', ]) diff --git a/src/ipa/rkisp1/algorithms/wdr.cpp b/src/ipa/rkisp1/algorithms/wdr.cpp new file mode 100644 index 000000000000..0c1b261d4373 --- /dev/null +++ b/src/ipa/rkisp1/algorithms/wdr.cpp @@ -0,0 +1,510 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2025, Ideas On Board + * + * RkISP1 Wide Dynamic Range control + */ + +#include "wdr.h" + +#include +#include + +#include "libcamera/internal/yaml_parser.h" + +#include +#include + +#include "linux/rkisp1-config.h" + +/** + * \file wdr.h + */ + +namespace libcamera { + +namespace ipa::rkisp1::algorithms { + +/** + * \class WideDynamicRange + * \brief RkISP1 Wide Dynamic Range algorithm + * + * This algorithm implements automatic global tone mapping for the RkISP1. + * Global tone mapping is done by the GWDR hardware block and applies + * a global tone mapping curve to the image to increase the perceived dynamic + * range. Imagine an indoor scene with bright outside visible through the + * windows. With normal exposure settings, the windows will be completely + * saturated and no structure (sky/clouds) will be visible because the AEGC has + * to increase overall exposure to reach a certain level of mean brightness. In + * WDR mode, the algorithm will artifically reduce the exposure time so that the + * texture and colours become visible in the formerly saturated areas. Then the + * global tone mapping curve is applied to mitigate the loss of brightness. + * + * Calculating that tone mapping curve is the most difficult part. This + * algorithm implements four tone mapping strategies: + * - Linear: The tone mapping curve is a combination of two linear functions + * with one kneepoint + * - Power: The tone mapping curve follows a power function + * - Exponential: The tone mapping curve follows an exponential function + * - HistogramEqualization: The tone mapping curve tries to equalize the + * histogram + * + * The overall strategy is the same in all cases: A negative exposure value is + * applied to the AEGC regulation until the number of nearly saturated pixels go + * below a given threshold (controllable via WdrMaxBrightPixels, default is 2%) + * or the MinExposureValue specified in the tuning file is reached. + * + * The global tone mapping curve is then calculated so that it accounts for the + * reduction of brightness due to the negative exposure value. As the result of + * tone mapping is very difficult to quantize and is by definition a lossy + * process there is not a single "correct" solution. + * + * The approach taken here is based on a simple linear model. Consider a pixel + * that was originally 50% grey. It will have its exposure pushed down by the + * WDR's initial exposure compensation. This value then needs to be pushed back + * up by the tone mapping curve so that it is 50% grey again. This point serves + * as our kneepoint. To get to this kneepoint, this pixel and all darker pixels + * (to the left of the kneepoint on the tone mapping curve) will simply have the + * exposure compensation undone by pow(2, -WDR_EV). This cancels out the + * original exposure compensation, which was pow(2, WDR_EV). The remaining + * brigher pixels (to the right of the kneepoint on the tone mapping curve) will + * be compressed. The WdrStrength control adjusts the gain of the left part of + * the tone mapping curve. + * + * In the Power and Exponential modes, the curves are calculated so that they + * pass through that kneepoint. + * + * The histogram equalization mode tries to equalize the histogram of the + * image and acts independently of the calculated exposure value. + * + * \code{.unparsed} + * algorithms: + * - WideDynamicRange: + * ExposureConstraint: + * MaxBrightPixels: 0.02 + * yTarget: 0.95 + * MinExposureValue: -4.0 + * \endcode + */ + +LOG_DEFINE_CATEGORY(RkISP1Wdr) + +static constexpr unsigned int kTonecurveXIntervals = RKISP1_CIF_ISP_WDR_CURVE_NUM_INTERV; + +/* + * Increasing interval sizes. The intervals are crafted so that they sum + * up to 4096. This results in better fitting curves than the constant intervals + * (all entries are 4) + */ +static constexpr std::array kLoglikeIntervals = { + { 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6 } +}; + +WideDynamicRange::WideDynamicRange() +{ +} + +/** + * \copydoc libcamera::ipa::Algorithm::init + */ +int WideDynamicRange::init([[maybe_unused]] IPAContext &context, + [[maybe_unused]] const YamlObject &tuningData) +{ + if (!(context.hw->supportedBlocks & 1 << RKISP1_EXT_PARAMS_BLOCK_TYPE_WDR)) { + LOG(RkISP1Wdr, Error) + << "Wide Dynamic Range not supported by the hardware or kernel."; + return -ENOTSUP; + } + + toneCurveIntervalValues_ = kLoglikeIntervals; + + /* Calculate a list of normed x values */ + toneCurveX_[0] = 0.0; + int lastValue = 0; + for (unsigned int i = 1; i < toneCurveX_.size(); i++) { + lastValue += std::pow(2, toneCurveIntervalValues_[i - 1] + 3); + lastValue = std::min(lastValue, 4096); + toneCurveX_[i] = lastValue / 4096.0; + } + + strength_ = 1.0; + mode_ = controls::draft::WdrOff; + exposureConstraintMaxBrightPixels_ = 0.02; + exposureConstraintY_ = 0.95; + minExposureValue_ = -4.0; + + const auto &constraint = tuningData["ExposureConstraint"]; + if (!constraint.isDictionary()) { + LOG(RkISP1Wdr, Warning) + << "ExposureConstraint not found in tuning data." + "Using default values MaxBrightPixels: " + << exposureConstraintMaxBrightPixels_ + << " yTarget: " << exposureConstraintY_; + } else { + exposureConstraintMaxBrightPixels_ = + constraint["MaxBrightPixels"] + .get() + .value_or(exposureConstraintMaxBrightPixels_); + exposureConstraintY_ = + constraint["yTarget"] + .get() + .value_or(exposureConstraintY_); + } + + const auto &minExp = tuningData["MinExposureValue"]; + minExposureValue_ = minExp.get().value_or(minExposureValue_); + if (!minExp) { + LOG(RkISP1Wdr, Warning) + << "MinExposureValue not found in tuning data." + " Using default value: " + << minExposureValue_; + } + + context.ctrlMap[&controls::draft::WdrMode] = + ControlInfo(controls::draft::WdrModeValues, controls::draft::WdrOff); + context.ctrlMap[&controls::draft::WdrStrength] = + ControlInfo(0.0f, 2.0f, static_cast(strength_)); + context.ctrlMap[&controls::draft::WdrMaxBrightPixels] = + ControlInfo(0.0f, 1.0f, static_cast(exposureConstraintMaxBrightPixels_)); + + applyCompensationLinear(1.0, 0.0); + + return 0; +} + +void WideDynamicRange::applyHistogramEqualization(double strength) +{ + if (hist_.empty()) + return; + + strength *= 0.65; + + /* + * In a fully equalized histogram, all bins have the same value. Try + * to equalize the histogram by applying a gain or damping depending on + * the distance of the actual bin value from that norm. + */ + std::vector gains; + gains.resize(hist_.size()); + double sum = 0; + double norm = 1.0 / (gains.size()); + for (unsigned i = 0; i < hist_.size(); i++) { + double diff = 1.0 + strength * (hist_[i] - norm) / norm; + gains[i] = diff; + sum += diff; + } + /* Never amplify the last entry. */ + gains.back() = std::max(gains.back(), 1.0); + + double scale = gains.size() / sum; + for (auto &v : gains) + v *= scale; + + Pwl pwl; + double step = 1.0 / gains.size(); + double lastX = 0; + double lastY = 0; + + pwl.append(lastX, lastY); + for (unsigned int i = 0; i < gains.size() - 1; i++) { + lastY += gains[i] * step; + lastX += step; + pwl.append(lastX, lastY); + } + pwl.append(1.0, 1.0); + + for (unsigned int i = 0; i < toneCurveX_.size(); i++) + toneCurveY_[i] = pwl.eval(toneCurveX_[i]); +} + +Vector WideDynamicRange::kneePoint(double gain, double strength) +{ + gain = std::pow(gain, strength); + double y = 0.5; + double x = y / gain; + + return { { x, y } }; +} + +void WideDynamicRange::applyCompensationLinear(double gain, double strength) +{ + auto kp = kneePoint(gain, strength); + double g1 = kp.y() / kp.x(); + double g2 = (kp.y() - 1) / (kp.x() - 1); + + for (unsigned int i = 0; i < toneCurveX_.size(); i++) { + double x = toneCurveX_[i]; + double y; + if (x <= kp.x()) { + y = g1 * x; + } else { + y = g2 * x + 1 - g2; + } + toneCurveY_[i] = y; + } +} + +void WideDynamicRange::applyCompensationPower(double gain, double strength) +{ + double e = 1.0; + if (strength > 1e-6) { + auto kp = kneePoint(gain, strength); + /* Calculate an exponent to go through the knee point. */ + e = log(kp.y()) / log(kp.x()); + } + + for (unsigned int i = 0; i < toneCurveX_.size(); i++) + toneCurveY_[i] = std::pow(toneCurveX_[i], e); +} + +void WideDynamicRange::applyCompensationExponential(double gain, double strength) +{ + double k = 0.1; + auto kp = kneePoint(gain, strength); + double kx = kp.x(); + double ky = kp.y(); + + if (kx > ky) { + LOG(RkISP1Wdr, Warning) << "Invalid knee point: " << kp; + kx = ky; + } + + /* + * The exponential curve is based on the function proposed by Glozman + * et al. in + * S. Glozman, T. Kats, and O. Yadid-Pecht, "Exponent Operator Based + * Tone Mapping Algorithm for Color Wide Dynamic Range Images," 2011. + * + * That function uses a k factor as parameter for the WDR compression + * curve: + * k=0: maximum compression + * k=infinity: linear curve + * + * To calculate a k factor that results in a curve that passes through + * the kneepoint, the equation needs to be solved for k after inserting + * the kneepoint. This can be formulated as search for a zero point. + * Unfortunately there is no closed solution for that transformation. + * Using newton's method to approximate the value is numerically + * unstable. + * + * Luckily the function only crosses the x axis once and for the set of + * possible kneepoints, a negative and a positive point can be guessed. + * The approximation is then implemented using bisection. + */ + if (std::abs(kx - ky) < 0.001) { + k = 1e8; + } else { + double kl = 0.0001; + double kh = 1000; + + auto fk = [=](double v) { + return std::exp(-kx / v) - + ky * std::exp(-1.0 / v) + ky - 1.0; + }; + + ASSERT(fk(kl) < 0); + ASSERT(fk(kh) > 0); + + k = kh / 10.0; + while (fk(k) > 0) { + kh = k; + k /= 10.0; + } + + do { + k = (kl + kh) / 2; + if (fk(k) < 0) + kl = k; + else + kh = k; + } while (std::abs(kh - kl) > 1e-3); + } + + double a = 1.0 / (1.0 - std::exp(-1.0 / k)); + for (unsigned int i = 0; i < toneCurveX_.size(); i++) + toneCurveY_[i] = a * (1.0 - std::exp(-toneCurveX_[i] / k)); +} + +/** + * \copydoc libcamera::ipa::Algorithm::queueRequest + */ +void WideDynamicRange::queueRequest([[maybe_unused]] IPAContext &context, + [[maybe_unused]] const uint32_t frame, + IPAFrameContext &frameContext, + const ControlList &controls) +{ + strength_ = controls.get(controls::draft::WdrStrength).value_or(strength_); + exposureConstraintMaxBrightPixels_ = + controls.get(controls::draft::WdrMaxBrightPixels) + .value_or(exposureConstraintMaxBrightPixels_); + + const auto &mode = controls.get(controls::draft::WdrMode); + if (mode) { + mode_ = static_cast(*mode); + } + + frameContext.wdr.mode = mode_; + frameContext.wdr.strength = strength_; +} + +/** + * \copydoc libcamera::ipa::Algorithm::prepare + */ +void WideDynamicRange::prepare(IPAContext &context, + [[maybe_unused]] const uint32_t frame, + IPAFrameContext &frameContext, + RkISP1Params *params) +{ + if (!params) { + LOG(RkISP1Wdr, Warning) << "Params is null"; + return; + } + + auto config = params->block(); + + auto mode = frameContext.wdr.mode; + + config.setEnabled(mode != controls::draft::WdrOff); + + double comp = 0; + + /* + * Todo: This overwrites frameContext.agc.exposureValue so that + * in the next call to Agc::process() that exposureValue get's + * applied. In the future it is planned to move the exposure + * calculations from Agc::process() to Agc::prepare(). In this + * case, we need to ensure that this code get's called early enough. + */ + if (mode != controls::draft::WdrOff) { + frameContext.wdr.wdrExposureValue = context.activeState.wdr.exposureValue; + frameContext.wdr.agcExposureValue = frameContext.agc.exposureValue; + + /* + * When WDR is enabled, the maxBrightPixels constraint is always + * active. This is problematic when the user sets a positive + * exposureValue. As this would mean that the negative WDR + * exposure value and the user provided positive value should + * cancel each other out. But as the regulation is not absolute + * and only dependent on the measured changes in the histogram, + * reducing the wdr EV would only lead to an even stronger pull + * from regulation. Positive user supplied EVs must therefore be + * handled using the wdr curve. + */ + if (frameContext.wdr.wdrExposureValue < 0) { + frameContext.agc.exposureValue = + std::min(frameContext.agc.exposureValue, + frameContext.wdr.wdrExposureValue); + comp = frameContext.agc.exposureValue - frameContext.wdr.agcExposureValue; + } + } + + /* Calculate how much EV we need to compensate with the WDR curve. */ + double gain = pow(2.0, -comp); + + if (mode == controls::draft::WdrOff) { + applyCompensationLinear(1.0, 0.0); + } else if (mode == controls::draft::WdrLinear) { + applyCompensationLinear(gain, frameContext.wdr.strength); + } else if (mode == controls::draft::WdrPower) { + applyCompensationPower(gain, frameContext.wdr.strength); + } else if (mode == controls::draft::WdrExponential) { + applyCompensationExponential(gain, frameContext.wdr.strength); + } else if (mode == controls::draft::WdrHistogramEqualization) { + applyHistogramEqualization(frameContext.wdr.strength); + } + + /* Reset value */ + config->dmin_strength = 0x10; + config->dmin_thresh = 0; + + for (unsigned int i = 0; i < kTonecurveXIntervals; i++) { + int v = toneCurveIntervalValues_[i]; + config->tone_curve.dY[i / 8] |= (v & 0x07) << ((i % 8) * 4); + } + + std::vector debugCurve; + + /* + * Fix the curve to adhere to the hardware constraints. Don't apply a + * constraint on the first element, which is most likely zero anyways. + */ + int lastY = toneCurveY_[0] * 4096.0; + for (unsigned int i = 0; i < toneCurveX_.size(); i++) { + int diff = static_cast(toneCurveY_[i] * 4096.0) - lastY; + diff = std::clamp(diff, -2048, 2048); + lastY = lastY + diff; + config->tone_curve.ym[i] = lastY; + debugCurve.push_back({ static_cast(toneCurveX_[i] * 4096.0), + lastY }); + } + + context.debugMetadata.set>(controls::debug::WdrCurve, debugCurve); +} + +void WideDynamicRange::process(IPAContext &context, [[maybe_unused]] const uint32_t frame, + IPAFrameContext &frameContext, + const rkisp1_stat_buffer *stats, + ControlList &metadata) +{ + if (!stats || !(stats->meas_type & RKISP1_CIF_ISP_STAT_HIST)) { + LOG(RkISP1Wdr, Error) << "No histogram data in statistics"; + return; + } + + if (!started_) { + started_ = true; + pid_.setStandardParameters(1, 5.0, 3.0); + pid_.setOutputLimits(minExposureValue_, 0.0); + context.activeState.wdr.exposureValue = 0.0; + } + + pid_.setTarget(exposureConstraintY_); + + const rkisp1_cif_isp_stat *params = &stats->params; + auto mode = frameContext.wdr.mode; + + metadata.set(controls::draft::WdrMode, mode); + + Histogram cumHist({ params->hist.hist_bins, context.hw->numHistogramBins }, + [](uint32_t x) { return x >> 4; }); + + std::vector hist; + double sum = 0; + for (unsigned i = 0; i < context.hw->numHistogramBins; i++) { + double v = params->hist.hist_bins[i] >> 4; + hist.push_back(v); + sum += v; + } + + /* Scale so that the entries sum up to 1. */ + double scale = 1.0 / sum; + for (auto &v : hist) + v *= scale; + hist_.swap(hist); + + double mean = cumHist.quantile(1.0 - exposureConstraintMaxBrightPixels_) / + cumHist.bins(); + LOG(RkISP1Wdr, Debug) << "Mean y of bright pixels: " << mean; + + if (mode == controls::draft::WdrOff) { + metadata.set(controls::draft::WdrExposureValue, 0); + return; + } + + context.activeState.wdr.exposureValue = pid_.process(mean); + LOG(RkISP1Wdr, Debug) << "Active state WDR ev: " << context.activeState.wdr.exposureValue; + metadata.set(controls::draft::WdrExposureValue, frameContext.wdr.wdrExposureValue); + + /* + * We overwrote agc exposure value in prepare() to create an + * underexposure for WDR. Report the original exposure value in metadata. + */ + metadata.set(controls::ExposureValue, frameContext.wdr.agcExposureValue); +} + +REGISTER_IPA_ALGORITHM(WideDynamicRange, "WideDynamicRange") + +} /* namespace ipa::rkisp1::algorithms */ + +} /* namespace libcamera */ diff --git a/src/ipa/rkisp1/algorithms/wdr.h b/src/ipa/rkisp1/algorithms/wdr.h new file mode 100644 index 000000000000..bdea4eb5492a --- /dev/null +++ b/src/ipa/rkisp1/algorithms/wdr.h @@ -0,0 +1,64 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2021-2022, Ideas On Board + * + * RkISP1 Wide Dynamic Range control + */ + +#pragma once + +#include + +#include "libcamera/internal/pid_controller.h" + +#include "linux/rkisp1-config.h" + +#include "algorithm.h" + +namespace libcamera { + +namespace ipa::rkisp1::algorithms { + +class WideDynamicRange : public Algorithm +{ +public: + WideDynamicRange(); + ~WideDynamicRange() = default; + + int init(IPAContext &context, const YamlObject &tuningData) override; + + void queueRequest(IPAContext &context, const uint32_t frame, + IPAFrameContext &frameContext, + const ControlList &controls) override; + void prepare(IPAContext &context, const uint32_t frame, + IPAFrameContext &frameContext, + RkISP1Params *params) override; + void process(IPAContext &context, const uint32_t frame, + IPAFrameContext &frameContext, + const rkisp1_stat_buffer *stats, + ControlList &metadata) override; + +private: + Vector kneePoint(double gain, double strength); + void applyCompensationLinear(double gain, double strength); + void applyCompensationPower(double gain, double strength); + void applyCompensationExponential(double gain, double strength); + void applyHistogramEqualization(double strength); + + double exposureConstraintMaxBrightPixels_; + double exposureConstraintY_; + double minExposureValue_; + double strength_; + bool started_ = false; + + controls::draft::WdrModeEnum mode_; + std::vector hist_; + PidController pid_; + + std::array toneCurveIntervalValues_; + std::array toneCurveX_; + std::array toneCurveY_; +}; + +} /* namespace ipa::rkisp1::algorithms */ +} /* namespace libcamera */ diff --git a/src/ipa/rkisp1/ipa_context.h b/src/ipa/rkisp1/ipa_context.h index 60cfab228edf..32f6db30bbdb 100644 --- a/src/ipa/rkisp1/ipa_context.h +++ b/src/ipa/rkisp1/ipa_context.h @@ -130,6 +130,10 @@ struct IPAActiveState { struct { double gamma; } goc; + + struct { + double exposureValue; + } wdr; }; struct IPAFrameContext : public FrameContext { @@ -198,6 +202,13 @@ struct IPAFrameContext : public FrameContext { struct { double lux; } lux; + + struct { + controls::draft::WdrModeEnum mode; + double wdrExposureValue; + double agcExposureValue; + double strength; + } wdr; }; struct IPAContext { diff --git a/src/ipa/rkisp1/params.cpp b/src/ipa/rkisp1/params.cpp index 4c0b051ce65d..5edb36c91b87 100644 --- a/src/ipa/rkisp1/params.cpp +++ b/src/ipa/rkisp1/params.cpp @@ -74,6 +74,7 @@ const std::map kBlockTypeInfo = { RKISP1_BLOCK_TYPE_ENTRY_EXT(CompandBls, COMPAND_BLS, compand_bls), RKISP1_BLOCK_TYPE_ENTRY_EXT(CompandExpand, COMPAND_EXPAND, compand_curve), RKISP1_BLOCK_TYPE_ENTRY_EXT(CompandCompress, COMPAND_COMPRESS, compand_curve), + RKISP1_BLOCK_TYPE_ENTRY_EXT(Wdr, WDR, wdr), }; } /* namespace */ diff --git a/src/ipa/rkisp1/params.h b/src/ipa/rkisp1/params.h index 40450e34497a..2e60528d102e 100644 --- a/src/ipa/rkisp1/params.h +++ b/src/ipa/rkisp1/params.h @@ -40,6 +40,7 @@ enum class BlockType { CompandBls, CompandExpand, CompandCompress, + Wdr, }; namespace details { @@ -74,6 +75,7 @@ RKISP1_DEFINE_BLOCK_TYPE(Afc, afc) RKISP1_DEFINE_BLOCK_TYPE(CompandBls, compand_bls) RKISP1_DEFINE_BLOCK_TYPE(CompandExpand, compand_curve) RKISP1_DEFINE_BLOCK_TYPE(CompandCompress, compand_curve) +RKISP1_DEFINE_BLOCK_TYPE(Wdr, wdr) } /* namespace details */ diff --git a/src/libcamera/control_ids_debug.yaml b/src/libcamera/control_ids_debug.yaml index 797532712099..9489e677402e 100644 --- a/src/libcamera/control_ids_debug.yaml +++ b/src/libcamera/control_ids_debug.yaml @@ -3,4 +3,9 @@ %YAML 1.1 --- vendor: debug -controls: [] +controls: +- WdrCurve: + type: Point + direction: out + description: Debug control WdrCurve found in src/ipa/rkisp1/algorithms/wdr.cpp + size: '[n]' diff --git a/src/libcamera/control_ids_draft.yaml b/src/libcamera/control_ids_draft.yaml index 03309eeac34f..0c0af7a19968 100644 --- a/src/libcamera/control_ids_draft.yaml +++ b/src/libcamera/control_ids_draft.yaml @@ -293,5 +293,75 @@ controls: Currently identical to ANDROID_STATISTICS_FACE_IDS. size: [n] + - WdrMode: + type: int32_t + direction: inout + description: | + Set the WDR mode. + + The WDR mode is used to select the algorithm used for global tone + mapping. It will automatically reduce the exposure time of the sensor + so that there are only a small number of saturated pixels in the image. + The algorithm then compensates for the loss of brightness by applying a + global tone mapping curve to the image. + enum: + - name: WdrOff + value: 0 + description: Wdr is disabled. + - name: WdrLinear + value: 1 + description: + Apply a linear global tone mapping curve. + + The curve with two linear sections is applied. This produces good + results at the expense of a slightly artificial look. + - name: WdrPower + value: 2 + description: | + Apply a power global tone mapping curve. + + This curve has high gain values on the dark areas of an image and + high compression values on the bright area. It therefore tends to + produce noticeable noise artifacts. + - name: WdrExponential + value: 3 + description: | + Apply a exponential global tone mapping curve. + + This curve has lower gain values in dark areas compared to the power + curve but produces a more natural look compared to the linear curve. + It is therefore the best choice for most scenes. + - name: WdrHistogramEqualization + value: 4 + description: | + Apply histogram equalization. + + This curve preserves most of the information of the image at the + expense of a very artificial look. It is therefore best suited for + technical analysis. + - WdrStrength: + type: float + direction: in + description: | + Specify the strength of the wdr algorithm. The exact meaning of this + value is specific to the algorithm in use. Usually a value of 0 means no + global tone mapping is applied. A values of 1 is the default value and + the correct value for most scenes. A value above 1 increases the global + tone mapping effect and can lead to unrealistic image effects. + - WdrMaxBrightPixels: + type: float + direction: in + description: | + Percentage of allowed (nearly) saturated pixels. The WDR algorithm + reduces the WdrExposureValue until the amount of pixels that are close + to saturation is lower than this value. + - WdrExposureValue: + type: float + direction: out + description: | + Reports the Exposure Value that was applied to the AEGC regulation so + that the WdrMaxBrightPixels limit is reached. + + \sa ExposureValue ... From patchwork Fri Aug 8 14:12:54 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Stefan Klug X-Patchwork-Id: 24087 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 B105ABDCC1 for ; Fri, 8 Aug 2025 14:14:32 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 692C96923D; Fri, 8 Aug 2025 16:14:32 +0200 (CEST) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (1024-bit key; unprotected) header.d=ideasonboard.com header.i=@ideasonboard.com header.b="KKn5cGE/"; dkim-atps=neutral Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 282446923B for ; Fri, 8 Aug 2025 16:14:31 +0200 (CEST) Received: from ideasonboard.com (unknown [IPv6:2a00:6020:448c:6c00:3ea1:35ac:90da:a221]) by perceval.ideasonboard.com (Postfix) with UTF8SMTPSA id 2BE3D185B; Fri, 8 Aug 2025 16:13:41 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1754662421; bh=DAsOrqQo5sRtxgjgunrfqnSNdeLD/rvz9FtghQV16sk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=KKn5cGE/OlUcQKKro0yeXfcKQxlffmgoKAOYDKYSQCkrwxgM24Qr0azg9bOso5Ruy X8OfZL3z/CdOUph8jKWvoeYi1lsMv1jc4C0UYXAM0EPzHJovV43P+9pSQnNlEGjya8 zk2Lf2+YSeda2c8tfWcftNeyhN0dpJopH9BUENSE= From: Stefan Klug To: libcamera-devel@lists.libcamera.org Cc: Stefan Klug , Paul Elder Subject: [PATCH v2 16/16] tuning: rksip1: Add a static WideDynamicRange entry Date: Fri, 8 Aug 2025 16:12:54 +0200 Message-ID: <20250808141315.413839-17-stefan.klug@ideasonboard.com> X-Mailer: git-send-email 2.48.1 In-Reply-To: <20250808141315.413839-1-stefan.klug@ideasonboard.com> References: <20250808141315.413839-1-stefan.klug@ideasonboard.com> MIME-Version: 1.0 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: , Errors-To: libcamera-devel-bounces@lists.libcamera.org Sender: "libcamera-devel" Add a static WideDynamicRange entry that gets added by default. Signed-off-by: Stefan Klug Reviewed-by: Paul Elder Reviewed-by: Kieran Bingham --- Changes in v3: - Collected tag --- utils/tuning/rkisp1.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/utils/tuning/rkisp1.py b/utils/tuning/rkisp1.py index 179d920c05df..2e6f70401fc4 100755 --- a/utils/tuning/rkisp1.py +++ b/utils/tuning/rkisp1.py @@ -48,16 +48,19 @@ lsc = LSCRkISP1(debug=[lt.Debug.Plot], # values. This can also be a custom function. smoothing_function=lt.smoothing.MedianBlur(3),) lux = LuxRkISP1(debug=[lt.Debug.Plot]) +wdr = StaticModule('WideDynamicRange', + {'ExposureConstraint': {'MaxBrightPixels': 0.02, 'yTarget': 0.95}, + 'MinExposureValue': -4.0}) tuner = lt.Tuner('RkISP1') -tuner.add([agc, awb, blc, ccm, color_processing, filter, gamma_out, lsc, lux, compress]) +tuner.add([agc, awb, blc, ccm, color_processing, filter, gamma_out, lsc, lux, wdr, compress]) tuner.set_input_parser(YamlParser()) tuner.set_output_formatter(YamlOutput()) # Bayesian AWB uses the lux value, so insert the lux algorithm before AWB. # Compress is parameterized by others, so add it at the end. tuner.set_output_order([agc, lux, awb, blc, ccm, color_processing, - filter, gamma_out, lsc, compress]) + filter, gamma_out, lsc, wdr, compress]) if __name__ == '__main__': sys.exit(tuner.run(sys.argv))