From 3e14b5bdd5429a601b956261edf2cc0547ab0aac Mon Sep 17 00:00:00 2001 From: Hinnka Date: Fri, 25 Sep 2026 10:32:52 +0800 Subject: [PATCH] feat: Bento region admission --- CLAUDE.md | 3 + .../processor/BentoRegionAdmission.kt | 298 +++++++----------- .../processor/GlesMgcRawSpatialShaders.kt | 15 +- .../processor/GlesMgcRawSpatialStacker.kt | 98 +++--- 4 files changed, 187 insertions(+), 227 deletions(-) create mode 100644 CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..59264e9f --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +AGENTS.md + +优先说中文 \ No newline at end of file diff --git a/app/src/main/java/com/hinnka/mycamera/processor/BentoRegionAdmission.kt b/app/src/main/java/com/hinnka/mycamera/processor/BentoRegionAdmission.kt index ad2e40a4..898bd67c 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/BentoRegionAdmission.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/BentoRegionAdmission.kt @@ -1,51 +1,41 @@ package com.hinnka.mycamera.processor -import kotlin.math.sqrt - -/** Region-local highlight admission on the RAW/2 guide and 8-quad alignment grids. */ +/** + * Highlight-region flow resolution on the RAW/2 guide and 8-quad alignment grids. + * + * Inside a clipped reference highlight the reference is a flat plateau, so the forward flow + * measured there carries no geometry and must never reach the merge. Every highlight tile takes + * its flow from observable, forward/backward-consistent tiles instead: the collar surrounding + * its connected highlight, or, when that collar is too sparse, the frame-wide supported flow. + * Residual misregistration is then caught by the ultrashort ghost fallback and inpainting gate. + */ internal class BentoRegionAdmission( private val width: Int, private val height: Int, private val gridWidth: Int, private val gridHeight: Int, private val tileStride: Int, - highlightMask: ByteArray, + private val highlightMask: ByteArray, private val alignment: FloatArray, private val support: FloatArray, ) { - private data class Region( - val tiles: IntArray, - val flow: FloatArray, - var admitted: Boolean, - ) - data class Result( val alignment: FloatArray, - val admittedRegions: Int, - val rejectedGeometryRegions: Int, + val regions: Int, + val collarRegions: Int, + val globalRegions: Int, ) - data class FinalMask( - val pixels: ByteArray, - val admittedRegions: Int, - val rejectedInpaintingRegions: Int, - val activePixels: Int, - val largestInpaintingArea: Int, - ) - - private val labels = IntArray(width * height) { -1 } - private val regions = ArrayList() - private val mask = highlightMask - private val queue = IntArray(mask.size) - private val tileHasHighlight = BooleanArray(gridWidth * gridHeight) + private val tileCount = gridWidth * gridHeight + private val tileHasHighlight = BooleanArray(tileCount) init { require(width > 0 && height > 0 && gridWidth > 0 && gridHeight > 0 && tileStride > 0) - require(mask.size == width * height) - require(alignment.size == gridWidth * gridHeight * 4) + require(highlightMask.size == width * height) + require(alignment.size == tileCount * 4) require(support.size == alignment.size) - for (pixel in mask.indices) { - if (mask[pixel].toInt() == 0) continue + for (pixel in highlightMask.indices) { + if (highlightMask[pixel].toInt() == 0) continue val x = pixel % width val y = pixel / width tileHasHighlight[ @@ -55,185 +45,133 @@ internal class BentoRegionAdmission( } } - fun resolveGeometry(): Result { - val tileOwner = IntArray(gridWidth * gridHeight) { -1 } - val tileStamp = IntArray(tileOwner.size) { -1 } - for (start in mask.indices) { - if (mask[start].toInt() == 0 || labels[start] >= 0) continue - val regionIndex = regions.size + /** Returns null when no tile in the frame has verifiable flow to transfer. */ + fun resolveGeometry(): Result? { + val globalFlow = globalSupportedFlow() + // Pixel regions that share an alignment tile must share that tile's single flow, so + // flow is resolved per 8-connected component of highlight tiles. + val groupOfTile = IntArray(tileCount) { -1 } + val queue = IntArray(tileCount) + val groups = ArrayList() + for (start in 0 until tileCount) { + if (!tileHasHighlight[start] || groupOfTile[start] >= 0) continue + val group = groups.size var head = 0 var tail = 1 queue[0] = start - labels[start] = regionIndex - val tiles = ArrayList() + groupOfTile[start] = group while (head < tail) { - val pixel = queue[head++] - val x = pixel % width - val y = pixel / width - val tile = (y / tileStride).coerceAtMost(gridHeight - 1) * gridWidth + - (x / tileStride).coerceAtMost(gridWidth - 1) - if (tileStamp[tile] != regionIndex) { - tileStamp[tile] = regionIndex - tiles += tile - } - for (ny in maxOf(0, y - 1)..minOf(height - 1, y + 1)) { - for (nx in maxOf(0, x - 1)..minOf(width - 1, x + 1)) { - val neighbor = ny * width + nx - if (labels[neighbor] < 0 && mask[neighbor].toInt() != 0) { - labels[neighbor] = regionIndex + val tile = queue[head++] + val tx = tile % gridWidth + val ty = tile / gridWidth + for (ny in maxOf(0, ty - 1)..minOf(gridHeight - 1, ty + 1)) { + for (nx in maxOf(0, tx - 1)..minOf(gridWidth - 1, tx + 1)) { + val neighbor = ny * gridWidth + nx + if (tileHasHighlight[neighbor] && groupOfTile[neighbor] < 0) { + groupOfTile[neighbor] = group queue[tail++] = neighbor } } } } - val flows = FloatArray(tiles.size * 2) - var admitted = true - for (index in tiles.indices) { - val tile = tiles[index] - val inferred = inferFromCollar(tile) - if (inferred == null) { - admitted = false - break - } - flows[index * 2] = inferred.first - flows[index * 2 + 1] = inferred.second - } - regions += Region(tiles.toIntArray(), flows, admitted) - if (admitted) { - for (tile in tiles) { - val prior = tileOwner[tile] - if (prior >= 0 && prior != regionIndex) { - regions[prior].admitted = false - admitted = false - } - tileOwner[tile] = regionIndex - } - regions[regionIndex].admitted = admitted - } + groups += queue.copyOf(tail) } + if (groups.isNotEmpty() && globalFlow == null) return null + val corrected = alignment.copyOf() - for (region in regions) { - if (!region.admitted) continue - for (index in region.tiles.indices) { - val offset = region.tiles[index] * 4 - corrected[offset] = region.flow[index * 2] - corrected[offset + 1] = region.flow[index * 2 + 1] + val collarStamp = IntArray(tileCount) { -1 } + val collar = IntArray(tileCount) + var collarRegions = 0 + for ((group, tiles) in groups.withIndex()) { + var collarCount = 0 + for (tile in tiles) { + val tx = tile % gridWidth + val ty = tile / gridWidth + for (ny in maxOf(0, ty - COLLAR_RADIUS)..minOf(gridHeight - 1, ty + COLLAR_RADIUS)) { + for (nx in maxOf(0, tx - COLLAR_RADIUS)..minOf(gridWidth - 1, tx + COLLAR_RADIUS)) { + val neighbor = ny * gridWidth + nx + if (tileHasHighlight[neighbor] || collarStamp[neighbor] == group) continue + collarStamp[neighbor] = group + if (isSupported(neighbor)) collar[collarCount++] = neighbor + } + } + } + val fromCollar = collarCount >= MIN_COLLAR_TILES + if (fromCollar) collarRegions++ + for (tile in tiles) { + val offset = tile * 4 + if (fromCollar) { + interpolateFromCollar(tile, collar, collarCount, corrected, offset) + } else { + val flow = checkNotNull(globalFlow) + corrected[offset] = flow[0] + corrected[offset + 1] = flow[1] + } } } return Result( - corrected, - regions.count { it.admitted }, - regions.count { !it.admitted }, + alignment = corrected, + regions = groups.size, + collarRegions = collarRegions, + globalRegions = groups.size - collarRegions, ) } - private fun inferFromCollar(tile: Int): Pair? { - val cx = tile % gridWidth - val cy = tile / gridWidth - var total = 0f - var sumX = 0f - var sumY = 0f - var sumNorm = 0f - var count = 0 - val sectors = BooleanArray(4) - for (dy in -COLLAR_RADIUS..COLLAR_RADIUS) { - for (dx in -COLLAR_RADIUS..COLLAR_RADIUS) { - if (dx == 0 && dy == 0) continue - val x = cx + dx - val y = cy + dy - if (x !in 0 until gridWidth || y !in 0 until gridHeight) continue - val neighbor = y * gridWidth + x - if (tileHasHighlight[neighbor]) continue - val confidence = support[neighbor * 4] - if (!confidence.isFinite() || confidence < MIN_SUPPORT) continue - val fx = alignment[neighbor * 4] - val fy = alignment[neighbor * 4 + 1] - if (!fx.isFinite() || !fy.isFinite()) continue - val weight = confidence / (1f + dx * dx + dy * dy) - total += weight - sumX += fx * weight - sumY += fy * weight - sumNorm += (fx * fx + fy * fy) * weight - count++ - sectors[if (kotlin.math.abs(dx) >= kotlin.math.abs(dy)) { - if (dx < 0) 0 else 1 - } else { - if (dy < 0) 2 else 3 - }] = true - } - } - if (count < MIN_COLLAR_TILES || sectors.count { it } < MIN_COLLAR_SECTORS || total <= 0f) { - return null - } - val x = sumX / total - val y = sumY / total - val sigma = sqrt(maxOf(0f, sumNorm / total - x * x - y * y)) - return if (sigma.isFinite() && sigma <= MAX_FLOW_SIGMA) x to y else null + private fun isSupported(tile: Int): Boolean { + val confidence = support[tile * 4] + return !tileHasHighlight[tile] && confidence.isFinite() && confidence >= MIN_SUPPORT && + alignment[tile * 4].isFinite() && alignment[tile * 4 + 1].isFinite() } - fun finish( - adjustedMask: ByteArray, - inpaintingMask: ByteArray, - maximumInpaintingArea: Int, - ): FinalMask { - require(adjustedMask.size == mask.size && inpaintingMask.size == mask.size) - // A saturated short core does not invalidate recoverable pixels elsewhere in the - // highlight. Region admission describes alignment and inpainting reliability; - // the RGB output stage clips against Camera White in the supplying exposure domain. - val visited = ByteArray(mask.size) - val largest = IntArray(regions.size) - for (start in inpaintingMask.indices) { - val region = labels[start] - if (region < 0 || visited[start].toInt() != 0 || inpaintingMask[start].toInt() == 0) continue - var head = 0 - var tail = 1 - queue[0] = start - visited[start] = 1 - while (head < tail) { - val pixel = queue[head++] - val x = pixel % width - val y = pixel / width - for (ny in maxOf(0, y - 1)..minOf(height - 1, y + 1)) { - for (nx in maxOf(0, x - 1)..minOf(width - 1, x + 1)) { - val neighbor = ny * width + nx - if (labels[neighbor] == region && visited[neighbor].toInt() == 0 && - inpaintingMask[neighbor].toInt() != 0 - ) { - visited[neighbor] = 1 - queue[tail++] = neighbor - } - } + /** Confidence-weighted per-axis median of every supported non-highlight tile. */ + private fun globalSupportedFlow(): FloatArray? { + val tiles = (0 until tileCount).filter(::isSupported) + if (tiles.size < MIN_COLLAR_TILES) return null + return FloatArray(2) { axis -> + val sorted = tiles.sortedBy { alignment[it * 4 + axis] } + val half = sorted.sumOf { support[it * 4].toDouble() } * 0.5 + var accumulated = 0.0 + var median = alignment[sorted.last() * 4 + axis] + for (tile in sorted) { + accumulated += support[tile * 4].toDouble() + if (accumulated >= half) { + median = alignment[tile * 4 + axis] + break } } - largest[region] = maxOf(largest[region], tail) + median } - var rejectedInpainting = 0 - for (index in regions.indices) { - if (regions[index].admitted && largest[index] >= maximumInpaintingArea) { - regions[index].admitted = false - rejectedInpainting++ - } + } + + /** Inverse-square-distance, confidence-weighted interpolation over the group's collar. */ + private fun interpolateFromCollar( + tile: Int, + collar: IntArray, + collarCount: Int, + output: FloatArray, + offset: Int, + ) { + val cx = tile % gridWidth + val cy = tile / gridWidth + var total = 0.0 + var sumX = 0.0 + var sumY = 0.0 + for (index in 0 until collarCount) { + val neighbor = collar[index] + val dx = neighbor % gridWidth - cx + val dy = neighbor / gridWidth - cy + val weight = support[neighbor * 4].toDouble() / (dx * dx + dy * dy).toDouble() + total += weight + sumX += alignment[neighbor * 4] * weight + sumY += alignment[neighbor * 4 + 1] * weight } - var active = 0 - for (pixel in adjustedMask.indices) { - val region = labels[pixel] - if (region < 0 || !regions[region].admitted) adjustedMask[pixel] = 0 - if (adjustedMask[pixel].toInt() != 0) active++ - } - return FinalMask( - adjustedMask, - regions.count { it.admitted }, - rejectedInpainting, - active, - largest.maxOrNull() ?: 0, - ) + output[offset] = (sumX / total).toFloat() + output[offset + 1] = (sumY / total).toFloat() } private companion object { const val COLLAR_RADIUS = 4 const val MIN_SUPPORT = 0.4f const val MIN_COLLAR_TILES = 4 - const val MIN_COLLAR_SECTORS = 3 - const val MAX_FLOW_SIGMA = 0.6f } } diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialShaders.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialShaders.kt index 21627617..1aa8b1e4 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialShaders.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialShaders.kt @@ -969,6 +969,7 @@ internal object GlesMgcRawSpatialShaders { precision highp sampler2D; precision highp int; uniform sampler2D uBaseFrame; + uniform sampler2D uSensorClipping; uniform ivec2 uSize; uniform float uMaxRgbClippingThreshold; out float oHighlightMask; @@ -985,7 +986,11 @@ internal object GlesMgcRawSpatialShaders { float clippedRatio = (maxIntensity - uMaxRgbClippingThreshold) / (1.0 - uMaxRgbClippingThreshold); - oHighlightMask = clamp(clippedRatio, 0.0, 1.0); + // The WB-balanced, filtered guide can stay below the ramp while a native CFA + // phase is already saturated. Those reference samples carry no highlight detail + // and must be replaced by the ultrashort like guide-detected clipping. + float sensorClipped = texelFetch(uSensorClipping, p, 0).r; + oHighlightMask = max(clamp(clippedRatio, 0.0, 1.0), sensorClipped); } """.trimIndent() @@ -1163,10 +1168,14 @@ internal object GlesMgcRawSpatialShaders { float smallest = min(base8.r, min(base8.g, base8.b)); float largest = max(base8.r, max(base8.g, base8.b)); float middle = base8.r + base8.g + base8.b - smallest - largest; + // A rejected short over a fully clipped reference (guide ramp complete or a + // sensor-clipped CFA phase) leaves only the clipped plateau, which renders as a + // flat gray patch in the ultrashort domain. It is a hole regardless of its hue. oInpaintingMask = fallback > 0.0 && - smallest >= uMinRgbForInpainting && - middle >= uMaxRgbClippingThreshold + (highlight >= 1.0 || + (smallest >= uMinRgbForInpainting && + middle >= uMaxRgbClippingThreshold)) ? 1.0 : 0.0; diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialStacker.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialStacker.kt index 1a3736d6..7cc0e8d1 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialStacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialStacker.kt @@ -965,10 +965,23 @@ internal class GlesMgcRawSpatialStacker( GLES30.GL_R8, GLES30.GL_NEAREST, ).also { output -> + // Assess reference saturation from native CFA codes on the RAW/2 guide + // grid, so no clipped reference sample stays outside the highlight mask. + val referenceSensorClipping = renderAlignedRawClippingMask( + rawTexture = referenceRaw, + flow = ConvertedAlignment.constant(zeroFlow), + calibration = referenceCalibration, + outputWidth = guideWidth, + outputHeight = guideHeight, + bayerQuadsPerTexel = 1, + clippingThreshold = BENTO_MAX_RGB_CLIPPING / 255f, + ) renderBentoHighlightMask( baseFrame = referenceGuide, + sensorClipping = referenceSensorClipping, outputMask = output, ) + releaseOwnedTexture(referenceSensorClipping, "reference sensor clipping") } } else { 0 @@ -1150,6 +1163,12 @@ internal class GlesMgcRawSpatialStacker( "Bento collar support", ) releaseTexturesFrom(reverseTextureStart) + val forwardAlignmentValues = readRgba32f( + forwardAlignment.texture, + forwardAlignment.gridWidth, + forwardAlignment.gridHeight, + "Bento forward alignment", + ) val admission = BentoRegionAdmission( width = guideWidth, height = guideHeight, @@ -1160,18 +1179,18 @@ internal class GlesMgcRawSpatialStacker( referenceHighlightMask, "Bento base highlight regions", ).also { baseHighlightMask = it }, - alignment = readRgba32f(forwardAlignment.texture, - forwardAlignment.gridWidth, forwardAlignment.gridHeight, - "Bento forward alignment"), + alignment = forwardAlignmentValues, support = collarSupportValues, ) + // Null means no tile in the frame verifies the short's geometry; the + // measured flow is kept only to finish the masks and Bento is rejected. val geometry = admission.resolveGeometry() val alignment = forwardAlignment.copy(texture = createFloatTexture( width = forwardAlignment.gridWidth, height = forwardAlignment.gridHeight, internalFormat = GLES30.GL_RGBA32F, format = GLES30.GL_RGBA, - values = geometry.alignment, + values = geometry?.alignment ?: forwardAlignmentValues, filter = GLES30.GL_NEAREST, )) bentoAlignAndAdmissionNs = System.nanoTime() - alignmentStartNs @@ -1235,22 +1254,14 @@ internal class GlesMgcRawSpatialStacker( label = "MGC Bento assessment masks", checkGlError = ::checkGlError, ) - val assessmentBaseHighlightMask = checkNotNull(baseHighlightMask) - val inpaintingPixels = readR8Mask(inpaintingMask, "Bento inpainting mask") - val ultrashortClippingPixels = readR8Mask( - ultrashortClippingMask, - "Bento ultrashort clipping mask", - ) - val finalMask = admission.finish( - adjustedMask = readR8Mask(checkNotNull(bentoMask), "Bento adjusted mask"), - inpaintingMask = inpaintingPixels, - maximumInpaintingArea = BENTO_MAX_INPAINTING_COMPONENT_AREA, - ) - uploadR8Mask(checkNotNull(bentoMask), finalMask.pixels, "Bento regional mask") val assessment = assessBentoMasks( - baseHighlightMask = assessmentBaseHighlightMask, - ultrashortClippingMask = ultrashortClippingPixels, - finalMask = finalMask, + baseHighlightMask = checkNotNull(baseHighlightMask), + inpaintingMask = readR8Mask(inpaintingMask, "Bento inpainting mask"), + ultrashortClippingMask = readR8Mask( + ultrashortClippingMask, + "Bento ultrashort clipping mask", + ), + hasAlignmentSupport = geometry != null, ) PLog.i( TAG, @@ -1259,10 +1270,9 @@ internal class GlesMgcRawSpatialStacker( "clippedRatio=${assessment.clippedPixelRatio} " + "largestInpaintingArea=${assessment.largestInpaintingArea} " + "ultrashortOverlap=${assessment.ultrashortClippingOverlap} " + - "regions=${finalMask.admittedRegions}/" + - "${finalMask.admittedRegions + geometry.rejectedGeometryRegions + finalMask.rejectedInpaintingRegions} " + - "rejectedGeometry=${geometry.rejectedGeometryRegions} " + - "rejectedInpainting=${finalMask.rejectedInpaintingRegions} " + + "regions=${geometry?.regions} " + + "collarFlowRegions=${geometry?.collarRegions} " + + "globalFlowRegions=${geometry?.globalRegions} " + "shortClippingDomain=sensor " + "shortClippingDiagnosticOnly=true " + "exposureRatio=$exposureRatio earlyGate=false " + @@ -5318,10 +5328,12 @@ internal class GlesMgcRawSpatialStacker( private fun renderBentoHighlightMask( baseFrame: Int, + sensorClipping: Int, outputMask: Int, ) { GLES30.glUseProgram(bentoHighlightProgram) bindTexture(bentoHighlightProgram, "uBaseFrame", 0, baseFrame) + bindTexture(bentoHighlightProgram, "uSensorClipping", 1, sensorClipping) uniform2i(bentoHighlightProgram, "uSize", guideWidth, guideHeight) uniform1f( bentoHighlightProgram, @@ -5372,24 +5384,6 @@ internal class GlesMgcRawSpatialStacker( return FloatArray(count).also { buffer.asFloatBuffer().get(it) } } - private fun uploadR8Mask(texture: Int, pixels: ByteArray, label: String) { - require(pixels.size == guideWidth * guideHeight) - val buffer = ByteBuffer.allocateDirect(pixels.size).apply { - put(pixels) - rewind() - } - GLES30.glBindBuffer(GLES30.GL_PIXEL_UNPACK_BUFFER, 0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture) - GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1) - GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, 0) - GLES30.glTexSubImage2D( - GLES30.GL_TEXTURE_2D, 0, 0, 0, guideWidth, guideHeight, - GLES30.GL_RED, GLES30.GL_UNSIGNED_BYTE, buffer, - ) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) - checkGlError(label) - } - private fun renderAlignedRawClippingMask( rawTexture: Int, flow: ConvertedAlignment, @@ -6572,12 +6566,14 @@ internal class GlesMgcRawSpatialStacker( private fun assessBentoMasks( baseHighlightMask: ByteArray, + inpaintingMask: ByteArray, ultrashortClippingMask: ByteArray, - finalMask: BentoRegionAdmission.FinalMask, + hasAlignmentSupport: Boolean, ): BentoAssessment { val guideMaskSize = guideWidth * guideHeight require( baseHighlightMask.size == guideMaskSize && + inpaintingMask.size == guideMaskSize && ultrashortClippingMask.size == guideMaskSize, ) var clippedPixels = 0 @@ -6597,12 +6593,26 @@ internal class GlesMgcRawSpatialStacker( } else { 0f } - val reason = if (finalMask.activePixels > 0) "none" else "no_admitted_region" + // Accepting the ultrashort moves the whole output into its exposure domain, where any + // reference-only clipped plateau renders at 1/ratio as a flat gray patch. A ghost hole + // too large to inpaint therefore rejects the ultrashort for the frame, not per region. + val largestInpaintingArea = BentoFallbackTopology.largestEightConnectedComponentArea( + inpaintingMask, + guideWidth, + guideHeight, + ) + val reason = when { + clippedPixels == 0 -> "no_clipped_pixels" + !hasAlignmentSupport -> "no_alignment_support" + largestInpaintingArea >= BENTO_MAX_INPAINTING_COMPONENT_AREA -> + "large_hole_needing_inpainting" + else -> "none" + } return BentoAssessment( accepted = reason == "none", reason = reason, clippedPixelRatio = clippedRatio, - largestInpaintingArea = finalMask.largestInpaintingArea, + largestInpaintingArea = largestInpaintingArea, ultrashortClippingOverlap = ultrashortOverlap, ) }