Show a patch.

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

{
    "id": 17865,
    "url": "https://patchwork.libcamera.org/api/patches/17865/?format=api",
    "web_url": "https://patchwork.libcamera.org/patch/17865/",
    "project": {
        "id": 1,
        "url": "https://patchwork.libcamera.org/api/projects/1/?format=api",
        "name": "libcamera",
        "link_name": "libcamera",
        "list_id": "libcamera_core",
        "list_email": "libcamera-devel@lists.libcamera.org",
        "web_url": "",
        "scm_url": "",
        "webscm_url": ""
    },
    "msgid": "<20221124103832.6172-5-naush@raspberrypi.com>",
    "date": "2022-11-24T10:38:31",
    "name": "[libcamera-devel,v2,4/5] ipa: raspberrypi: Use the generic statistics structure in the algorithms",
    "commit_ref": null,
    "pull_url": null,
    "state": "superseded",
    "archived": false,
    "hash": "5943321718524bb1307bcaa2d01ff74defc7dee6",
    "submitter": {
        "id": 34,
        "url": "https://patchwork.libcamera.org/api/people/34/?format=api",
        "name": "Naushir Patuck",
        "email": "naush@raspberrypi.com"
    },
    "delegate": null,
    "mbox": "https://patchwork.libcamera.org/patch/17865/mbox/",
    "series": [
        {
            "id": 3635,
            "url": "https://patchwork.libcamera.org/api/series/3635/?format=api",
            "web_url": "https://patchwork.libcamera.org/project/libcamera/list/?series=3635",
            "date": "2022-11-24T10:38:27",
            "name": "Raspberry Pi: Generalise statistics",
            "version": 2,
            "mbox": "https://patchwork.libcamera.org/series/3635/mbox/"
        }
    ],
    "comments": "https://patchwork.libcamera.org/api/patches/17865/comments/",
    "check": "pending",
    "checks": "https://patchwork.libcamera.org/api/patches/17865/checks/",
    "tags": {},
    "headers": {
        "Return-Path": "<libcamera-devel-bounces@lists.libcamera.org>",
        "X-Original-To": "parsemail@patchwork.libcamera.org",
        "Delivered-To": "parsemail@patchwork.libcamera.org",
        "Received": [
            "from lancelot.ideasonboard.com (lancelot.ideasonboard.com\n\t[92.243.16.209])\n\tby patchwork.libcamera.org (Postfix) with ESMTPS id E60A5BDE6B\n\tfor <parsemail@patchwork.libcamera.org>;\n\tThu, 24 Nov 2022 10:38:47 +0000 (UTC)",
            "from lancelot.ideasonboard.com (localhost [IPv6:::1])\n\tby lancelot.ideasonboard.com (Postfix) with ESMTP id A522063325;\n\tThu, 24 Nov 2022 11:38:47 +0100 (CET)",
            "from mail-wr1-x42f.google.com (mail-wr1-x42f.google.com\n\t[IPv6:2a00:1450:4864:20::42f])\n\tby lancelot.ideasonboard.com (Postfix) with ESMTPS id 797D263316\n\tfor <libcamera-devel@lists.libcamera.org>;\n\tThu, 24 Nov 2022 11:38:43 +0100 (CET)",
            "by mail-wr1-x42f.google.com with SMTP id q7so961316wrr.8\n\tfor <libcamera-devel@lists.libcamera.org>;\n\tThu, 24 Nov 2022 02:38:43 -0800 (PST)",
            "from naush-laptop.localdomain ([93.93.133.154])\n\tby smtp.gmail.com with ESMTPSA id\n\ts16-20020adff810000000b002368a6deaf8sm995103wrp.57.2022.11.24.02.38.41\n\t(version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256);\n\tThu, 24 Nov 2022 02:38:42 -0800 (PST)"
        ],
        "DKIM-Signature": [
            "v=1; a=rsa-sha256; c=relaxed/simple; d=libcamera.org;\n\ts=mail; t=1669286327;\n\tbh=WNBUmKaA8eAmX6ziSmJ7c/VJTmbjFr0YF+ETxqbfW8E=;\n\th=To:Date:In-Reply-To:References:Subject:List-Id:List-Unsubscribe:\n\tList-Archive:List-Post:List-Help:List-Subscribe:From:Reply-To:\n\tFrom;\n\tb=yslVjMMLcYg6q1Xi7bbtC45aaFnA+jr5uGzcjGUBPYay/9M3ZIHAzP2SZmnJWrYL/\n\tngmvTlHqZZPvn/nZLzxOPShZ5Cq76AzaFtgkQE/M3YKaNJGME1OyEA4OtTOdfUi3Mo\n\tDkpgz2ubuV5rY8zMDCZBzOpUxD3gI40xpNvdg43U91UVHWrWBFW60NoAFMvAsXkPcf\n\to6QvfFLqsf3y8W6gqR54HskGg9eF1xqmg4Q2MInTnzw5BqQGWVxpONci3nAdXAOGP/\n\tgGYIO7P3dWl+wyB+1SDifRpUHGCbxBFdtXVszmVKwsHyy+XlZ9UK/c2ngznzr0GAk9\n\twVN4+sUtzvBdw==",
            "v=1; a=rsa-sha256; c=relaxed/relaxed;\n\td=raspberrypi.com; s=google;\n\th=content-transfer-encoding:mime-version:references:in-reply-to\n\t:message-id:date:subject:cc:to:from:from:to:cc:subject:date\n\t:message-id:reply-to;\n\tbh=6KA1x2/XLmduJUFV1jLTJqy+rDVS3k4ooI+vQMQQH0A=;\n\tb=Zhb/Z6diXwbhYFqSlRAnFrhBA086eIfkkB3aM9QLf56TxbmtvXwHub7a03ZaJNuHAf\n\tzIX3MjrZqDd6UT61C7hKYjNHFjOMkQsBhTvaNnaOtfNuU19LodOQjbZUvAy3EhEOjQl9\n\tQSeC0TzZZL8/ge8up9ehrGkOQPS8aR7mVbBEbDkGAOUFO+dD/R6wIJ7QX35IPBuuJOte\n\tfnyB6VZKTg3//n+zTMAN0iUvy/YMyz34YdL3xDPQlEqU834hIgy+EyHbCxhAyOSWwNbs\n\tugCCf4pAgFedcD6+21rKKgu5hAaHcujlUX9L4pZAdBWJongpqcIv2LqPpE1xTTQjP3Fl\n\tQ7yQ=="
        ],
        "Authentication-Results": "lancelot.ideasonboard.com; dkim=pass (2048-bit key; \n\tunprotected) header.d=raspberrypi.com\n\theader.i=@raspberrypi.com\n\theader.b=\"Zhb/Z6di\"; dkim-atps=neutral",
        "X-Google-DKIM-Signature": "v=1; a=rsa-sha256; c=relaxed/relaxed;\n\td=1e100.net; s=20210112;\n\th=content-transfer-encoding:mime-version:references:in-reply-to\n\t:message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc\n\t:subject:date:message-id:reply-to;\n\tbh=6KA1x2/XLmduJUFV1jLTJqy+rDVS3k4ooI+vQMQQH0A=;\n\tb=YOCZb7OJdpCN9vHgJ31uYyqNsnCfDTSehPVJeSYbf5ExTpX/UYTLsc1P8UfdTgQS0Q\n\tzYbzS58GU5OShAiwqei0xsc3uSkW+436lcCjxdq7sFlzGLkfhKNnxVZa2g9B8topeZEP\n\teiBBCmzMWrX7u4REF6EMFxlG8Fly0wVqO/DYWVpIKuLysO9/e1zhFBmjg5J2pDIZ5Dbh\n\tXjXYHWvSRTGX+Fny47X7k+UZ7XgYq5xzOovdghO2Gd3DXaFJ3p1WpUxhR6cQM5u3GtkL\n\t5cguD6LOSlWsUadFQHJM8X3MXEKZwUMwCTXSiCk+8GIjkvjcI3iO40/xVjRZ/BJPMLfD\n\tmYkQ==",
        "X-Gm-Message-State": "ANoB5pkjQ7bf6ctnst2lLPsczURRxFfxWm52M8LopebQlJcRCefWT4vV\n\ta5uau9s0mmDnF6fjnJZDRY+z4x1UVsavFg==",
        "X-Google-Smtp-Source": "AA0mqf4fl34p7vv2eIM7eQi5l/NuwBJ9JoBZtLsOPbLS8JNt0ZRe8CGffu/QdGbSsMroN6DhtyvZBA==",
        "X-Received": "by 2002:adf:ebc5:0:b0:241:6c90:79e9 with SMTP id\n\tv5-20020adfebc5000000b002416c9079e9mr4179878wrn.642.1669286322575; \n\tThu, 24 Nov 2022 02:38:42 -0800 (PST)",
        "To": "libcamera-devel@lists.libcamera.org",
        "Date": "Thu, 24 Nov 2022 10:38:31 +0000",
        "Message-Id": "<20221124103832.6172-5-naush@raspberrypi.com>",
        "X-Mailer": "git-send-email 2.25.1",
        "In-Reply-To": "<20221124103832.6172-1-naush@raspberrypi.com>",
        "References": "<20221124103832.6172-1-naush@raspberrypi.com>",
        "MIME-Version": "1.0",
        "Content-Transfer-Encoding": "8bit",
        "Subject": "[libcamera-devel] [PATCH v2 4/5] ipa: raspberrypi: Use the generic\n\tstatistics structure in the algorithms",
        "X-BeenThere": "libcamera-devel@lists.libcamera.org",
        "X-Mailman-Version": "2.1.29",
        "Precedence": "list",
        "List-Id": "<libcamera-devel.lists.libcamera.org>",
        "List-Unsubscribe": "<https://lists.libcamera.org/options/libcamera-devel>,\n\t<mailto:libcamera-devel-request@lists.libcamera.org?subject=unsubscribe>",
        "List-Archive": "<https://lists.libcamera.org/pipermail/libcamera-devel/>",
        "List-Post": "<mailto:libcamera-devel@lists.libcamera.org>",
        "List-Help": "<mailto:libcamera-devel-request@lists.libcamera.org?subject=help>",
        "List-Subscribe": "<https://lists.libcamera.org/listinfo/libcamera-devel>,\n\t<mailto:libcamera-devel-request@lists.libcamera.org?subject=subscribe>",
        "From": "Naushir Patuck via libcamera-devel\n\t<libcamera-devel@lists.libcamera.org>",
        "Reply-To": "Naushir Patuck <naush@raspberrypi.com>",
        "Errors-To": "libcamera-devel-bounces@lists.libcamera.org",
        "Sender": "\"libcamera-devel\" <libcamera-devel-bounces@lists.libcamera.org>"
    },
    "content": "Repurpose the StatisticsPtr type from being a shared_ptr<bcm2835_isp_stats> to\nshared_ptr<RPiController::Statistics>. This removes any hardware specific header\nfiles and structures from the algorithms source code.\n\nAdd a new function in the Raspberry Pi IPA to populate the generic statistics\nstructure from the values provided by the hardware in the bcm2835_isp_stats\nstructure.\n\nUpdate the Lux, AWB, AGC, ALSC, Contrast, and Focus algorithms to use the\ngeneric statistics structure appropriately in their calculations. Additionally,\nremove references to any hardware specific headers and defines in these source\nfiles.\n\nSigned-off-by: Naushir Patuck <naush@raspberrypi.com>\n---\n src/ipa/raspberrypi/controller/controller.h   |  4 +-\n src/ipa/raspberrypi/controller/rpi/agc.cpp    | 27 +++++-------\n src/ipa/raspberrypi/controller/rpi/agc.h      |  2 +-\n src/ipa/raspberrypi/controller/rpi/alsc.cpp   | 32 +++++++-------\n src/ipa/raspberrypi/controller/rpi/alsc.h     |  3 +-\n src/ipa/raspberrypi/controller/rpi/awb.cpp    | 20 ++++-----\n src/ipa/raspberrypi/controller/rpi/awb.h      |  1 +\n .../raspberrypi/controller/rpi/contrast.cpp   |  8 ++--\n src/ipa/raspberrypi/controller/rpi/focus.cpp  |  7 ++-\n src/ipa/raspberrypi/controller/rpi/lux.cpp    | 14 +-----\n src/ipa/raspberrypi/raspberrypi.cpp           | 44 ++++++++++++++++++-\n src/ipa/raspberrypi/statistics.h              |  2 +\n 12 files changed, 96 insertions(+), 68 deletions(-)",
    "diff": "diff --git a/src/ipa/raspberrypi/controller/controller.h b/src/ipa/raspberrypi/controller/controller.h\nindex 3e1e051703b3..e6c950c3a509 100644\n--- a/src/ipa/raspberrypi/controller/controller.h\n+++ b/src/ipa/raspberrypi/controller/controller.h\n@@ -15,19 +15,17 @@\n #include <vector>\n #include <string>\n \n-#include <linux/bcm2835-isp.h>\n-\n #include \"libcamera/internal/yaml_parser.h\"\n \n #include \"camera_mode.h\"\n #include \"device_status.h\"\n #include \"metadata.h\"\n+#include \"statistics.h\"\n \n namespace RPiController {\n \n class Algorithm;\n typedef std::unique_ptr<Algorithm> AlgorithmPtr;\n-typedef std::shared_ptr<bcm2835_isp_stats> StatisticsPtr;\n \n /*\n  * The Controller holds a pointer to some global_metadata, which is how\ndiff --git a/src/ipa/raspberrypi/controller/rpi/agc.cpp b/src/ipa/raspberrypi/controller/rpi/agc.cpp\nindex bd54a639d637..a7f0e954407d 100644\n--- a/src/ipa/raspberrypi/controller/rpi/agc.cpp\n+++ b/src/ipa/raspberrypi/controller/rpi/agc.cpp\n@@ -9,8 +9,6 @@\n #include <map>\n #include <tuple>\n \n-#include <linux/bcm2835-isp.h>\n-\n #include <libcamera/base/log.h>\n \n #include \"../awb_status.h\"\n@@ -450,7 +448,7 @@ void Agc::process(StatisticsPtr &stats, Metadata *imageMetadata)\n \tfetchCurrentExposure(imageMetadata);\n \t/* Compute the total gain we require relative to the current exposure. */\n \tdouble gain, targetY;\n-\tcomputeGain(stats.get(), imageMetadata, gain, targetY);\n+\tcomputeGain(stats, imageMetadata, gain, targetY);\n \t/* Now compute the target (final) exposure which we think we want. */\n \tcomputeTargetExposure(gain);\n \t/*\n@@ -584,24 +582,23 @@ void Agc::fetchAwbStatus(Metadata *imageMetadata)\n \t\tLOG(RPiAgc, Debug) << \"No AWB status found\";\n }\n \n-static double computeInitialY(bcm2835_isp_stats *stats, AwbStatus const &awb,\n+static double computeInitialY(StatisticsPtr &stats, AwbStatus const &awb,\n \t\t\t      double weights[], double gain)\n {\n-\tbcm2835_isp_stats_region *regions = stats->agc_stats;\n \t/*\n \t * Note how the calculation below means that equal weights give you\n \t * \"average\" metering (i.e. all pixels equally important).\n \t */\n \tdouble rSum = 0, gSum = 0, bSum = 0, pixelSum = 0;\n-\tfor (unsigned int i = 0; i < AgcStatsSize; i++) {\n-\t\tdouble counted = regions[i].counted;\n-\t\tdouble rAcc = std::min(regions[i].r_sum * gain, ((1 << PipelineBits) - 1) * counted);\n-\t\tdouble gAcc = std::min(regions[i].g_sum * gain, ((1 << PipelineBits) - 1) * counted);\n-\t\tdouble bAcc = std::min(regions[i].b_sum * gain, ((1 << PipelineBits) - 1) * counted);\n+\tfor (unsigned int i = 0; i < stats->agcRegions.numRegions(); i++) {\n+\t\tauto &region = stats->agcRegions.get(i);\n+\t\tdouble rAcc = std::min<double>(region.val.rSum * gain, ((1 << PipelineBits) - 1) * region.counted);\n+\t\tdouble gAcc = std::min<double>(region.val.gSum * gain, ((1 << PipelineBits) - 1) * region.counted);\n+\t\tdouble bAcc = std::min<double>(region.val.bSum * gain, ((1 << PipelineBits) - 1) * region.counted);\n \t\trSum += rAcc * weights[i];\n \t\tgSum += gAcc * weights[i];\n \t\tbSum += bAcc * weights[i];\n-\t\tpixelSum += counted * weights[i];\n+\t\tpixelSum += region.counted * weights[i];\n \t}\n \tif (pixelSum == 0.0) {\n \t\tLOG(RPiAgc, Warning) << \"computeInitialY: pixelSum is zero\";\n@@ -623,23 +620,23 @@ static double computeInitialY(bcm2835_isp_stats *stats, AwbStatus const &awb,\n \n static constexpr double EvGainYTargetLimit = 0.9;\n \n-static double constraintComputeGain(AgcConstraint &c, Histogram &h, double lux,\n+static double constraintComputeGain(AgcConstraint &c, const Histogram &h, double lux,\n \t\t\t\t    double evGain, double &targetY)\n {\n \ttargetY = c.yTarget.eval(c.yTarget.domain().clip(lux));\n \ttargetY = std::min(EvGainYTargetLimit, targetY * evGain);\n \tdouble iqm = h.interQuantileMean(c.qLo, c.qHi);\n-\treturn (targetY * NUM_HISTOGRAM_BINS) / iqm;\n+\treturn (targetY * h.bins()) / iqm;\n }\n \n-void Agc::computeGain(bcm2835_isp_stats *statistics, Metadata *imageMetadata,\n+void Agc::computeGain(StatisticsPtr &statistics, Metadata *imageMetadata,\n \t\t      double &gain, double &targetY)\n {\n \tstruct LuxStatus lux = {};\n \tlux.lux = 400; /* default lux level to 400 in case no metadata found */\n \tif (imageMetadata->get(\"lux.status\", lux) != 0)\n \t\tLOG(RPiAgc, Warning) << \"No lux level found\";\n-\tHistogram h(statistics->hist[0].g_hist, NUM_HISTOGRAM_BINS);\n+\tconst Histogram &h = statistics->yHist;\n \tdouble evGain = status_.ev * config_.baseEv;\n \t/*\n \t * The initial gain and target_Y come from some of the regions. After\ndiff --git a/src/ipa/raspberrypi/controller/rpi/agc.h b/src/ipa/raspberrypi/controller/rpi/agc.h\nindex 6d6b0e5ad857..0ea71e6d1aa0 100644\n--- a/src/ipa/raspberrypi/controller/rpi/agc.h\n+++ b/src/ipa/raspberrypi/controller/rpi/agc.h\n@@ -98,7 +98,7 @@ private:\n \tvoid housekeepConfig();\n \tvoid fetchCurrentExposure(Metadata *imageMetadata);\n \tvoid fetchAwbStatus(Metadata *imageMetadata);\n-\tvoid computeGain(bcm2835_isp_stats *statistics, Metadata *imageMetadata,\n+\tvoid computeGain(StatisticsPtr &statistics, Metadata *imageMetadata,\n \t\t\t double &gain, double &targetY);\n \tvoid computeTargetExposure(double gain);\n \tbool applyDigitalGain(double gain, double targetY);\ndiff --git a/src/ipa/raspberrypi/controller/rpi/alsc.cpp b/src/ipa/raspberrypi/controller/rpi/alsc.cpp\nindex a4afaf841c41..eb4e2f9496e1 100644\n--- a/src/ipa/raspberrypi/controller/rpi/alsc.cpp\n+++ b/src/ipa/raspberrypi/controller/rpi/alsc.cpp\n@@ -310,19 +310,21 @@ double getCt(Metadata *metadata, double defaultCt)\n \treturn awbStatus.temperatureK;\n }\n \n-static void copyStats(bcm2835_isp_stats_region regions[XY], StatisticsPtr &stats,\n+static void copyStats(RgbyRegions &regions, StatisticsPtr &stats,\n \t\t      AlscStatus const &status)\n {\n-\tbcm2835_isp_stats_region *inputRegions = stats->awb_stats;\n+\tif (!regions.numRegions())\n+\t\tregions.init(stats->awbRegions.size());\n+\n \tdouble *rTable = (double *)status.r;\n \tdouble *gTable = (double *)status.g;\n \tdouble *bTable = (double *)status.b;\n-\tfor (int i = 0; i < XY; i++) {\n-\t\tregions[i].r_sum = inputRegions[i].r_sum / rTable[i];\n-\t\tregions[i].g_sum = inputRegions[i].g_sum / gTable[i];\n-\t\tregions[i].b_sum = inputRegions[i].b_sum / bTable[i];\n-\t\tregions[i].counted = inputRegions[i].counted;\n-\t\t/* (don't care about the uncounted value) */\n+\tfor (unsigned int i = 0; i < stats->awbRegions.numRegions(); i++) {\n+\t\tauto r = stats->awbRegions.get(i);\n+\t\tr.val.rSum = static_cast<uint64_t>(r.val.rSum / rTable[i]);\n+\t\tr.val.gSum = static_cast<uint64_t>(r.val.gSum / gTable[i]);\n+\t\tr.val.bSum = static_cast<uint64_t>(r.val.bSum / bTable[i]);\n+\t\tregions.set(i, r);\n \t}\n }\n \n@@ -512,19 +514,19 @@ void resampleCalTable(double const calTableIn[XY],\n }\n \n /* Calculate chrominance statistics (R/G and B/G) for each region. */\n-static_assert(XY == AWB_REGIONS, \"ALSC/AWB statistics region mismatch\");\n-static void calculateCrCb(bcm2835_isp_stats_region *awbRegion, double cr[XY],\n+static void calculateCrCb(const RgbyRegions &awbRegion, double cr[XY],\n \t\t\t  double cb[XY], uint32_t minCount, uint16_t minG)\n {\n \tfor (int i = 0; i < XY; i++) {\n-\t\tbcm2835_isp_stats_region &zone = awbRegion[i];\n-\t\tif (zone.counted <= minCount ||\n-\t\t    zone.g_sum / zone.counted <= minG) {\n+\t\tauto s = awbRegion.get(i);\n+\n+\t\tif (s.counted <= minCount || s.val.gSum / s.counted <= minG) {\n \t\t\tcr[i] = cb[i] = InsufficientData;\n \t\t\tcontinue;\n \t\t}\n-\t\tcr[i] = zone.r_sum / (double)zone.g_sum;\n-\t\tcb[i] = zone.b_sum / (double)zone.g_sum;\n+\n+\t\tcr[i] = s.val.rSum / (double)s.val.gSum;\n+\t\tcb[i] = s.val.bSum / (double)s.val.gSum;\n \t}\n }\n \ndiff --git a/src/ipa/raspberrypi/controller/rpi/alsc.h b/src/ipa/raspberrypi/controller/rpi/alsc.h\nindex a858ef5a6551..9167c9ffa2e3 100644\n--- a/src/ipa/raspberrypi/controller/rpi/alsc.h\n+++ b/src/ipa/raspberrypi/controller/rpi/alsc.h\n@@ -12,6 +12,7 @@\n \n #include \"../algorithm.h\"\n #include \"../alsc_status.h\"\n+#include \"../statistics.h\"\n \n namespace RPiController {\n \n@@ -98,7 +99,7 @@ private:\n \t/* copy out the results from the async thread so that it can be restarted */\n \tvoid fetchAsyncResults();\n \tdouble ct_;\n-\tbcm2835_isp_stats_region statistics_[AlscCellsY * AlscCellsX];\n+\tRgbyRegions statistics_;\n \tdouble asyncResults_[3][AlscCellsY][AlscCellsX];\n \tdouble asyncLambdaR_[AlscCellsX * AlscCellsY];\n \tdouble asyncLambdaB_[AlscCellsX * AlscCellsY];\ndiff --git a/src/ipa/raspberrypi/controller/rpi/awb.cpp b/src/ipa/raspberrypi/controller/rpi/awb.cpp\nindex 861022014896..c089aedf020c 100644\n--- a/src/ipa/raspberrypi/controller/rpi/awb.cpp\n+++ b/src/ipa/raspberrypi/controller/rpi/awb.cpp\n@@ -21,9 +21,6 @@ LOG_DEFINE_CATEGORY(RPiAwb)\n \n #define NAME \"rpi.awb\"\n \n-static constexpr unsigned int AwbStatsSizeX = DEFAULT_AWB_REGIONS_X;\n-static constexpr unsigned int AwbStatsSizeY = DEFAULT_AWB_REGIONS_Y;\n-\n /*\n  * todo - the locking in this algorithm needs some tidying up as has been done\n  * elsewhere (ALSC and AGC).\n@@ -406,17 +403,16 @@ void Awb::asyncFunc()\n }\n \n static void generateStats(std::vector<Awb::RGB> &zones,\n-\t\t\t  bcm2835_isp_stats_region *stats, double minPixels,\n+\t\t\t  RgbyRegions &stats, double minPixels,\n \t\t\t  double minG)\n {\n-\tfor (unsigned int i = 0; i < AwbStatsSizeX * AwbStatsSizeY; i++) {\n+\tfor (auto const &region : stats) {\n \t\tAwb::RGB zone;\n-\t\tdouble counted = stats[i].counted;\n-\t\tif (counted >= minPixels) {\n-\t\t\tzone.G = stats[i].g_sum / counted;\n+\t\tif (region.counted >= minPixels) {\n+\t\t\tzone.G = region.val.gSum / region.counted;\n \t\t\tif (zone.G >= minG) {\n-\t\t\t\tzone.R = stats[i].r_sum / counted;\n-\t\t\t\tzone.B = stats[i].b_sum / counted;\n+\t\t\t\tzone.R = region.val.rSum / region.counted;\n+\t\t\t\tzone.B = region.val.bSum / region.counted;\n \t\t\t\tzones.push_back(zone);\n \t\t\t}\n \t\t}\n@@ -430,7 +426,7 @@ void Awb::prepareStats()\n \t * LSC has already been applied to the stats in this pipeline, so stop\n \t * any LSC compensation.  We also ignore config_.fast in this version.\n \t */\n-\tgenerateStats(zones_, statistics_->awb_stats, config_.minPixels,\n+\tgenerateStats(zones_, statistics_->awbRegions, config_.minPixels,\n \t\t      config_.minG);\n \t/*\n \t * apply sensitivities, so values appear to come from our \"canonical\"\n@@ -646,7 +642,7 @@ void Awb::awbBayes()\n \t * valid... not entirely sure about this.\n \t */\n \tPwl prior = interpolatePrior();\n-\tprior *= zones_.size() / (double)(AwbStatsSizeX * AwbStatsSizeY);\n+\tprior *= zones_.size() / (double)(statistics_->awbRegions.numRegions());\n \tprior.map([](double x, double y) {\n \t\tLOG(RPiAwb, Debug) << \"(\" << x << \",\" << y << \")\";\n \t});\ndiff --git a/src/ipa/raspberrypi/controller/rpi/awb.h b/src/ipa/raspberrypi/controller/rpi/awb.h\nindex 30acd89d0969..d81779dd51ff 100644\n--- a/src/ipa/raspberrypi/controller/rpi/awb.h\n+++ b/src/ipa/raspberrypi/controller/rpi/awb.h\n@@ -13,6 +13,7 @@\n #include \"../awb_algorithm.h\"\n #include \"../pwl.h\"\n #include \"../awb_status.h\"\n+#include \"../statistics.h\"\n \n namespace RPiController {\n \ndiff --git a/src/ipa/raspberrypi/controller/rpi/contrast.cpp b/src/ipa/raspberrypi/controller/rpi/contrast.cpp\nindex 5b37edcbd46a..a4f8c4f04fc4 100644\n--- a/src/ipa/raspberrypi/controller/rpi/contrast.cpp\n+++ b/src/ipa/raspberrypi/controller/rpi/contrast.cpp\n@@ -106,7 +106,7 @@ Pwl computeStretchCurve(Histogram const &histogram,\n \t * bit.\n \t */\n \tdouble histLo = histogram.quantile(config.loHistogram) *\n-\t\t\t(65536 / NUM_HISTOGRAM_BINS);\n+\t\t\t(65536 / histogram.bins());\n \tdouble levelLo = config.loLevel * 65536;\n \tLOG(RPiContrast, Debug)\n \t\t<< \"Move histogram point \" << histLo << \" to \" << levelLo;\n@@ -119,7 +119,7 @@ Pwl computeStretchCurve(Histogram const &histogram,\n \t * Keep the mid-point (median) in the same place, though, to limit the\n \t * apparent amount of global brightness shift.\n \t */\n-\tdouble mid = histogram.quantile(0.5) * (65536 / NUM_HISTOGRAM_BINS);\n+\tdouble mid = histogram.quantile(0.5) * (65536 / histogram.bins());\n \tenhance.append(mid, mid);\n \n \t/*\n@@ -127,7 +127,7 @@ Pwl computeStretchCurve(Histogram const &histogram,\n \t * there up.\n \t */\n \tdouble histHi = histogram.quantile(config.hiHistogram) *\n-\t\t\t(65536 / NUM_HISTOGRAM_BINS);\n+\t\t\t(65536 / histogram.bins());\n \tdouble levelHi = config.hiLevel * 65536;\n \tLOG(RPiContrast, Debug)\n \t\t<< \"Move histogram point \" << histHi << \" to \" << levelHi;\n@@ -158,7 +158,7 @@ Pwl applyManualContrast(Pwl const &gammaCurve, double brightness,\n void Contrast::process(StatisticsPtr &stats,\n \t\t       [[maybe_unused]] Metadata *imageMetadata)\n {\n-\tHistogram histogram(stats->hist[0].g_hist, NUM_HISTOGRAM_BINS);\n+\tHistogram &histogram = stats->yHist;\n \t/*\n \t * We look at the histogram and adjust the gamma curve in the following\n \t * ways: 1. Adjust the gamma curve so as to pull the start of the\ndiff --git a/src/ipa/raspberrypi/controller/rpi/focus.cpp b/src/ipa/raspberrypi/controller/rpi/focus.cpp\nindex 8c5029bd0e95..ea3cc00e42c3 100644\n--- a/src/ipa/raspberrypi/controller/rpi/focus.cpp\n+++ b/src/ipa/raspberrypi/controller/rpi/focus.cpp\n@@ -31,10 +31,9 @@ char const *Focus::name() const\n void Focus::process(StatisticsPtr &stats, Metadata *imageMetadata)\n {\n \tFocusStatus status;\n-\tunsigned int i;\n-\tfor (i = 0; i < FOCUS_REGIONS; i++)\n-\t\tstatus.focusMeasures[i] = stats->focus_stats[i].contrast_val[1][1] / 1000;\n-\tstatus.num = i;\n+\tfor (unsigned int i = 0; i < stats->focusRegions.numRegions(); i++)\n+\t\tstatus.focusMeasures[i] = stats->focusRegions.get(i).val;\n+\tstatus.num = stats->focusRegions.numRegions();\n \timageMetadata->set(\"focus.status\", status);\n \n \tLOG(RPiFocus, Debug)\ndiff --git a/src/ipa/raspberrypi/controller/rpi/lux.cpp b/src/ipa/raspberrypi/controller/rpi/lux.cpp\nindex 9759186afacf..06625f3a5ea3 100644\n--- a/src/ipa/raspberrypi/controller/rpi/lux.cpp\n+++ b/src/ipa/raspberrypi/controller/rpi/lux.cpp\n@@ -6,8 +6,6 @@\n  */\n #include <math.h>\n \n-#include <linux/bcm2835-isp.h>\n-\n #include <libcamera/base/log.h>\n \n #include \"../device_status.h\"\n@@ -83,20 +81,12 @@ void Lux::process(StatisticsPtr &stats, Metadata *imageMetadata)\n \tif (imageMetadata->get(\"device.status\", deviceStatus) == 0) {\n \t\tdouble currentGain = deviceStatus.analogueGain;\n \t\tdouble currentAperture = deviceStatus.aperture.value_or(currentAperture_);\n-\t\tuint64_t sum = 0;\n-\t\tuint32_t num = 0;\n-\t\tuint32_t *bin = stats->hist[0].g_hist;\n-\t\tconst int numBins = sizeof(stats->hist[0].g_hist) /\n-\t\t\t\t    sizeof(stats->hist[0].g_hist[0]);\n-\t\tfor (int i = 0; i < numBins; i++)\n-\t\t\tsum += bin[i] * (uint64_t)i, num += bin[i];\n-\t\t/* add .5 to reflect the mid-points of bins */\n-\t\tdouble currentY = sum / (double)num + .5;\n+\t\tdouble currentY = stats->yHist.interQuantileMean(0, 1);\n \t\tdouble gainRatio = referenceGain_ / currentGain;\n \t\tdouble shutterSpeedRatio =\n \t\t\treferenceShutterSpeed_ / deviceStatus.shutterSpeed;\n \t\tdouble apertureRatio = referenceAperture_ / currentAperture;\n-\t\tdouble yRatio = currentY * (65536 / numBins) / referenceY_;\n+\t\tdouble yRatio = currentY * (65536 / stats->yHist.bins()) / referenceY_;\n \t\tdouble estimatedLux = shutterSpeedRatio * gainRatio *\n \t\t\t\t      apertureRatio * apertureRatio *\n \t\t\t\t      yRatio * referenceLux_;\ndiff --git a/src/ipa/raspberrypi/raspberrypi.cpp b/src/ipa/raspberrypi/raspberrypi.cpp\nindex b74f1ecf738f..44527357243d 100644\n--- a/src/ipa/raspberrypi/raspberrypi.cpp\n+++ b/src/ipa/raspberrypi/raspberrypi.cpp\n@@ -51,6 +51,7 @@\n #include \"metadata.h\"\n #include \"sharpen_algorithm.h\"\n #include \"sharpen_status.h\"\n+#include \"statistics.h\"\n \n namespace libcamera {\n \n@@ -136,6 +137,7 @@ private:\n \tvoid prepareISP(const ISPConfig &data);\n \tvoid reportMetadata();\n \tvoid fillDeviceStatus(const ControlList &sensorControls);\n+\tRPiController::StatisticsPtr fillStatistics(bcm2835_isp_stats *stats) const;\n \tvoid processStats(unsigned int bufferId);\n \tvoid applyFrameDurations(Duration minFrameDuration, Duration maxFrameDuration);\n \tvoid applyAGC(const struct AgcStatus *agcStatus, ControlList &ctrls);\n@@ -1119,6 +1121,46 @@ void IPARPi::fillDeviceStatus(const ControlList &sensorControls)\n \trpiMetadata_.set(\"device.status\", deviceStatus);\n }\n \n+RPiController::StatisticsPtr IPARPi::fillStatistics(bcm2835_isp_stats *stats) const\n+{\n+\tusing namespace RPiController;\n+\n+\tunsigned int i;\n+\tStatisticsPtr statistics =\n+\t\tstd::make_unique<Statistics>(Statistics::AgcStatsPos::PreWb, Statistics::ColourStatsPos::PostLsc);\n+\n+\t/* RGB histograms are not used, so do not populate them. */\n+\tstatistics->yHist = std::move(RPiController::Histogram(stats->hist[0].g_hist, NUM_HISTOGRAM_BINS));\n+\n+\tstatistics->awbRegions.init({ DEFAULT_AWB_REGIONS_X, DEFAULT_AWB_REGIONS_Y });\n+\tfor (i = 0; i < statistics->awbRegions.numRegions(); i++)\n+\t\tstatistics->awbRegions.set(i, { { stats->awb_stats[i].r_sum,\n+\t\t\t\t\t\t  stats->awb_stats[i].g_sum,\n+\t\t\t\t\t\t  stats->awb_stats[i].b_sum },\n+\t\t\t\t\t\tstats->awb_stats[i].counted,\n+\t\t\t\t\t\tstats->awb_stats[i].notcounted });\n+\n+\t/*\n+\t * There are only ever 15 regions computed by the firmware due to zoning,\n+\t * but the HW defines AGC_REGIONS == 16!\n+\t */\n+\tstatistics->agcRegions.init(15);\n+\tfor (i = 0; i < statistics->agcRegions.numRegions(); i++)\n+\t\tstatistics->agcRegions.set(i, { { stats->agc_stats[i].r_sum,\n+\t\t\t\t\t\t  stats->agc_stats[i].g_sum,\n+\t\t\t\t\t\t  stats->agc_stats[i].b_sum },\n+\t\t\t\t\t\tstats->agc_stats[i].counted,\n+\t\t\t\t\t\tstats->awb_stats[i].notcounted });\n+\n+\tstatistics->focusRegions.init({ 4, 3 });\n+\tfor (i = 0; i < statistics->focusRegions.numRegions(); i++)\n+\t\tstatistics->focusRegions.set(i, { stats->focus_stats[i].contrast_val[1][1] / 1000,\n+\t\t\t\t\t\t  stats->focus_stats[i].contrast_val_num[1][1],\n+\t\t\t\t\t\t  stats->focus_stats[i].contrast_val_num[1][0] });\n+\n+\treturn statistics;\n+}\n+\n void IPARPi::processStats(unsigned int bufferId)\n {\n \tauto it = buffers_.find(bufferId);\n@@ -1129,7 +1171,7 @@ void IPARPi::processStats(unsigned int bufferId)\n \n \tSpan<uint8_t> mem = it->second.planes()[0];\n \tbcm2835_isp_stats *stats = reinterpret_cast<bcm2835_isp_stats *>(mem.data());\n-\tRPiController::StatisticsPtr statistics = std::make_shared<bcm2835_isp_stats>(*stats);\n+\tRPiController::StatisticsPtr statistics = fillStatistics(stats);\n \thelper_->process(statistics, rpiMetadata_);\n \tcontroller_.process(statistics, &rpiMetadata_);\n \ndiff --git a/src/ipa/raspberrypi/statistics.h b/src/ipa/raspberrypi/statistics.h\nindex a762bf3d41aa..affb7272c963 100644\n--- a/src/ipa/raspberrypi/statistics.h\n+++ b/src/ipa/raspberrypi/statistics.h\n@@ -67,4 +67,6 @@ struct Statistics {\n \tFocusRegions focusRegions;\n };\n \n+using StatisticsPtr = std::shared_ptr<Statistics>;\n+\n } /* namespace RPiController */\n",
    "prefixes": [
        "libcamera-devel",
        "v2",
        "4/5"
    ]
}