From patchwork Sun Nov 29 15:24:11 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: =?utf-8?q?Alain_Cousini=C3=A9?= X-Patchwork-Id: 29106 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 7E47FC3360 for ; Sun, 29 Nov 2026 15:24:55 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 20EF16AA43; Sun, 29 Nov 2026 16:24:54 +0100 (CET) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (2048-bit key; unprotected) header.d=laposte.net header.i=@laposte.net header.b="k3du34Xa"; dkim-atps=neutral Received: from smtp-outgoing-1802.laposte.net (smtp-outgoing-1802.laposte.net [160.92.124.103]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 898C06AA2B for ; Sun, 29 Nov 2026 16:24:43 +0100 (CET) X-mail-filterd: {"version":"1.9.7", "queueID":"4jcrYP15wSz10MQN", "contextId": "1b1365f2-eae0-4cb9-9862-fc06179f8740"} Received: from outgoing-mail.laposte.net (localhost.localdomain [127.0.0.1]) by mlpnf0120.laposte.net (SMTP Server) with ESMTP id 4jcrYP15wSz10MQN; Sun, 29 Nov 2026 16:24:41 +0100 (CET) X-mail-filterd: {"version":"1.9.7", "queueID":"4jcrYN5yy4z10MQ4", "contextId": "584c99ca-85a6-4af9-944d-1004623691b3"} X-lpn-mailing: LEGIT X-lpn-spamrating: 36 X-lpn-spamlevel: not-spam Received: from debian.home (m-dj.hd.free.fr [82.67.82.126]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mlpnf0120.laposte.net (SMTP Server) with ESMTPSA id 4jcrYN5yy4z10MQ4; Sun, 29 Nov 2026 16:24:40 +0100 (CET) From: =?utf-8?q?Alain_Cousini=C3=A9?= To: libcamera-devel@lists.libcamera.org, Milan Zamazal Cc: Hans de Goede , Bryan O'Donoghue , =?utf-8?q?Barnab=C3=A1s_P=C5=91cze?= , Laurent Pinchart , Jai Luthra , =?utf-8?q?Alain_Cousini=C3=A9?= Subject: [PATCH v8 1/6] libcamera: software_isp: Add support for monochrome formats - Shader Date: Sun, 29 Nov 2026 16:24:11 +0100 Message-ID: <20261129152416.174279-2-alain.cousinie@laposte.net> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261129152416.174279-1-alain.cousinie@laposte.net> References: <20261129152416.174279-1-alain.cousinie@laposte.net> MIME-Version: 1.0 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=laposte.net; s=lpn-wlmd; t=1795965883; bh=/tB3sh4gPi1rTkHEnvlYPIy8pYELz3ehNol3gGWFQGw=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References:MIME-Version:Content-Type:Content-Transfer-Encoding; b=k3du34XaJ7UfpmNPBoobZVlAUBwA/gJZZJiJFnPnawuSNrxIFMoaRQ7rKGhkEJZtTHd26spMl3frBg271J9dPYfGXTL4ItpqCT8lraTHGKSEyq+dUMFgyxFbb4DkRoTxUVUZctK0LJkL0HqrZffxMIq4Ia3iKe3oFI/WzZPeTu4k/bdMsp7u6vezbYQGeLZ02t6sFXT7QQUMXgCgoh1KaaVMXXVpKb5ibmhNshsvBinsY/FpkUVm9p76toGWBbHRcl5r/w3RarxB+DFbpUdtMjE8TbcrAdCSQlGJg7A+0xTDlG94BSiQAffQ8qgrTWpU4z86Qdm7X4Gp6uWVaiYbUQ==; 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 Add mono.frag, a single fragment shader for all monochrome formats, selected through defines: RAW8, RAW10, RAW12 and RAW16 (unpacked, 2 bytes per pixel little endian for the last three) and RAW10P and RAW12P (CSI-2 packed). For packed formats, the shader finds the most significant byte of the pixel and the shared least significant byte of its block from tex_size. It applies the black level, the optional shading correction (red channel of the gain table, as the signal is the same on all channels), the S-shaped contrast curve and the gamma, then writes the grey value as RGB. identity.vert is reused as suggested in the v6 review: no dedicated vertex shader is needed. The precision declaration is the same as in the Bayer shaders. The shader is wired into the GPU debayer in patch 4/6. Signed-off-by: Alain Cousinié --- src/libcamera/shaders/meson.build | 1 + src/libcamera/shaders/mono.frag | 168 ++++++++++++++++++++++++++++++ 2 files changed, 169 insertions(+) create mode 100644 src/libcamera/shaders/mono.frag diff --git a/src/libcamera/shaders/meson.build b/src/libcamera/shaders/meson.build index c409ff9b0..e6df53da1 100644 --- a/src/libcamera/shaders/meson.build +++ b/src/libcamera/shaders/meson.build @@ -7,6 +7,7 @@ shader_files = files([ 'bayer_unpacked.frag', 'bayer_unpacked.vert', 'identity.vert', + 'mono.frag', ]) # Generate header from shaders diff --git a/src/libcamera/shaders/mono.frag b/src/libcamera/shaders/mono.frag new file mode 100644 index 000000000..96815c244 --- /dev/null +++ b/src/libcamera/shaders/mono.frag @@ -0,0 +1,168 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/* + * Copyright (C) 2026, Alain Cousinié + * + * Generic single fragment shader for all monochrome formats in libcamera. + */ + +#ifdef GL_ES +precision highp float; +#endif + +/* Automatic pipeline mode deduction with build safety check */ +#if defined(RAW8) || defined(RAW10) || defined(RAW12) || defined(RAW16) + #define PIPELINE_MONO_UNPACKED +#elif defined(RAW10P) || defined(RAW12P) + #define PIPELINE_MONO_PACKED +#else + #error Invalid or unsupported monochrome format +#endif + +/* Texture coordinates geometrically corrected by identity.vert */ +varying vec2 textureOut; + +/* Standard uniforms supplied by the CPU (debayer_egl.cpp) */ +uniform sampler2D tex_y; +#if defined(PIPELINE_MONO_PACKED) +uniform vec2 tex_size; /* Native [width, height] of the texture */ +#endif +uniform float gamma; +uniform float contrastExp; +uniform vec3 blacklevel; +#if defined(APPLY_LSC) +uniform sampler2D lsc_tex; /* Grids of LSC gains sent from the CPU */ +#endif + +/* ========================================== + * UNIFIED PIXEL EXTRACTION FUNCTION + * ========================================== */ +float readNativePixel(vec2 texOut) +{ + float pixelVal = 0.0; + + /* ------------------------------------------------------------------------- + * CASE UNPACKED MONOCHROME + * ------------------------------------------------------------------------- + * - RAW8: Transmitted as 1 byte per pixel. Sampled natively via GL_LUMINANCE. + * [ Byte 0: P0 (8-bit) ] + * + * - RAW10/RAW12/RAW16: Stored across 2 contiguous bytes (16 bits) per pixel, + * aligned Little-Endian. Imported into OpenGL as a 2-channel GL_RG texture. + * [ Byte 0 (texel.r): LSB (P0_low) ] -> Parsed as (texel.r * 255.0) + * [ Byte 1 (texel.g): MSB (P0_high) ] -> Parsed as (texel.g * 255.0) + * ------------------------------------------------------------------------- */ + #if defined(PIPELINE_MONO_UNPACKED) + #if defined(RAW8) + pixelVal = floor(texture2D(tex_y, texOut).r * 255.0 + 0.5); + #else + vec4 texel = texture2D(tex_y, texOut); + float byteLow = floor(texel.r * 255.0 + 0.5); + float byteHigh = floor(texel.g * 255.0 + 0.5); + pixelVal = (byteHigh * 256.0) + byteLow; + #endif + + /* ------------------------------------------------------------------------- + * CASE PACKED MONOCHROME + * ------------------------------------------------------------------------- + * Pixels are grouped into sequential macro-blocks to optimize MIPI bandwidth. + * MSB bytes are sent sequentially, followed by shared trailing LSB bytes. + * Sampled in OpenGL via a 1-channel GL_LUMINANCE texture. + * + * - RAW10P (4 Pixels into 5 Bytes): + * [Byte 0: P0_high(8b)] [Byte 1: P1_high(8b)] [Byte 2: P2_high(8b)] [Byte 3: P3_high(8b)] + * [Byte 4: P3_low(2b) | P2_low(2b) | P1_low(2b) | P0_low(2b)] + * BLOCK_PIXELS = 4.0, BLOCK_BYTES = 5.0, LSB_SIZE = 2.0, LSB_MASK = 4.0 + * + * - RAW12P (2 Pixels into 3 Bytes): + * [Byte 0: P0_high(8b)] [Byte 1: P1_high(8b)] + * [Byte 2: P1_low(4b) | P0_low(4b)] + * BLOCK_PIXELS = 2.0, BLOCK_BYTES = 3.0, LSB_SIZE = 4.0, LSB_MASK = 16.0 + * ------------------------------------------------------------------------- */ + #elif defined(PIPELINE_MONO_PACKED) + + /* Scale normalized coordinates up to actual texture dimensions */ + vec2 v_pixelCoords = texOut * tex_size; + + float px = floor(v_pixelCoords.x); + float py = floor(v_pixelCoords.y); + + float blockIndex = floor(px / BLOCK_PIXELS); + float idx = mod(px, BLOCK_PIXELS); + float blockStart = blockIndex * BLOCK_BYTES; + + float normY = (py + 0.5) / tex_size.y; + float xMSB = (blockStart + idx + 0.5) / TEX_WIDTH; + float byteHigh = floor(texture2D(tex_y, vec2(xMSB, normY)).r * 255.0 + 0.5); + + #if defined(RAW10P) + /* 4 pixels in 5 bytes: Byte 4 holds [P3_low(2b) | P2_low(2b) | P1_low(2b) | P0_low(2b)] */ + float b4 = floor(texture2D(tex_y, vec2((blockStart + 4.5) / TEX_WIDTH, normY)).r * 255.0 + 0.5); + float lsbBits = 0.0; + + if (idx < 0.5) { + lsbBits = mod(b4, 4.0); + } else if (idx < 1.5) { + lsbBits = mod(floor(b4 / 4.0), 4.0); + } else if (idx < 2.5) { + lsbBits = mod(floor(b4 / 16.0), 4.0); + } else { + lsbBits = floor(b4 / 64.0); + } + pixelVal = (byteHigh * 4.0) + lsbBits; + + #elif defined(RAW12P) + /* 2 pixels in 3 bytes: Byte 2 holds [P1_low(4b) | P0_low(4b)] */ + float b2 = floor(texture2D(tex_y, vec2((blockStart + 2.5) / TEX_WIDTH, normY)).r * 255.0 + 0.5); + float lsbBits = 0.0; + + if (idx < 0.5) { + lsbBits = mod(b2, 16.0); + } else { + lsbBits = floor(b2 / 16.0); + } + pixelVal = (byteHigh * 16.0) + lsbBits; + + #endif + #endif + return pixelVal; +} + +/* ========================================== + * GENERIC MAIN PIPELINE + * ========================================== */ +void main(void) +{ + /* Read raw pixel value via the unified generic function */ + float rawValue = readNativePixel(textureOut); + + /* Step 1: Normalization and Black Level Subtraction */ + float normalizedIntensity = rawValue * INV_MAX_VAL; + normalizedIntensity = clamp(normalizedIntensity - blacklevel.r, 0.0, 1.0); + + /* Step 2: Lens Shading Correction */ + #if defined(APPLY_LSC) + /* Sample the LSC lookup grid texture using normalized output coordinates */ + vec4 lscGains = texture2D(lsc_tex, textureOut); + + /* + * In libcamera's SoftISP LSC implementation, values are stored in UQ2.6 format + * inside an 8-bit texture. We upscale the normalized value back to its real range [0..4] + * We sample the first channel (red) since the signal is uniform across channels for grayscale. + */ + float lscGain = lscGains.r * 4.0; + + /* Apply the spatial attenuation correction factor */ + normalizedIntensity = clamp(normalizedIntensity * lscGain, 0.0, 1.0); + #endif + + /* Step 3: Contrast Enhancement (S-Curve) */ + float centerDist = 1.0 - abs(2.0 * normalizedIntensity - 1.0); + float singlePow = 0.5 * pow(centerDist, contrastExp); + normalizedIntensity = mix(singlePow, 1.0 - singlePow, step(0.5, normalizedIntensity)); + + /* Step 4: Gamma Correction */ + vec3 rgb = pow(vec3(normalizedIntensity), vec3(gamma)); + + /* Step 5: Texture Output (Grayscale is uniform, no color swapping needed) */ + gl_FragColor = vec4(rgb, 1.0); +} From patchwork Sun Nov 29 15:24:12 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: =?utf-8?q?Alain_Cousini=C3=A9?= X-Patchwork-Id: 29105 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 BD86AC3355 for ; Sun, 29 Nov 2026 15:24:53 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 017AD6AA4E; Sun, 29 Nov 2026 16:24:51 +0100 (CET) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (2048-bit key; unprotected) header.d=laposte.net header.i=@laposte.net header.b="jPg+Nv3Z"; dkim-atps=neutral Received: from smtp-outgoing-1602.laposte.net (smtp-outgoing-1602.laposte.net [160.92.124.97]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 9E5ED6AA32 for ; Sun, 29 Nov 2026 16:24:43 +0100 (CET) X-mail-filterd: {"version":"1.9.7", "queueID":"4jcrYP37Zqz10MQ4", "contextId": "6b419b7c-01c4-4ec9-a06c-9bfa3aaf68e4"} Received: from outgoing-mail.laposte.net (localhost.localdomain [127.0.0.1]) by mlpnf0120.laposte.net (SMTP Server) with ESMTP id 4jcrYP37Zqz10MQ4; Sun, 29 Nov 2026 16:24:41 +0100 (CET) X-mail-filterd: {"version":"1.9.7", "queueID":"4jcrYP1Hnzz10MQQ", "contextId": "007f0289-a614-4ff0-a754-eccd4942f6c8"} X-lpn-mailing: LEGIT X-lpn-spamrating: 36 X-lpn-spamlevel: not-spam Received: from debian.home (m-dj.hd.free.fr [82.67.82.126]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mlpnf0120.laposte.net (SMTP Server) with ESMTPSA id 4jcrYP1Hnzz10MQQ; Sun, 29 Nov 2026 16:24:41 +0100 (CET) From: =?utf-8?q?Alain_Cousini=C3=A9?= To: libcamera-devel@lists.libcamera.org, Milan Zamazal Cc: Hans de Goede , Bryan O'Donoghue , =?utf-8?q?Barnab=C3=A1s_P=C5=91cze?= , Laurent Pinchart , Jai Luthra , =?utf-8?q?Alain_Cousini=C3=A9?= Subject: [PATCH v8 2/6] libcamera: software_isp: Add support for monochrome formats - Stats Date: Sun, 29 Nov 2026 16:24:12 +0100 Message-ID: <20261129152416.174279-3-alain.cousinie@laposte.net> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261129152416.174279-1-alain.cousinie@laposte.net> References: <20261129152416.174279-1-alain.cousinie@laposte.net> MIME-Version: 1.0 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=laposte.net; s=lpn-wlmd; t=1795965883; bh=bB7L6kmtNBYcvF5fEhWyUzQVWituEoZZnlr2jwVVFRk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References:MIME-Version:Content-Type:Content-Transfer-Encoding; b=jPg+Nv3Zby0jfSBrxBA/twdfhlk0EWPBApx1bu/CefdVQCiX4Rt6wQtxLG9jVdOtWReX3XuazfdH5O+/ZIa+k32WFJl+8lXCIbjkT3cbOTB8pCo9/936jLVzi4b1u6MSzMvbvTj/wX/dAYvJuUkRdnbDCvJvhR8jVgHYkEEl+tvr5JOxYCv6XN4xPPJfCcQZ+Vf/L+/1mKS5cSMk6ZiiUVTpYEjyj3p95ZfNbYYyIeJJNwCYUX7GuigeAxDOQJq3x40FNawjyBSBkK2PzWlnnWR1ExbNbBr6ZbEM43qVCKVvLXhsAXzUT2kUGrE6qGLqSrY7ak1g/Eb6DELvzj07ng==; 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 Add support for monochrome formats in SwStatsCpu: one function per format for unpacked R8, R10, R12 and R16, and for CSI-2 packed R10 and R12. The pattern size follows the Bayer formats: 2x2 for unpacked formats, and a width equal to the group of packed pixels for R10P (4 pixels in 5 bytes) and R12P (2 pixels in 3 bytes). The CPU and GPU debayers use the same pattern. One pixel out of four is sampled horizontally on each line, for all formats, to limit the cost. Each sample is weighted by 4 so the totals keep the density of a full sum. Values are brought to the 8-bit scale as for the Bayer statistics, and the same sum feeds R, G and B. The 64-bin histogram uses the most significant bits of the pixel. For packed formats, only the most significant byte of the sampled pixel is read, which is enough for statistics. Bayer statistics visit two lines out of four and one 2x2 block out of two, i.e. a quarter of the pixels. The cost is therefore similar, but no line is skipped for monochrome. This avoids aliasing on scenes with fine structures along the vertical axis (scanning, line patterns). Signed-off-by: Alain Cousinié --- .../internal/software_isp/swstats_cpu.h | 13 ++ src/libcamera/software_isp/swstats_cpu.cpp | 184 ++++++++++++++++++ 2 files changed, 197 insertions(+) diff --git a/include/libcamera/internal/software_isp/swstats_cpu.h b/include/libcamera/internal/software_isp/swstats_cpu.h index 551870921..f702cf126 100644 --- a/include/libcamera/internal/software_isp/swstats_cpu.h +++ b/include/libcamera/internal/software_isp/swstats_cpu.h @@ -101,8 +101,21 @@ private: /* Bayer 12 bpp packed */ void statsBGGR12PLine0(const uint8_t *src[], SwIspStats &stats); void statsGBRG12PLine0(const uint8_t *src[], SwIspStats &stats); + /* Mono 8 bpp unpacked */ + void statsMono8Line0(const uint8_t *src[], SwIspStats &stats); + /* Mono 10 bpp unpacked */ + void statsMono10Line0(const uint8_t *src[], SwIspStats &stats); + /* Mono 10 bpp packed */ + void statsMono10PLine0(const uint8_t *src[], SwIspStats &stats); + /* Mono 12 bpp unpacked */ + void statsMono12Line0(const uint8_t *src[], SwIspStats &stats); + /* Mono 12 bpp packed */ + void statsMono12PLine0(const uint8_t *src[], SwIspStats &stats); + /* Mono 16 bpp unpacked */ + void statsMono16Line0(const uint8_t *src[], SwIspStats &stats); void processBayerFrame2(MappedFrameBuffer &in); + void processMonoFrame2(MappedFrameBuffer &in); processFrameFn processFrame_; diff --git a/src/libcamera/software_isp/swstats_cpu.cpp b/src/libcamera/software_isp/swstats_cpu.cpp index 74633815e..852f391de 100644 --- a/src/libcamera/software_isp/swstats_cpu.cpp +++ b/src/libcamera/software_isp/swstats_cpu.cpp @@ -390,6 +390,124 @@ void SwStatsCpu::statsGBRG12PLine0(const uint8_t *src[], SwIspStats &stats) SWSTATS_FINISH_LINE_STATS() } +/* + * Horizontal sub-sampling optimization: evaluates 1 pixel out of 4 (x += 4) + * to reduce CPU overhead. Each sample gets a weight of +4 to preserve global + * frame statistical density required by the Auto Exposure (AE) algorithm. + */ +inline void storeMonoAccumulation(SwIspStats &stats, uint64_t value) +{ + stats.sum_.r() += value; + stats.sum_.g() += value; + stats.sum_.b() += value; +} + +void SwStatsCpu::statsMono8Line0(const uint8_t *src[], SwIspStats &stats) +{ + const uint8_t *cur = src[1] + window_.x; + uint64_t sum = 0; + + for (unsigned int x = 0; x < window_.width; x += 4) { + sum += *cur; + stats.yHistogram[*cur >> 2] += 4; + cur += 4; + } + /* Process 4 pixels per iteration : x << 2 */ + storeMonoAccumulation(stats, sum << 2); +} + +void SwStatsCpu::statsMono10Line0(const uint8_t *src[], SwIspStats &stats) +{ + /* + * Little-Endian optimization: Unpacked 10-bit format stores data + * right-aligned in a 2-byte container. Reading via a 16-bit pointer + * allows clean data access before applying the bit-shift. + */ + const uint16_t *cur = reinterpret_cast(src[1] + window_.x * 2); + uint64_t sum = 0; + + for (unsigned int x = 0; x < window_.width; x += 4) { + uint16_t val = *cur; + sum += val; + stats.yHistogram[(val >> 4) & 0x3f] += 4; + cur += 4; + } + /* Process 4 pixels per iteration : x 10 >> 2 to 8bits and x << 2 */ + storeMonoAccumulation(stats, sum); +} + +void SwStatsCpu::statsMono12Line0(const uint8_t *src[], SwIspStats &stats) +{ + /* + * 12-bit unpacked processing. Data is read via a native 16-bit pointer + * and right-shifted to fit the histogram range. + */ + const uint16_t *cur = reinterpret_cast(src[1] + window_.x * 2); + uint64_t sum = 0; + + for (unsigned int x = 0; x < window_.width; x += 4) { + uint16_t val = *cur; + sum += val; + stats.yHistogram[(val >> 6) & 0x3f] += 4; + cur += 4; + } + /* Process 4 pixels per iteration : 12 >> 4 to 8bits and x << 2 */ + storeMonoAccumulation(stats, sum >> 2); +} + +void SwStatsCpu::statsMono10PLine0(const uint8_t *src[], SwIspStats &stats) +{ + /* + * MIPI CSI-2 10-bit packed: 4 pixels in 5 bytes. Stepping 5 bytes + * evaluates the head MSB pixel of each block as a native 8-bit value. + */ + const uint8_t *cur = src[1] + window_.x * 5 / 4; + uint64_t sum = 0; + + for (unsigned int x = 0; x < window_.width; x += 4) { + uint8_t val = *cur; + sum += val; + stats.yHistogram[val >> 2] += 4; + cur += 5; + } + /* Process 4 pixels per iteration : first byte x << 2 */ + storeMonoAccumulation(stats, sum << 2); +} + +void SwStatsCpu::statsMono12PLine0(const uint8_t *src[], SwIspStats &stats) +{ + /* + * MIPI CSI-2 12-bit packed: 2 pixels in 3 bytes. Stepping 6 bytes + * advances by two full blocks for optimal data alignment. + */ + const uint8_t *cur = src[1] + window_.x * 3 / 2; + uint64_t sum = 0; + + for (unsigned int x = 0; x < window_.width; x += 4) { + uint8_t val = *cur; + sum += val; + stats.yHistogram[val >> 2] += 4; + cur += 6; + } + /* Process 4 pixels per iteration : first byte x << 2 */ + storeMonoAccumulation(stats, sum << 2); +} + +void SwStatsCpu::statsMono16Line0(const uint8_t *src[], SwIspStats &stats) +{ + const uint16_t *cur = reinterpret_cast(src[1] + window_.x * 2); + uint64_t sum = 0; + + for (unsigned int x = 0; x < window_.width; x += 4) { + uint16_t val = *cur; + sum += val; + stats.yHistogram[val >> 10] += 4; + cur += 4; + } + /* Process 4 pixels per iteration : 16 >> 8 to 8bits and x << 2 */ + storeMonoAccumulation(stats, sum >> 6); +} + /** * \brief Reset state to start statistics gathering for a new frame * \param[in] frame The frame number @@ -512,6 +630,53 @@ int SwStatsCpu::configure(const StreamConfiguration &inputCfg, unsigned int stat uint8_t bitDepth = bayerFormat.bitDepth; + if (bayerFormat.order == BayerFormat::Order::MONO) { + /* + * Bayer statistics visit 2 lines out of 4 and every other 2x2 block + * (a quarter of the pixels). Sample the same share here, one pixel out + * of four on every line, so that no line is skipped. + */ + ySkipMask_ = 0; + xShift_ = 0; + sumShift_ = 0; + processFrame_ = &SwStatsCpu::processMonoFrame2; + + if (bayerFormat.packing == BayerFormat::Packing::None) { + patternSize_.width = 2; + patternSize_.height = 2; + + switch (bitDepth) { + case 8: + stats0_ = &SwStatsCpu::statsMono8Line0; + return 0; + case 10: + stats0_ = &SwStatsCpu::statsMono10Line0; + return 0; + case 12: + stats0_ = &SwStatsCpu::statsMono12Line0; + return 0; + case 16: + stats0_ = &SwStatsCpu::statsMono16Line0; + return 0; + } + } + if (bayerFormat.packing == BayerFormat::Packing::CSI2) { + patternSize_.height = 2; + + switch (bitDepth) { + case 10: + patternSize_.width = 4; + stats0_ = &SwStatsCpu::statsMono10PLine0; + return 0; + case 12: + patternSize_.width = 2; + stats0_ = &SwStatsCpu::statsMono12PLine0; + return 0; + } + } + return -EINVAL; + } + if ((bitDepth == 10 || bitDepth == 12) && bayerFormat.packing == BayerFormat::Packing::CSI2) { if (bitDepth == 10) @@ -612,6 +777,25 @@ void SwStatsCpu::processBayerFrame2(MappedFrameBuffer &in) } } +void SwStatsCpu::processMonoFrame2(MappedFrameBuffer &in) +{ + const uint8_t *src = in.planes()[0].data(); + const uint8_t *linePointers[3]; + + src += window_.y * stride_; + + for (unsigned int y = 0; y < window_.height; y++) { + if (y & ySkipMask_) { + src += stride_; + continue; + } + + linePointers[1] = src; + (this->*stats0_)(linePointers, stats_[0]); + src += stride_; + } +} + /** * \brief Calculate statistics for a frame in one go * \param[in] frame The frame number From patchwork Sun Nov 29 15:24:13 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: =?utf-8?q?Alain_Cousini=C3=A9?= X-Patchwork-Id: 29104 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 BA188C3355 for ; Sun, 29 Nov 2026 15:24:51 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 3936E6AA4C; Sun, 29 Nov 2026 16:24:50 +0100 (CET) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (2048-bit key; unprotected) header.d=laposte.net header.i=@laposte.net header.b="Ed/PxYXI"; dkim-atps=neutral Received: from smtp-outgoing-1902.laposte.net (smtp-outgoing-1902.laposte.net [160.92.124.106]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id B30766AA34 for ; Sun, 29 Nov 2026 16:24:43 +0100 (CET) X-mail-filterd: {"version":"1.9.7", "queueID":"4jcrYP5RNkz10MQ4", "contextId": "470f4e06-bf23-4464-ad1d-464774cb2e4c"} Received: from outgoing-mail.laposte.net (localhost.localdomain [127.0.0.1]) by mlpnf0120.laposte.net (SMTP Server) with ESMTP id 4jcrYP5RNkz10MQ4; Sun, 29 Nov 2026 16:24:41 +0100 (CET) X-mail-filterd: {"version":"1.9.7", "queueID":"4jcrYP3Knlz10MQN", "contextId": "d495d0ab-ed2b-462c-8702-b7c09b49a382"} X-lpn-mailing: LEGIT X-lpn-spamrating: 36 X-lpn-spamlevel: not-spam Received: from debian.home (m-dj.hd.free.fr [82.67.82.126]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mlpnf0120.laposte.net (SMTP Server) with ESMTPSA id 4jcrYP3Knlz10MQN; Sun, 29 Nov 2026 16:24:41 +0100 (CET) From: =?utf-8?q?Alain_Cousini=C3=A9?= To: libcamera-devel@lists.libcamera.org, Milan Zamazal Cc: Hans de Goede , Bryan O'Donoghue , =?utf-8?q?Barnab=C3=A1s_P=C5=91cze?= , Laurent Pinchart , Jai Luthra , =?utf-8?q?Alain_Cousini=C3=A9?= Subject: [PATCH v8 3/6] libcamera: software_isp: Add support for monochrome formats - CPU Date: Sun, 29 Nov 2026 16:24:13 +0100 Message-ID: <20261129152416.174279-4-alain.cousinie@laposte.net> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261129152416.174279-1-alain.cousinie@laposte.net> References: <20261129152416.174279-1-alain.cousinie@laposte.net> MIME-Version: 1.0 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=laposte.net; s=lpn-wlmd; t=1795965883; bh=kgQZNXXP03trVVzMucEXmfktinkF8xSNdfpP8VoBRIY=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References:MIME-Version:Content-Type:Content-Transfer-Encoding; b=Ed/PxYXIXtpEHACAzBmRb6zI/T2HsRD9M/9HFWEeGDjNWn6nRfY8G6ONw9zzw7CnnXQm1JxrMMjjLg5ZCXZRHOLMKzBxFXFRQndPSpKuzh0agtrkPwQ7V476vGiAz4PMrYR3HM25AyJ+v7KHdqjmTRR5asdfGbZDg13IasDh6iD27aDgDejhmHEO/nHx0UX1wZNEAfXsg5yXKY/rSc9moN7oQDJk/x87kd65bTNJ5Jno4cC5BK0EUKV1jrXk/H5Ln0zNrd7w/HmCb2bHjG7l0z+cfd78pqBB/iif7qmm4GeSg07WgMtfHj+esHQLj7TZ8y1o9UY4H7c/Ys6Oav1TGg==; 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 Add conversion functions for unpacked R8, R10, R12 and R16, and for CSI-2 packed R10 and R12. Each one takes the 8 most significant bits of the pixel and stores the same value in B, G and R through STORE_PIXEL. The black level, contrast and gamma tables apply as for Bayer. The least significant bits are not used. SoftwareIsp disables the colour correction matrix for monochrome input. The pattern size is the one of the statistics (see patch 2/6). Its height of 2 guarantees an even number of lines, which processMono2() needs as it processes lines in pairs, like process2(). With no neighbouring pixels to interpolate, sizes() keeps no border for monochrome. While there, align DebayerCpu::sizes() with DebayerEGL::sizes(): borderHeight is declared after the null check, and the size is printed with operator<<. Signed-off-by: Alain Cousinié --- src/libcamera/software_isp/debayer_cpu.cpp | 178 ++++++++++++++++++++- src/libcamera/software_isp/debayer_cpu.h | 19 +++ 2 files changed, 189 insertions(+), 8 deletions(-) diff --git a/src/libcamera/software_isp/debayer_cpu.cpp b/src/libcamera/software_isp/debayer_cpu.cpp index 91867baa6..9399814f9 100644 --- a/src/libcamera/software_isp/debayer_cpu.cpp +++ b/src/libcamera/software_isp/debayer_cpu.cpp @@ -50,6 +50,7 @@ private: void shiftLinePointers(const uint8_t *linePointers[], const uint8_t *src); void memcpyNextLine(const uint8_t *linePointers[]); void process2(uint32_t frame, const uint8_t *src, uint8_t *dst); + void processMono2(uint32_t frame, const uint8_t *src, uint8_t *dst); void process4(uint32_t frame, const uint8_t *src, uint8_t *dst); /* Max. supported Bayer pattern height is 4, debayering this requires 5 lines */ @@ -424,6 +425,90 @@ void DebayerCpu::debayer12P_RGRG_BGR888(uint8_t *dst, const uint8_t *src[]) } } +template +void DebayerCpu::debayer8_MONO_BGR888(uint8_t *dst, const uint8_t *src[]) +{ + const uint8_t *cur = src[1]; + + for (int x = 0; x < static_cast(window_.width);) { + uint8_t pixel_val = *cur++; + STORE_PIXEL(pixel_val, pixel_val, pixel_val) + } +} + +template +void DebayerCpu::debayer10_MONO_BGR888(uint8_t *dst, const uint8_t *src[]) +{ + const uint16_t *cur = reinterpret_cast(src[1]); + + for (int x = 0; x < static_cast(window_.width);) { + uint16_t native_val = *cur++; + uint8_t pixel_val = static_cast(native_val >> 2); + + STORE_PIXEL(pixel_val, pixel_val, pixel_val) + } +} + +template +void DebayerCpu::debayer12_MONO_BGR888(uint8_t *dst, const uint8_t *src[]) +{ + const uint16_t *cur = reinterpret_cast(src[1]); + + for (int x = 0; x < static_cast(window_.width);) { + uint16_t native_val = *cur++; + uint8_t pixel_val = static_cast(native_val >> 4); + + STORE_PIXEL(pixel_val, pixel_val, pixel_val) + } +} + +template +void DebayerCpu::debayer10P_MONO_BGR888(uint8_t *dst, const uint8_t *src[]) +{ + const uint8_t *cur = src[1]; + + for (int x = 0; x < static_cast(window_.width);) { + uint8_t gray0 = *cur++; + uint8_t gray1 = *cur++; + uint8_t gray2 = *cur++; + uint8_t gray3 = *cur++; + cur++; + + STORE_PIXEL(gray0, gray0, gray0) + STORE_PIXEL(gray1, gray1, gray1) + STORE_PIXEL(gray2, gray2, gray2) + STORE_PIXEL(gray3, gray3, gray3) + } +} + +template +void DebayerCpu::debayer12P_MONO_BGR888(uint8_t *dst, const uint8_t *src[]) +{ + const uint8_t *cur = src[1]; + + for (int x = 0; x < static_cast(window_.width);) { + uint8_t gray0 = *cur++; + uint8_t gray1 = *cur++; + cur++; + + STORE_PIXEL(gray0, gray0, gray0) + STORE_PIXEL(gray1, gray1, gray1) + } +} + +template +void DebayerCpu::debayer16_MONO_BGR888(uint8_t *dst, const uint8_t *src[]) +{ + const uint16_t *cur = reinterpret_cast(src[1]); + + for (int x = 0; x < static_cast(window_.width);) { + uint16_t native_val = *cur++; + uint8_t pixel_val = static_cast(native_val >> 8); + + STORE_PIXEL(pixel_val, pixel_val, pixel_val) + } +} + /* * Setup the Debayer object according to the passed in parameters. * Return 0 on success, a negative errno value on failure @@ -433,6 +518,7 @@ int DebayerCpu::getInputConfig(PixelFormat inputFormat, DebayerInputConfig &conf { BayerFormat bayerFormat = BayerFormat::fromPixelFormat(inputFormat); + std::vector outputFormats = { formats::RGB888, formats::XRGB8888, formats::ARGB8888, @@ -440,6 +526,20 @@ int DebayerCpu::getInputConfig(PixelFormat inputFormat, DebayerInputConfig &conf formats::XBGR8888, formats::ABGR8888 }; + if (bayerFormat.order == BayerFormat::Order::MONO) { + if (bayerFormat.packing == BayerFormat::Packing::None) { + config.bpp = (bayerFormat.bitDepth + 7) & ~7; + config.patternSize.width = 2; + config.patternSize.height = 2; + } else if (bayerFormat.packing == BayerFormat::Packing::CSI2) { + config.bpp = bayerFormat.bitDepth; + config.patternSize.width = (bayerFormat.bitDepth == 12) ? 2 : 4; + config.patternSize.height = 2; + } + config.outputFormats = outputFormats; + return 0; + } + if ((bayerFormat.bitDepth == 8 || bayerFormat.bitDepth == 10 || bayerFormat.bitDepth == 12) && bayerFormat.packing == BayerFormat::Packing::None && isStandardBayerOrder(bayerFormat.order)) { @@ -513,8 +613,6 @@ int DebayerCpu::setDebayerFunctions(PixelFormat inputFormat, PixelFormat outputFormat, bool ccmEnabled) { - BayerFormat bayerFormat = - BayerFormat::fromPixelFormat(inputFormat); bool addAlphaByte = false; xShift_ = 0; @@ -525,6 +623,42 @@ int DebayerCpu::setDebayerFunctions(PixelFormat inputFormat, return -EINVAL; }; + BayerFormat bayerFormat = BayerFormat::fromPixelFormat(inputFormat); + + if (bayerFormat.order == BayerFormat::Order::MONO) { + if (outputFormat == formats::XRGB8888 || outputFormat == formats::ARGB8888 || + outputFormat == formats::XBGR8888 || outputFormat == formats::ABGR8888) { + addAlphaByte = true; + } + if (bayerFormat.packing == BayerFormat::Packing::None) { + switch (bayerFormat.bitDepth) { + case 8: + SET_DEBAYER_METHODS(debayer8_MONO_BGR888, debayer8_MONO_BGR888) + return 0; + case 10: + SET_DEBAYER_METHODS(debayer10_MONO_BGR888, debayer10_MONO_BGR888) + return 0; + case 12: + SET_DEBAYER_METHODS(debayer12_MONO_BGR888, debayer12_MONO_BGR888) + return 0; + case 16: + SET_DEBAYER_METHODS(debayer16_MONO_BGR888, debayer16_MONO_BGR888) + return 0; + } + } + if (bayerFormat.packing == BayerFormat::Packing::CSI2) { + switch (bayerFormat.bitDepth) { + case 10: + SET_DEBAYER_METHODS(debayer10P_MONO_BGR888, debayer10P_MONO_BGR888) + return 0; + case 12: + SET_DEBAYER_METHODS(debayer12P_MONO_BGR888, debayer12P_MONO_BGR888) + return 0; + } + } + return invalidFmt(); + } + switch (outputFormat) { case formats::XRGB8888: case formats::ARGB8888: @@ -633,6 +767,9 @@ int DebayerCpu::configure(const StreamConfiguration &inputCfg, return -EINVAL; } + BayerFormat bayerFormat = BayerFormat::fromPixelFormat(inputCfg.pixelFormat); + isMono_ = (bayerFormat.order == BayerFormat::Order::MONO); + if (stats_->configure(inputCfg, threads_.size()) != 0) return -EINVAL; @@ -828,7 +965,9 @@ void DebayerCpuThread::process(uint32_t frame, const uint8_t *src, uint8_t *dst) /* Adjust dst for yStart_ */ dst += yStart_ * debayer_->outputConfig_.stride; - if (debayer_->inputConfig_.patternSize.height == 2) + if (debayer_->isMono_) + processMono2(frame, src, dst); + else if (debayer_->inputConfig_.patternSize.height == 2) process2(frame, src, dst); else process4(frame, src, dst); @@ -905,6 +1044,27 @@ void DebayerCpuThread::process2(uint32_t frame, const uint8_t *src, uint8_t *dst } } +void DebayerCpuThread::processMono2(uint32_t frame, const uint8_t *src, uint8_t *dst) +{ + unsigned int outputStride = debayer_->outputConfig_.stride; + unsigned int inputStride = debayer_->inputConfig_.stride; + /* Holds [0] previous- [1] current- [2] next-line */ + const uint8_t *linePointers[3]; + + for (unsigned int y = yStart_; y < yEnd_; y += 2) { + linePointers[1] = src; + debayer_->stats_->processLine0(frame, y, linePointers, threadIndex_); + debayer_->debayer0(dst, linePointers); + src += inputStride; + dst += outputStride; + + linePointers[1] = src; + debayer_->debayer1(dst, linePointers); + src += inputStride; + dst += outputStride; + } +} + void DebayerCpuThread::process4(uint32_t frame, const uint8_t *src, uint8_t *dst) { unsigned int outputStride = debayer_->outputConfig_.stride; @@ -1125,12 +1285,11 @@ void DebayerCpu::stop() SizeRange DebayerCpu::sizes(PixelFormat inputFormat, const Size &inputSize) { Size patternSize = this->patternSize(inputFormat); - unsigned int borderHeight = patternSize.height; - if (patternSize.isNull()) return {}; /* No need for top/bottom border with a pattern height of 2 */ + unsigned int borderHeight = patternSize.height; if (patternSize.height == 2) borderHeight = 0; @@ -1141,13 +1300,16 @@ SizeRange DebayerCpu::sizes(PixelFormat inputFormat, const Size &inputSize) if (inputSize.width < (3 * patternSize.width) || inputSize.height < (2 * borderHeight + patternSize.height)) { LOG(Debayer, Warning) - << "Input format size too small: " << inputSize.toString(); + << "Input format size too small: " << inputSize; return {}; } + BayerFormat bayerFormat = BayerFormat::fromPixelFormat(inputFormat); + bool localIsMono = (bayerFormat.order == BayerFormat::Order::MONO); + return SizeRange(Size(patternSize.width, patternSize.height), - Size((inputSize.width - 2 * patternSize.width) & ~(patternSize.width - 1), - (inputSize.height - 2 * borderHeight) & ~(patternSize.height - 1)), + Size((inputSize.width - (localIsMono ? 0 : 2 * patternSize.width)) & ~(patternSize.width - 1), + (inputSize.height - (localIsMono ? 0 : 2 * borderHeight)) & ~(patternSize.height - 1)), patternSize.width, patternSize.height); } diff --git a/src/libcamera/software_isp/debayer_cpu.h b/src/libcamera/software_isp/debayer_cpu.h index ae570893b..0f60515ba 100644 --- a/src/libcamera/software_isp/debayer_cpu.h +++ b/src/libcamera/software_isp/debayer_cpu.h @@ -120,6 +120,24 @@ private: void debayer12P_GBGB_BGR888(uint8_t *dst, const uint8_t *src[]); template void debayer12P_RGRG_BGR888(uint8_t *dst, const uint8_t *src[]); + /* 8-bit raw monochrome format */ + template + void debayer8_MONO_BGR888(uint8_t *dst, const uint8_t *src[]); + /* unpacked 10-bit raw monochrome format */ + template + void debayer10_MONO_BGR888(uint8_t *dst, const uint8_t *src[]); + /* unpacked 12-bit raw monochrome format */ + template + void debayer12_MONO_BGR888(uint8_t *dst, const uint8_t *src[]); + /* CSI-2 packed 10-bit raw monochrome format */ + template + void debayer10P_MONO_BGR888(uint8_t *dst, const uint8_t *src[]); + /* CSI-2 packed 12-bit raw monochrome format */ + template + void debayer12P_MONO_BGR888(uint8_t *dst, const uint8_t *src[]); + /* Mono 16 bpp unpacked */ + template + void debayer16_MONO_BGR888(uint8_t *dst, const uint8_t *src[]); static int getInputConfig(PixelFormat inputFormat, DebayerInputConfig &config); int setupStandardBayerOrder(BayerFormat::Order order); @@ -147,6 +165,7 @@ private: std::array gammaTable_; LookupTable gammaLut_; bool ccmEnabled_; + bool isMono_ = false; DebayerParams params_; debayerFn debayer0_; From patchwork Sun Nov 29 15:24:14 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: =?utf-8?q?Alain_Cousini=C3=A9?= X-Patchwork-Id: 29102 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 71317C3355 for ; Sun, 29 Nov 2026 15:24:47 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 1B71F6AA47; Sun, 29 Nov 2026 16:24:47 +0100 (CET) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (2048-bit key; unprotected) header.d=laposte.net header.i=@laposte.net header.b="mW2IgxsZ"; dkim-atps=neutral Received: from smtp-outgoing-1601.laposte.net (smtp-outgoing-1601.laposte.net [160.92.124.96]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id D5E976AA37 for ; Sun, 29 Nov 2026 16:24:43 +0100 (CET) X-mail-filterd: {"version":"1.9.7", "queueID":"4jcrYQ0cLpz10MQ4", "contextId": "06d2e918-b7d5-46be-b35a-304f37973738"} Received: from outgoing-mail.laposte.net (localhost.localdomain [127.0.0.1]) by mlpnf0120.laposte.net (SMTP Server) with ESMTP id 4jcrYQ0cLpz10MQ4; Sun, 29 Nov 2026 16:24:42 +0100 (CET) X-mail-filterd: {"version":"1.9.7", "queueID":"4jcrYP5fFmz10MQQ", "contextId": "255c20e3-f7cc-46db-a4ae-ce74ae6e5a8d"} X-lpn-mailing: LEGIT X-lpn-spamrating: 36 X-lpn-spamlevel: not-spam Received: from debian.home (m-dj.hd.free.fr [82.67.82.126]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mlpnf0120.laposte.net (SMTP Server) with ESMTPSA id 4jcrYP5fFmz10MQQ; Sun, 29 Nov 2026 16:24:41 +0100 (CET) From: =?utf-8?q?Alain_Cousini=C3=A9?= To: libcamera-devel@lists.libcamera.org, Milan Zamazal Cc: Hans de Goede , Bryan O'Donoghue , =?utf-8?q?Barnab=C3=A1s_P=C5=91cze?= , Laurent Pinchart , Jai Luthra , =?utf-8?q?Alain_Cousini=C3=A9?= Subject: [PATCH v8 4/6] libcamera: software_isp: Add support for monochrome formats - GPU Date: Sun, 29 Nov 2026 16:24:14 +0100 Message-ID: <20261129152416.174279-5-alain.cousinie@laposte.net> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261129152416.174279-1-alain.cousinie@laposte.net> References: <20261129152416.174279-1-alain.cousinie@laposte.net> MIME-Version: 1.0 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=laposte.net; s=lpn-wlmd; t=1795965883; bh=dQm4e6X5ZLEqdIk2af92k1NerzH9zOL2CSlJ8jzSmlk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References:MIME-Version:Content-Type:Content-Transfer-Encoding; b=mW2IgxsZeaSFeLzC6g5xUkHw0wJrT/VVOz7PnlLrAjqF1b1WL8xJ3QobqKeH89gy3cpGEmzh0l6zxm6M2+Nup68QmRiOiCbxVphhh6mvDtEjOsWTYCCKtTQrSYrzd+f4ULg4qiDRg9cuVJEzF2cN+ogxExo3hqxu9smKrtE7mjVU6qUbL6PbSbyoyUCahqVcJso6EVjZ2K8gtRvVoxt07L2AeVXyigqWHOwO+WIB2P1a7rtRM2LLR/R6SSP1AtSs2fdvAkbi0XkO34SEm+KrpMf1R6Mg2Vs3+x0mRvvbPjpwr6RLXsYOtqetnkBLtQfuRWyZMhDaIUlHhq4o5bHsyw==; 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 Select mono.frag for R8, R10, R12 and R16 in DebayerEGL. Unpacked 10, 12 and 16-bit data is sent as a two-channel texture, 8-bit and packed data as a single-channel texture. For packed formats, TEX_WIDTH is the stride in bytes and the shader stride is width_, as for the Bayer shaders. Unlike the CPU, which only uses the 8 most significant bits, the GPU uses the full depth of the pixel. As for the CPU, the pattern size follows the Bayer formats and the statistics. firstRed_ is meaningless for monochrome and set to 0. The CCM is now only sent to the shader if it has a "ccm" input: Bayer shaders do, mono.frag does not. sizes() keeps no border for monochrome. Signed-off-by: Alain Cousinié --- src/libcamera/software_isp/debayer_egl.cpp | 88 ++++++++++++++++++++-- 1 file changed, 81 insertions(+), 7 deletions(-) diff --git a/src/libcamera/software_isp/debayer_egl.cpp b/src/libcamera/software_isp/debayer_egl.cpp index 33933b11d..fcbc66cd8 100644 --- a/src/libcamera/software_isp/debayer_egl.cpp +++ b/src/libcamera/software_isp/debayer_egl.cpp @@ -61,6 +61,21 @@ int DebayerEGL::getInputConfig(PixelFormat inputFormat, DebayerInputConfig &conf formats::XBGR8888, formats::ABGR8888 }; + if (bayerFormat.order == BayerFormat::Order::MONO) { + if (bayerFormat.packing == BayerFormat::Packing::None) { + config.bpp = (bayerFormat.bitDepth + 7) & ~7; + config.patternSize.width = 2; + config.patternSize.height = 2; + } else if (bayerFormat.packing == BayerFormat::Packing::CSI2) { + config.bpp = bayerFormat.bitDepth; + config.patternSize.width = (bayerFormat.bitDepth == 12) ? 2 : 4; + config.patternSize.height = 2; + } + + config.outputFormats = outputFormats; + return 0; + } + if ((bayerFormat.bitDepth == 8 || bayerFormat.bitDepth == 10) && bayerFormat.packing == BayerFormat::Packing::None && isStandardBayerOrder(bayerFormat.order)) { @@ -172,6 +187,13 @@ int DebayerEGL::initBayerShaders(PixelFormat inputFormat, PixelFormat outputForm shaderStridePixels_ = inputConfig_.stride; switch (inputFormat) { + case libcamera::formats::R8: + case libcamera::formats::R10: + case libcamera::formats::R12: + case libcamera::formats::R16: + firstRed_x_ = 0.0; + firstRed_y_ = 0.0; + break; case libcamera::formats::SBGGR8: case libcamera::formats::SBGGR10_CSI2P: case libcamera::formats::SBGGR12_CSI2P: @@ -201,8 +223,56 @@ int DebayerEGL::initBayerShaders(PixelFormat inputFormat, PixelFormat outputForm return -EINVAL; }; + BayerFormat bayerFormat = BayerFormat::fromPixelFormat(inputFormat); + /* Shader selection */ switch (inputFormat) { + case libcamera::formats::R8: + fragmentShaderData = mono_frag; + vertexShaderData = identity_vert; + egl_.pushEnv(shaderEnv, "#define INV_MAX_VAL (1.0 / 255.0)"); + egl_.pushEnv(shaderEnv, "#define RAW8"); + break; + case libcamera::formats::R10: + fragmentShaderData = mono_frag; + vertexShaderData = identity_vert; + egl_.pushEnv(shaderEnv, "#define INV_MAX_VAL (1.0 / 1023.0)"); + if (bayerFormat.packing == BayerFormat::Packing::None) { + egl_.pushEnv(shaderEnv, "#define RAW10"); + glFormat_ = GL_RG; + bytesPerPixel_ = 2; + } else { + egl_.pushEnv(shaderEnv, "#define RAW10P"); + egl_.pushEnv(shaderEnv, "#define BLOCK_PIXELS 4.0"); + egl_.pushEnv(shaderEnv, "#define BLOCK_BYTES 5.0"); + egl_.pushEnv(shaderEnv, (std::string("#define TEX_WIDTH ") + std::to_string(inputConfig_.stride) + ".0").c_str()); + shaderStridePixels_ = width_; + } + break; + case libcamera::formats::R12: + fragmentShaderData = mono_frag; + vertexShaderData = identity_vert; + egl_.pushEnv(shaderEnv, "#define INV_MAX_VAL (1.0 / 4095.0)"); + if (bayerFormat.packing == BayerFormat::Packing::None) { + egl_.pushEnv(shaderEnv, "#define RAW12"); + glFormat_ = GL_RG; + bytesPerPixel_ = 2; + } else { + egl_.pushEnv(shaderEnv, "#define RAW12P"); + egl_.pushEnv(shaderEnv, "#define BLOCK_PIXELS 2.0"); + egl_.pushEnv(shaderEnv, "#define BLOCK_BYTES 3.0"); + egl_.pushEnv(shaderEnv, (std::string("#define TEX_WIDTH ") + std::to_string(inputConfig_.stride) + ".0").c_str()); + shaderStridePixels_ = width_; + } + break; + case libcamera::formats::R16: + fragmentShaderData = mono_frag; + vertexShaderData = identity_vert; + egl_.pushEnv(shaderEnv, "#define INV_MAX_VAL (1.0 / 65535.0)"); + egl_.pushEnv(shaderEnv, "#define RAW16"); + glFormat_ = GL_RG; + bytesPerPixel_ = 2; + break; case libcamera::formats::SBGGR8: case libcamera::formats::SGBRG8: case libcamera::formats::SGRBG8: @@ -474,9 +544,11 @@ void DebayerEGL::setShaderVariableValues(eGLImage &eglImageIn, const DebayerPara << " textureUniformProjMatrix_ " << textureUniformProjMatrix_; /* Pre-transpose matrix for GLES 2.0. */ - Matrix ccm = params.combinedMatrix.transpose(); - glUniformMatrix3fv(ccmUniformDataIn_, 1, GL_FALSE, ccm.data().data()); - LOG(Debayer, Debug) << " ccmUniformDataIn_ " << ccmUniformDataIn_ << " data " << params.combinedMatrix; + if (ccmUniformDataIn_ != -1) { + Matrix ccm = params.combinedMatrix.transpose(); + glUniformMatrix3fv(ccmUniformDataIn_, 1, GL_FALSE, ccm.data().data()); + LOG(Debayer, Debug) << " ccmUniformDataIn_ " << ccmUniformDataIn_ << " data " << params.combinedMatrix; + } if (lscEnabled_ && params.lscLutVersion != lscLutVersion_) { egl_.updateTexture2D(*eglImageLscLookup_, params.lscLut.data()); @@ -723,12 +795,11 @@ void DebayerEGL::stop() SizeRange DebayerEGL::sizes(PixelFormat inputFormat, const Size &inputSize) { Size patternSize = this->patternSize(inputFormat); - unsigned int borderHeight = patternSize.height; - if (patternSize.isNull()) return {}; /* No need for top/bottom border with a pattern height of 2 */ + unsigned int borderHeight = patternSize.height; if (patternSize.height == 2) borderHeight = 0; @@ -743,9 +814,12 @@ SizeRange DebayerEGL::sizes(PixelFormat inputFormat, const Size &inputSize) return {}; } + BayerFormat bayerFormat = BayerFormat::fromPixelFormat(inputFormat); + bool localIsMono = (bayerFormat.order == BayerFormat::Order::MONO); + return SizeRange(Size(patternSize.width, patternSize.height), - Size((inputSize.width - 2 * patternSize.width) & ~(patternSize.width - 1), - (inputSize.height - 2 * borderHeight) & ~(patternSize.height - 1)), + Size((inputSize.width - (localIsMono ? 0 : 2 * patternSize.width)) & ~(patternSize.width - 1), + (inputSize.height - (localIsMono ? 0 : 2 * borderHeight)) & ~(patternSize.height - 1)), patternSize.width, patternSize.height); } From patchwork Sun Nov 29 15:24:15 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: =?utf-8?q?Alain_Cousini=C3=A9?= X-Patchwork-Id: 29103 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 61B75C3355 for ; Sun, 29 Nov 2026 15:24:49 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 6BFE16AA4A; Sun, 29 Nov 2026 16:24:48 +0100 (CET) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (2048-bit key; unprotected) header.d=laposte.net header.i=@laposte.net header.b="Bk3kz7uR"; dkim-atps=neutral Received: from smtp-outgoing-2001.laposte.net (smtp-outgoing-2001.laposte.net [160.92.124.108]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id A3E696AA33 for ; Sun, 29 Nov 2026 16:24:43 +0100 (CET) X-mail-filterd: {"version":"1.9.7", "queueID":"4jcrYQ2SYjz10MQ4", "contextId": "627d66e3-b458-44f1-ac40-ac396829c45c"} Received: from outgoing-mail.laposte.net (localhost.localdomain [127.0.0.1]) by mlpnf0120.laposte.net (SMTP Server) with ESMTP id 4jcrYQ2SYjz10MQ4; Sun, 29 Nov 2026 16:24:42 +0100 (CET) X-mail-filterd: {"version":"1.9.7", "queueID":"4jcrYQ0qWpz10MQN", "contextId": "8786b6ea-21b3-4deb-b685-9bd3ce1ef0de"} X-lpn-mailing: LEGIT X-lpn-spamrating: 36 X-lpn-spamlevel: not-spam Received: from debian.home (m-dj.hd.free.fr [82.67.82.126]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mlpnf0120.laposte.net (SMTP Server) with ESMTPSA id 4jcrYQ0qWpz10MQN; Sun, 29 Nov 2026 16:24:42 +0100 (CET) From: =?utf-8?q?Alain_Cousini=C3=A9?= To: libcamera-devel@lists.libcamera.org, Milan Zamazal Cc: Hans de Goede , Bryan O'Donoghue , =?utf-8?q?Barnab=C3=A1s_P=C5=91cze?= , Laurent Pinchart , Jai Luthra , =?utf-8?q?Alain_Cousini=C3=A9?= Subject: [PATCH v8 5/6] libcamera: software_isp: Add support for monochrome formats - SOFT Date: Sun, 29 Nov 2026 16:24:15 +0100 Message-ID: <20261129152416.174279-6-alain.cousinie@laposte.net> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261129152416.174279-1-alain.cousinie@laposte.net> References: <20261129152416.174279-1-alain.cousinie@laposte.net> MIME-Version: 1.0 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=laposte.net; s=lpn-wlmd; t=1795965883; bh=6uN1Z1Upsyo9ksWFTF2bgxXHzQOnnt6e4dWTQC5rfAA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References:MIME-Version:Content-Type:Content-Transfer-Encoding; b=Bk3kz7uRM4RO90QfVGOXlNyDK0EVxqjpNAv3gc2FQ/oIKDSjZkFySHsOZI5Y5B33jCnlXlfNubn2MZiQ91Vwvn2Xon1odK4Jtcfv6ka19fcQup1xAHHSrcezHV8uXjU54hHh7O1ML/Prn6CKaS105XgGwHlk3YTy+BZhikv12i8nXDpRO9sLQ9XpZzTvxRYgMqWrRhcznBfJPwtA4IjEjBBQnbxFZkhXeTOdS5+dm74V5nXBo1nE0hQlTTB9ChVatF5byynn5XDDLuRIcoqMV6ub6HMe3ckYMxgIXi8uvdeopJb9nRK3zk9ZxbE6PXZFNtkh7gHy32zgtRduTKfzwQ==; 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 A monochrome sensor has no colour channels, so there is nothing for the colour correction matrix to correct. Skip the CCM in SoftwareIsp::configure() when the input format is monochrome. The CCM and LSC settings are left untouched for Bayer formats: the colour path behaves exactly as before. Signed-off-by: Alain Cousinié --- src/libcamera/software_isp/software_isp.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/libcamera/software_isp/software_isp.cpp b/src/libcamera/software_isp/software_isp.cpp index 627625b4f..39d271728 100644 --- a/src/libcamera/software_isp/software_isp.cpp +++ b/src/libcamera/software_isp/software_isp.cpp @@ -294,7 +294,14 @@ int SoftwareIsp::configure(const StreamConfiguration &inputCfg, if (ret < 0) return ret; - ret = debayer_->configure(inputCfg, outputCfgs, ccmEnabled_, lscEnabled_); + BayerFormat bayerFormat = BayerFormat::fromPixelFormat(inputCfg.pixelFormat); + bool runCcm = ccmEnabled_; + + /* A monochrome sensor has no colour channels: skip the CCM. */ + if (bayerFormat.order == BayerFormat::Order::MONO) + runCcm = false; + + ret = debayer_->configure(inputCfg, outputCfgs, runCcm, lscEnabled_); if (ret < 0) return ret; From patchwork Sun Nov 29 15:24:16 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: =?utf-8?q?Alain_Cousini=C3=A9?= X-Patchwork-Id: 29107 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 BEC9FC3355 for ; Sun, 29 Nov 2026 15:24:56 +0000 (UTC) Received: from lancelot.ideasonboard.com (localhost [IPv6:::1]) by lancelot.ideasonboard.com (Postfix) with ESMTP id 1D2446AA3D; Sun, 29 Nov 2026 16:24:56 +0100 (CET) Authentication-Results: lancelot.ideasonboard.com; dkim=pass (2048-bit key; unprotected) header.d=laposte.net header.i=@laposte.net header.b="QAPA2yaM"; dkim-atps=neutral Received: from smtp-outgoing-1803.laposte.net (smtp-outgoing-1803.laposte.net [160.92.124.104]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id F24606AA38 for ; Sun, 29 Nov 2026 16:24:43 +0100 (CET) X-mail-filterd: {"version":"1.9.7", "queueID":"4jcrYQ5CPkz10MQ4", "contextId": "a36f143c-217d-4b5e-9316-192a4aba5ee2"} Received: from outgoing-mail.laposte.net (localhost.localdomain [127.0.0.1]) by mlpnf0120.laposte.net (SMTP Server) with ESMTP id 4jcrYQ5CPkz10MQ4; Sun, 29 Nov 2026 16:24:42 +0100 (CET) X-mail-filterd: {"version":"1.9.7", "queueID":"4jcrYQ2gHNz10MQQ", "contextId": "46d3f9da-21cc-493e-8957-ab85c5707b4c"} X-lpn-mailing: LEGIT X-lpn-spamrating: 36 X-lpn-spamlevel: not-spam Received: from debian.home (m-dj.hd.free.fr [82.67.82.126]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mlpnf0120.laposte.net (SMTP Server) with ESMTPSA id 4jcrYQ2gHNz10MQQ; Sun, 29 Nov 2026 16:24:42 +0100 (CET) From: =?utf-8?q?Alain_Cousini=C3=A9?= To: libcamera-devel@lists.libcamera.org, Milan Zamazal Cc: Hans de Goede , Bryan O'Donoghue , =?utf-8?q?Barnab=C3=A1s_P=C5=91cze?= , Laurent Pinchart , Jai Luthra , =?utf-8?q?Alain_Cousini=C3=A9?= Subject: [PATCH v8 6/6] libcamera: software_isp: Add support for monochrome formats - TEST NO PROD Date: Sun, 29 Nov 2026 16:24:16 +0100 Message-ID: <20261129152416.174279-7-alain.cousinie@laposte.net> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261129152416.174279-1-alain.cousinie@laposte.net> References: <20261129152416.174279-1-alain.cousinie@laposte.net> MIME-Version: 1.0 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=laposte.net; s=lpn-wlmd; t=1795965883; bh=6P3eBAqe/cT/Fodq5LLY+cfWo8ZnfxURYTx4Jqrr0y4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References:MIME-Version:Content-Type:Content-Transfer-Encoding; b=QAPA2yaM95DYXzuvQ4u9fuBUFEEtYMH7owAiw9asF84xeetsKfFWJEHVMKD/cPu6uezSEQ8RG8blnN14aaL3Pa7tORr+5gXHUHX+IUkA5GMXeAksJeP99xZTnxS2dS5H3ZzB3QXWnK8ChQ3AkkzdwCFN/osBlXPVONX01P3uG1f31E179gmW3sSOvoCH7X6BPYc+FXHju8UhYWwm+EFWybUFaUK53TXEfad7m8EOOCad0YRbNwZ4WJiWeIRuJTFM0NfTU+0coMg0L8CQ9Zywo9o6NykuUc1QYKm/E1IoD/ju78Tyb1Iq3uBKWWHfigNnY90X0Y3ax3UtdycpFj6CFA==; 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 TEST PATCH ONLY, not meant to be merged. Convert a real unpacked R10 monochrome stream on the fly to the format selected by LIBCAMERA_SOFTISP_SIM_MONO (RAW8, RAW10, RAW10P, RAW12, RAW12P or RAW16), to exercise each layout without a matching sensor. The hooks in SoftwareIsp are only set up for monochrome input and do nothing for Bayer formats or when the variable is not set. The simple pipeline handler is modified because the packed format does not work with my og0va1b sensor (640x480) on Intel IPU6 ISYS. This change is therefore only a local workaround, to be able to test with my hardware: it prefers unpacked formats for monochrome sensors only and is not meant to be merged. The Bayer selection is not modified. Tests performed: - Hardware: og0va1b IR camera, 640x480, real unpacked R10, with the CPU debayer (LIBCAMERA_SOFTISP_MODE=cpu) and the GPU debayer, using qcam. Linux 7.4 og0ve1b module modified as proposed in https://lore.kernel.org/all/5bb49b41-368c-4889-9f56-9a477e85694f@laposte.net/ - Full size: the framing and look are comparable between CPU and GPU. - Simulated formats: R8, R12, R16, R10P, R12P with LIBCAMERA_SOFTISP_SIM_MONO. Observed: image visually identical to the R10 reference. - Output smaller than the input (320x240 on 640x480): the CPU crops the centre at the native resolution, while the GPU shrinks the whole image. This comes from the existing EGL projection, which the series does not modify. - Not tested: the simulated formats on real sensors, and a numerical comparison of the levels (no calibration chart) at equal brightness. Signed-off-by: Alain Cousinié --- src/libcamera/pipeline/simple/simple.cpp | 6 +- src/libcamera/software_isp/debayer.cpp | 205 +++++++++++++++++++- src/libcamera/software_isp/debayer.h | 18 ++ src/libcamera/software_isp/software_isp.cpp | 6 +- 4 files changed, 232 insertions(+), 3 deletions(-) diff --git a/src/libcamera/pipeline/simple/simple.cpp b/src/libcamera/pipeline/simple/simple.cpp index 2f7f4c893..13660fd14 100644 --- a/src/libcamera/pipeline/simple/simple.cpp +++ b/src/libcamera/pipeline/simple/simple.cpp @@ -1247,6 +1247,7 @@ CameraConfiguration::Status SimpleCameraConfiguration::validate() const Size &maxOutputSize = pipeConfig->outputSizes.max; bool curCfgPacked = false; bool newCfgPacked = false; + bool newCfgMono = false; /* TEST ONLY, not for merge */ if (pipeConfig_) { BayerFormat curBayerFmt = BayerFormat::fromPixelFormat(pipeConfig_->captureFormat); @@ -1255,6 +1256,7 @@ CameraConfiguration::Status SimpleCameraConfiguration::validate() if (curBayerFmt.isValid() && newBayerFmt.isValid()) { curCfgPacked = curBayerFmt.packing == BayerFormat::Packing::CSI2; newCfgPacked = newBayerFmt.packing == BayerFormat::Packing::CSI2; + newCfgMono = newBayerFmt.order == BayerFormat::Order::MONO; } } @@ -1263,7 +1265,9 @@ CameraConfiguration::Status SimpleCameraConfiguration::validate() captureSize.width >= maxRawStreamSize.width && captureSize.height >= maxRawStreamSize.height) { if (!pipeConfig_ || captureSize < pipeConfig_->captureSize || - (captureSize <= pipeConfig_->captureSize && !curCfgPacked && newCfgPacked)) + (captureSize <= pipeConfig_->captureSize && + (newCfgMono ? (curCfgPacked && !newCfgPacked) /* TEST ONLY: unpacked for mono */ + : (!curCfgPacked && newCfgPacked)))) pipeConfig_ = pipeConfig; } diff --git a/src/libcamera/software_isp/debayer.cpp b/src/libcamera/software_isp/debayer.cpp index 4f6659000..029ced2f0 100644 --- a/src/libcamera/software_isp/debayer.cpp +++ b/src/libcamera/software_isp/debayer.cpp @@ -11,6 +11,10 @@ #include "debayer.h" +#include + +#include + namespace libcamera { /** @@ -98,7 +102,10 @@ LOG_DEFINE_CATEGORY(Debayer) * \param[in] cm The camera manager */ Debayer::Debayer(const CameraManager &cm) - : bench_(cm, "Debayer") + : bench_(cm, "Debayer"), + simAllocator_(DmaBufAllocator::DmaBufAllocatorFlag::CmaHeap | + DmaBufAllocator::DmaBufAllocatorFlag::SystemHeap | + DmaBufAllocator::DmaBufAllocatorFlag::UDmaBuf) { } @@ -339,4 +346,200 @@ bool Debayer::isStandardBayerOrder(BayerFormat::Order order) order == BayerFormat::GRBG || order == BayerFormat::RGGB; } +namespace { + +std::optional parseSimMonoFormat() +{ + const char *env = std::getenv("LIBCAMERA_SOFTISP_SIM_MONO"); + if (!env || !*env) + return std::nullopt; + + std::string val(env); + if (val == "RAW8") + return BayerFormat{ BayerFormat::Order::MONO, 8, BayerFormat::Packing::None }; + if (val == "RAW10") + return BayerFormat{ BayerFormat::Order::MONO, 10, BayerFormat::Packing::None }; + if (val == "RAW10P") + return BayerFormat{ BayerFormat::Order::MONO, 10, BayerFormat::Packing::CSI2 }; + if (val == "RAW12") + return BayerFormat{ BayerFormat::Order::MONO, 12, BayerFormat::Packing::None }; + if (val == "RAW12P") + return BayerFormat{ BayerFormat::Order::MONO, 12, BayerFormat::Packing::CSI2 }; + if (val == "RAW16") + return BayerFormat{ BayerFormat::Order::MONO, 16, BayerFormat::Packing::None }; + + LOG(Debayer, Warning) << "Unknown LIBCAMERA_SOFTISP_SIM_MONO value: " << val; + return std::nullopt; +} + +unsigned int simStrideForFormat(const BayerFormat &fmt, unsigned int width) +{ + unsigned int lineBytes = 0; + if (fmt.packing == BayerFormat::Packing::None) { + lineBytes = width * ((fmt.bitDepth + 7) / 8); + } else { + if (fmt.bitDepth == 10) + lineBytes = (width * 5) / 4; + else if (fmt.bitDepth == 12) + lineBytes = (width * 3) / 2; + } + return (lineBytes + 63) & ~63; +} + +} /* namespace */ + +const StreamConfiguration &Debayer::setupSimulation(const StreamConfiguration &inputCfg) +{ + simActive_ = false; + pendingRealInputs_.clear(); + simMappedBuffer_.reset(); + simFrameBuffer_.reset(); + + auto targetOpt = parseSimMonoFormat(); + if (!targetOpt) + return inputCfg; + + BayerFormat realFmt = BayerFormat::fromPixelFormat(inputCfg.pixelFormat); + if (realFmt.order != BayerFormat::Order::MONO || + realFmt.packing != BayerFormat::Packing::None || + realFmt.bitDepth != 10) { + LOG(Debayer, Warning) << "Simulation expects RAW10 unpacked input, got " + << realFmt; + return inputCfg; + } + + if (realFmt == *targetOpt) + return inputCfg; + + PixelFormat targetPixelFormat = targetOpt->toPixelFormat(); + if (!targetPixelFormat.isValid()) { + LOG(Debayer, Error) << "Simulation: no PixelFormat registered for " + << *targetOpt; + return inputCfg; + } + + simTargetFmt_ = *targetOpt; + realInputStride_ = inputCfg.stride; + + simInputCfg_ = inputCfg; + simInputCfg_.pixelFormat = targetPixelFormat; + simInputCfg_.stride = simStrideForFormat(simTargetFmt_, inputCfg.size.width); + simInputCfg_.frameSize = simInputCfg_.stride * inputCfg.size.height; + + if (!simAllocator_.isValid()) { + LOG(Debayer, Error) << "Simulation: DmaBufAllocator is not valid"; + return inputCfg; + } + + UniqueFD fd = simAllocator_.alloc("softisp-mono-sim", simInputCfg_.frameSize); + if (!fd.isValid()) { + LOG(Debayer, Error) << "Simulation: failed to allocate DmaBuf"; + return inputCfg; + } + + std::vector planes(1); + planes[0].fd = SharedFD(std::move(fd)); + planes[0].offset = 0; + planes[0].length = simInputCfg_.frameSize; + + simFrameBuffer_ = std::make_unique(planes); + simMappedBuffer_ = std::make_unique(simFrameBuffer_.get(), + MappedFrameBuffer::MapFlag::Write); + if (!simMappedBuffer_->isValid()) { + LOG(Debayer, Error) << "Simulation: failed to mmap DmaBuf"; + return inputCfg; + } + + simActive_ = true; + LOG(Debayer, Info) << "Mono simulation enabled: " << realFmt + << " -> " << simTargetFmt_ + << " (stride=" << simInputCfg_.stride << ")"; + + return simInputCfg_; +} + +FrameBuffer *Debayer::simulateInputFrame(FrameBuffer *realInput) +{ + if (!simActive_) + return realInput; + + DmaSyncer syncRead(realInput->planes()[0].fd, DmaSyncer::SyncType::Read); + DmaSyncer syncWrite(simFrameBuffer_->planes()[0].fd, DmaSyncer::SyncType::Write); + + MappedFrameBuffer in(realInput, MappedFrameBuffer::MapFlag::Read); + if (!in.isValid()) + return realInput; + + const unsigned int width = simInputCfg_.size.width; + const unsigned int height = simInputCfg_.size.height; + const uint8_t *srcBase = in.planes()[0].data(); + uint8_t *dstBase = simMappedBuffer_->planes()[0].data(); + + for (unsigned int y = 0; y < height; y++) { + const uint16_t *src = reinterpret_cast(srcBase + y * realInputStride_); + uint8_t *dst = dstBase + y * simInputCfg_.stride; + + if (simTargetFmt_.packing == BayerFormat::Packing::None) { + uint16_t *dst16 = reinterpret_cast(dst); + + switch (simTargetFmt_.bitDepth) { + case 8: + for (unsigned int x = 0; x < width; x++) + dst[x] = static_cast(src[x] >> 2); + break; + case 10: + for (unsigned int x = 0; x < width; x++) + dst16[x] = src[x]; + break; + case 12: + for (unsigned int x = 0; x < width; x++) + dst16[x] = (src[x] << 2) | (src[x] >> 8); + break; + case 16: + for (unsigned int x = 0; x < width; x++) + dst16[x] = (src[x] << 6) | (src[x] >> 4); + break; + } + } else if (simTargetFmt_.packing == BayerFormat::Packing::CSI2) { + switch (simTargetFmt_.bitDepth) { + case 10: + for (unsigned int x = 0; x < width; x += 4) { + dst[0] = static_cast(src[x] >> 2); + dst[1] = static_cast(src[x + 1] >> 2); + dst[2] = static_cast(src[x + 2] >> 2); + dst[3] = static_cast(src[x + 3] >> 2); + dst[4] = (src[x] & 0x03) | ((src[x + 1] & 0x03) << 2) | + ((src[x + 2] & 0x03) << 4) | ((src[x + 3] & 0x03) << 6); + dst += 5; + } + break; + case 12: + for (unsigned int x = 0; x < width; x += 2) { + uint16_t p0 = (src[x] << 2) | (src[x] >> 8); + uint16_t p1 = (src[x + 1] << 2) | (src[x + 1] >> 8); + dst[0] = static_cast(p0 >> 4); + dst[1] = static_cast(p1 >> 4); + dst[2] = (p0 & 0x0f) | ((p1 & 0x0f) << 4); + dst += 3; + } + break; + } + } + } + + simFrameBuffer_->_d()->metadata().planes()[0].bytesused = simInputCfg_.frameSize; + pendingRealInputs_.push_back(realInput); + return simFrameBuffer_.get(); +} + +FrameBuffer *Debayer::restoreRealInputFrame(FrameBuffer *buffer) +{ + if (!simActive_ || buffer != simFrameBuffer_.get() || pendingRealInputs_.empty()) + return buffer; + + FrameBuffer *realInput = pendingRealInputs_.front(); + pendingRealInputs_.pop_front(); + return realInput; +} + } /* namespace libcamera */ diff --git a/src/libcamera/software_isp/debayer.h b/src/libcamera/software_isp/debayer.h index e30a05279..2a45ff5f0 100644 --- a/src/libcamera/software_isp/debayer.h +++ b/src/libcamera/software_isp/debayer.h @@ -11,7 +11,10 @@ #pragma once +#include +#include #include +#include #include #include @@ -22,6 +25,8 @@ #include "libcamera/internal/bayer_format.h" #include "libcamera/internal/dma_buf_allocator.h" +#include "libcamera/internal/framebuffer.h" +#include "libcamera/internal/mapped_framebuffer.h" #include "libcamera/internal/software_isp/benchmark.h" #include "libcamera/internal/software_isp/debayer_params.h" @@ -82,9 +87,22 @@ public: bool swapRedBlueGains_; Benchmark bench_; + const StreamConfiguration &setupSimulation(const StreamConfiguration &inputCfg); + FrameBuffer *simulateInputFrame(FrameBuffer *realInput); + FrameBuffer *restoreRealInputFrame(FrameBuffer *buffer); + private: virtual Size patternSize(PixelFormat inputFormat) = 0; + DmaBufAllocator simAllocator_; + StreamConfiguration simInputCfg_; + BayerFormat simTargetFmt_; + std::unique_ptr simFrameBuffer_; + std::unique_ptr simMappedBuffer_; + std::deque pendingRealInputs_; + unsigned int realInputStride_ = 0; + bool simActive_ = false; + protected: void dmaSyncBegin(std::vector &dmaSyncers, FrameBuffer *input, FrameBuffer *output); static bool isStandardBayerOrder(BayerFormat::Order order); diff --git a/src/libcamera/software_isp/software_isp.cpp b/src/libcamera/software_isp/software_isp.cpp index 39d271728..9c4cb8e1f 100644 --- a/src/libcamera/software_isp/software_isp.cpp +++ b/src/libcamera/software_isp/software_isp.cpp @@ -301,7 +301,9 @@ int SoftwareIsp::configure(const StreamConfiguration &inputCfg, if (bayerFormat.order == BayerFormat::Order::MONO) runCcm = false; - ret = debayer_->configure(inputCfg, outputCfgs, runCcm, lscEnabled_); + const StreamConfiguration &debayerCfg = + bayerFormat.order == BayerFormat::Order::MONO ? debayer_->setupSimulation(inputCfg) : inputCfg; + ret = debayer_->configure(debayerCfg, outputCfgs, runCcm, lscEnabled_); if (ret < 0) return ret; @@ -441,6 +443,7 @@ void SoftwareIsp::stop() void SoftwareIsp::process(uint32_t frame, FrameBuffer *input, FrameBuffer *output) { ipa_->computeParams(frame); + input = debayer_->simulateInputFrame(input); debayer_->invokeMethod(&Debayer::process, ConnectionTypeQueued, frame, input, output, debayerParams_); } @@ -462,6 +465,7 @@ void SoftwareIsp::statsReady(uint32_t frame, uint32_t bufferId) void SoftwareIsp::inputReady(FrameBuffer *input) { + input = debayer_->restoreRealInputFrame(input); ASSERT(queuedInputBuffers_.front() == input); queuedInputBuffers_.pop_front(); inputBufferReady.emit(input);