feat: compute shader implementation for block Lucas-Kanade alignment

This commit is contained in:
zhoubinjia committed 2026-11-05 13:09:10 +08:00
1 parent 85accc7073
commit 4cf9bcabd0
2 files changed
+158 -243

No files matched your search

@@ -2400,8 +2400,7 @@ internal object GlesMgcRawSpatialShaders {
* been expanded onto this LK grid by UpsampleAlignment. Bilinear weights below are the
* image-warp S16 Q15 conversion and saturating rounded shift used by the AArch64 worker.
*/
val blockLucasKanade = """
#version 300 es
private val blockLucasKanadeCommon = """
precision highp float;
precision highp sampler2D;
precision highp int;
@@ -2416,14 +2415,16 @@ internal object GlesMgcRawSpatialShaders {
uniform int uTileSize;
uniform int uNormalize;
uniform int uHasInitialAlignment;
out vec4 oAlignment;
float referenceAt(ivec2 p) {
return float(texelFetch(
int referenceValueAt(ivec2 p) {
return texelFetch(
uReference,
clamp(p, ivec2(0), uImageSize - ivec2(1)),
0
).r);
).r;
}
float referenceAt(ivec2 p) {
return float(referenceValueAt(p));
}
vec2 gradientAt(ivec2 p) {
return clamp(
@@ -2455,7 +2456,7 @@ internal object GlesMgcRawSpatialShaders {
? biased / 32768
: -((-biased + 32767) / 32768);
}
float warpedCurrentAt(vec2 p) {
int warpedCurrentValueAt(vec2 p) {
vec2 bounded = clamp(
p,
vec2(0.0),
@@ -2475,17 +2476,48 @@ internal object GlesMgcRawSpatialShaders {
currentAt(p0 + ivec2(1, 0)) * w10 +
currentAt(p0 + ivec2(0, 1)) * w01 +
currentAt(p0 + ivec2(1, 1)) * w11;
return float(clamp(roundedShiftRight15(weighted), -32768, 32767));
return clamp(roundedShiftRight15(weighted), -32768, 32767);
}
void main() {
ivec2 tile = ivec2(gl_FragCoord.xy);
vec3 initialAlignment = uHasInitialAlignment != 0
float warpedCurrentAt(vec2 p) {
return float(warpedCurrentValueAt(p));
}
vec3 initialAlignmentAt(ivec2 tile) {
return uHasInitialAlignment != 0
? texelFetch(
uInitialAlignment,
clamp(tile, ivec2(0), uGridSize - ivec2(1)),
0
).xyz
: vec3(0.0);
}
vec4 solveAlignment(ivec2 tile, vec3 initialAlignment, vec2 target, float count) {
vec4 products0 = texelFetch(uProducts0, tile, 0);
float bx = 0.5 * target.x / count;
float by = 0.5 * target.y / count;
// det(H) crossed a Float32 texture boundary in the reference pass. Keep +1
// here: evaluating 1 + xx*yy - xy*xy can turn a rank-one tile into 1/0.
float inverseDeterminant = 1.0 / (1.0 + products0.w);
vec2 delta = inverseDeterminant * vec2(
products0.z * by - products0.y * bx,
products0.z * bx - products0.x * by
);
// BlockLucasKanadeHalide updates XY and carries the incoming candidate
// cost through unchanged in its third planar channel.
return vec4(
initialAlignment.xy + clamp(delta, vec2(-1.0), vec2(1.0)),
initialAlignment.z,
0.0
);
}
""".trimIndent()
/** Fragment fallback for GLES 3.0: one fragment walks a whole tile serially. */
val blockLucasKanade = "#version 300 es\n" + blockLucasKanadeCommon + "\n" + """
out vec4 oAlignment;
void main() {
ivec2 tile = ivec2(gl_FragCoord.xy);
vec3 initialAlignment = initialAlignmentAt(tile);
vec2 flow = initialAlignment.xy;
ivec2 origin = (tile + ivec2(1)) * uTileStride;
float count = float(uTileSize * uTileSize);
@@ -2503,8 +2535,7 @@ internal object GlesMgcRawSpatialShaders {
meanResidual /= count;
}
float targetX = 0.0;
float targetY = 0.0;
vec2 target = vec2(0.0);
for (int y = 0; y < 64; ++y) {
if (y >= uTileSize) break;
for (int x = 0; x < 64; ++x) {
@@ -2514,119 +2545,77 @@ internal object GlesMgcRawSpatialShaders {
// and reference*gradient loses small residuals to Float32 cancellation.
float residual = warpedCurrentAt(vec2(p) + flow) -
referenceAt(p) - meanResidual;
vec2 gradient = gradientAt(p);
targetX += residual * gradient.x;
targetY += residual * gradient.y;
target += residual * gradientAt(p);
}
}
vec4 products0 = texelFetch(uProducts0, tile, 0);
float bx = 0.5 * targetX / count;
float by = 0.5 * targetY / count;
// det(H) crossed a Float32 texture boundary in the reference pass. Keep +1
// here: evaluating 1 + xx*yy - xy*xy can turn a rank-one tile into 1/0.
float inverseDeterminant = 1.0 / (1.0 + products0.w);
vec2 delta = inverseDeterminant * vec2(
products0.z * by - products0.y * bx,
products0.z * bx - products0.x * by
);
flow += clamp(delta, vec2(-1.0), vec2(1.0));
// BlockLucasKanadeHalide updates XY and carries the incoming candidate
// cost through unchanged in its third planar channel.
oAlignment = vec4(flow, initialAlignment.z, 0.0);
oAlignment = solveAlignment(tile, initialAlignment, target, count);
}
""".trimIndent()
/**
* AlignL1Halide UInt16 path (0x3be3c58). Candidate ties retain the first
* candidate. The quadratic correction is exactly
* .5*(Eminus-Eplus)/(Eminus+Eplus-2*Ecenter).
* Compute form of [blockLucasKanade]: one 128-lane work group solves one tile. Lanes stride
* the tile's pixels and reduce through shared memory. The normalize mean is an exact Int32
* sum (|residual| <= 65535 over at most 64x64 pixels), so it equals the serial Float32 sum
* whenever that sum is exact; the gradient products are a Float32 tree sum, whose rounding
* differs from the serial fragment order only in the last bits.
*/
val alignL1 = """
#version 300 es
precision highp float;
precision highp sampler2D;
precision highp int;
precision highp isampler2D;
uniform highp isampler2D uReference;
uniform highp isampler2D uCurrent;
uniform sampler2D uInitialAlignment;
uniform ivec2 uImageSize;
uniform ivec2 uGridSize;
uniform ivec2 uInitialGridSize;
uniform int uTileStride;
uniform int uTileSize;
uniform int uSearchRadius;
uniform float uInitialScale;
uniform int uHasInitialAlignment;
out vec4 oAlignment;
val blockLucasKanadeCompute = "#version 310 es\n" + blockLucasKanadeCommon + "\n" + """
layout(local_size_x = 128, local_size_y = 1, local_size_z = 1) in;
layout(rgba32f, binding = 0) writeonly uniform highp image2D uOutput;
shared int sResidualSum[128];
shared vec2 sTarget[128];
float valueAt(highp isampler2D image, ivec2 p) {
return float(texelFetch(
image,
clamp(p, ivec2(0), uImageSize - ivec2(1)),
0
).r);
}
float sadAt(ivec2 origin, ivec2 displacement) {
float sad = 0.0;
for (int y = 0; y < 16; ++y) {
if (y >= uTileSize) break;
for (int x = 0; x < 16; ++x) {
if (x >= uTileSize) break;
ivec2 p = origin + ivec2(x, y);
sad += abs(
valueAt(uReference, p) -
valueAt(uCurrent, p + displacement)
);
}
}
return sad / float(uTileSize * uTileSize);
}
void main() {
ivec2 tile = ivec2(gl_FragCoord.xy);
ivec2 initialTile = clamp(
ivec2(
floor(
(vec2(tile) + 0.5) *
vec2(uInitialGridSize) / vec2(uGridSize)
)
),
ivec2(0),
uInitialGridSize - ivec2(1)
);
vec2 initial = uHasInitialAlignment != 0
? texelFetch(uInitialAlignment, initialTile, 0).xy * uInitialScale
: vec2(0.0);
ivec2 center = ivec2(round(initial));
ivec2 origin = tile * uTileStride;
ivec2 best = center;
float bestCost = sadAt(origin, center);
for (int y = -3; y <= 3; ++y) {
for (int x = -3; x <= 3; ++x) {
if (abs(x) > uSearchRadius || abs(y) > uSearchRadius) continue;
if (x == 0 && y == 0) continue;
ivec2 candidate = center + ivec2(x, y);
float cost = sadAt(origin, candidate);
if (cost < bestCost) {
bestCost = cost;
best = candidate;
}
ivec2 tile = ivec2(gl_WorkGroupID.xy);
int lane = int(gl_LocalInvocationIndex);
vec3 initialAlignment = initialAlignmentAt(tile);
vec2 flow = initialAlignment.xy;
ivec2 origin = (tile + ivec2(1)) * uTileStride;
int pixelCount = uTileSize * uTileSize;
// Barriers stay outside uNormalize branches; disabled lanes contribute zero.
int residualSum = 0;
if (uNormalize != 0) {
for (int i = lane; i < pixelCount; i += 128) {
ivec2 p = origin + ivec2(i % uTileSize, i / uTileSize);
residualSum += warpedCurrentValueAt(vec2(p) + flow) - referenceValueAt(p);
}
}
float minusX = sadAt(origin, best - ivec2(1, 0));
float plusX = sadAt(origin, best + ivec2(1, 0));
float minusY = sadAt(origin, best - ivec2(0, 1));
float plusY = sadAt(origin, best + ivec2(0, 1));
float denomX = minusX + plusX - 2.0 * bestCost;
float denomY = minusY + plusY - 2.0 * bestCost;
float subX = abs(denomX) > 1.0e-12
? 0.5 * (minusX - plusX) / denomX
: 0.0;
float subY = abs(denomY) > 1.0e-12
? 0.5 * (minusY - plusY) / denomY
: 0.0;
oAlignment = vec4(vec2(best) + clamp(vec2(subX, subY), -0.5, 0.5),
bestCost, 0.0);
sResidualSum[lane] = residualSum;
memoryBarrierShared();
barrier();
for (int stride = 64; stride > 0; stride >>= 1) {
if (lane < stride) {
sResidualSum[lane] += sResidualSum[lane + stride];
}
memoryBarrierShared();
barrier();
}
float count = float(pixelCount);
float meanResidual = uNormalize != 0 ? float(sResidualSum[0]) / count : 0.0;
vec2 target = vec2(0.0);
for (int i = lane; i < pixelCount; i += 128) {
ivec2 p = origin + ivec2(i % uTileSize, i / uTileSize);
// Subtract before reduction. Separately accumulating current*gradient
// and reference*gradient loses small residuals to Float32 cancellation.
float residual = warpedCurrentAt(vec2(p) + flow) -
referenceAt(p) - meanResidual;
target += residual * gradientAt(p);
}
sTarget[lane] = target;
memoryBarrierShared();
barrier();
for (int stride = 64; stride > 0; stride >>= 1) {
if (lane < stride) {
sTarget[lane] += sTarget[lane + stride];
}
memoryBarrierShared();
barrier();
}
if (lane == 0) {
imageStore(uOutput, tile, solveAlignment(tile, initialAlignment, sTarget[0], count));
}
}
""".trimIndent()
@@ -382,12 +382,12 @@ internal class GlesMgcRawSpatialStacker(
private var rawToGrayProgram = 0
private var downsampleProgram = 0
private var downsample4Program = 0
private var alignProgram = 0
private var alignmentGradientProductsProgram = 0
private var upsampleAlignmentProgram = 0
private var medianAlignmentProgram = 0
private var globalAlignment: GlesSpatialGlobalAlignment? = null
private var blockLucasKanadeProgram = 0
private var blockLucasKanadeUsesCompute = false
private var convertAlignmentProgram = 0
private var strengthAlignmentProgram = 0
private var strengthRejectionProgram = 0
@@ -2790,10 +2790,7 @@ internal class GlesMgcRawSpatialStacker(
"mgc_sabre_alignment_gradient_products",
)
upsampleAlignmentProgram = initMergeUpsampleAlignment()
blockLucasKanadeProgram = linkProgram(
GlesMgcRawSpatialShaders.blockLucasKanade,
"mgc_sabre_block_lucas_kanade",
)
initBlockLucasKanade("mgc_sabre_block_lucas_kanade")
convertAlignmentProgram = linkProgram(
GlesMgcRawSpatialShaders.convertAlignment,
"mgc_sabre_convert_alignment",
@@ -2857,6 +2854,21 @@ internal class GlesMgcRawSpatialStacker(
)
}
private fun initBlockLucasKanade(name: String) {
// A tile reduction needs the GLES 3.1 compute baseline; GLES 3.0 keeps one serial
// fragment per tile with the same sampling and solve functions.
blockLucasKanadeUsesCompute = supportsComputePrograms
blockLucasKanadeProgram = if (blockLucasKanadeUsesCompute) {
linkComputeProgram(GlesMgcRawSpatialShaders.blockLucasKanadeCompute, "${name}_compute")
} else {
linkProgram(GlesMgcRawSpatialShaders.blockLucasKanade, name)
}
DngCaptureDiagnostics.put(
"merge.lkDispatch",
if (blockLucasKanadeUsesCompute) "compute-tile-reduction-128" else "fragment-serial",
)
}
private fun initMergeUpsampleAlignment(): Int {
if (processorPipeline == MgcRawProcessorPipeline.SPATIAL) {
medianAlignmentProgram = linkProgram(
@@ -2908,11 +2920,7 @@ internal class GlesMgcRawSpatialStacker(
"mgc_alignment_gradient_products",
)
upsampleAlignmentProgram = initMergeUpsampleAlignment()
blockLucasKanadeProgram = linkProgram(
GlesMgcRawSpatialShaders.blockLucasKanade,
"mgc_block_lucas_kanade",
)
alignProgram = linkProgram(GlesMgcRawSpatialShaders.alignL1, "mgc_align_l1")
initBlockLucasKanade("mgc_block_lucas_kanade")
convertAlignmentProgram = linkProgram(
GlesMgcRawSpatialShaders.convertAlignment,
"mgc_convert_alignment",
@@ -3985,12 +3993,16 @@ internal class GlesMgcRawSpatialStacker(
"uHasInitialAlignment",
if (input != null) 1 else 0,
)
draw(
blockLucasKanadeProgram,
gridWidth,
gridHeight,
intArrayOf(output),
)
if (blockLucasKanadeUsesCompute) {
dispatchBlockLucasKanade(output, gridWidth, gridHeight)
} else {
draw(
blockLucasKanadeProgram,
gridWidth,
gridHeight,
intArrayOf(output),
)
}
GlesGpuScheduler.yieldToUiRenderer()
input = Alignment(
texture = output,
@@ -4004,55 +4016,34 @@ internal class GlesMgcRawSpatialStacker(
return checkNotNull(input)
}
private fun renderAlignmentLevel(
reference: TextureLevel,
current: TextureLevel,
initial: Alignment?,
tileStride: Int,
tileSize: Int,
searchRadius: Int,
initialScale: Float,
): Alignment {
val gridWidth = ceilDiv(reference.width, tileStride)
val gridHeight = ceilDiv(reference.height, tileStride)
val output = createTexture(
gridWidth,
gridHeight,
GLES30.GL_RGBA16F,
GLES30.GL_NEAREST,
/** One work group per LK tile; [output] is an immutable RGBA32F scratch alignment. */
private fun dispatchBlockLucasKanade(output: Int, gridWidth: Int, gridHeight: Int) {
// GLES 3.1 guarantees 65535 work groups per axis; LK grids are tile counts.
check(gridWidth in 1..65535 && gridHeight in 1..65535) {
"LK grid ${gridWidth}x$gridHeight exceeds the GLES 3.1 dispatch baseline"
}
GLES31.glBindImageTexture(
0,
output,
0,
false,
0,
GLES31.GL_WRITE_ONLY,
GLES30.GL_RGBA32F,
)
GLES30.glUseProgram(alignProgram)
bindTexture(alignProgram, "uReference", 0, reference.texture)
bindTexture(alignProgram, "uCurrent", 1, current.texture)
val initialTexture = initial?.texture ?: createZeroFlowTexture()
bindTexture(
alignProgram,
"uInitialAlignment",
2,
initialTexture,
)
uniform2i(alignProgram, "uImageSize", reference.width, reference.height)
uniform2i(alignProgram, "uGridSize", gridWidth, gridHeight)
uniform2i(
alignProgram,
"uInitialGridSize",
initial?.gridWidth ?: gridWidth,
initial?.gridHeight ?: gridHeight,
)
uniform1i(alignProgram, "uTileStride", tileStride)
uniform1i(alignProgram, "uTileSize", tileSize)
uniform1i(alignProgram, "uSearchRadius", searchRadius)
uniform1f(alignProgram, "uInitialScale", initialScale)
uniform1i(alignProgram, "uHasInitialAlignment", if (initial != null) 1 else 0)
draw(alignProgram, gridWidth, gridHeight, intArrayOf(output))
return Alignment(
texture = output,
gridWidth = gridWidth,
gridHeight = gridHeight,
tileStride = tileStride,
scaleToBayerQuads = reference.scaleToBayerQuads,
gridMin = 0,
GLES31.glDispatchCompute(gridWidth, gridHeight, 1)
// Consumers are the next iteration's sampler, upsample/convert draws and readbacks.
GlesGpuScheduler.memoryBarrier()
GLES31.glBindImageTexture(
0,
0,
0,
false,
0,
GLES31.GL_WRITE_ONLY,
GLES30.GL_RGBA32F,
)
checkGlError("MGC LK compute ${gridWidth}x$gridHeight")
}
private fun createConvertedAlignment(alignment: Alignment): ConvertedAlignment {
@@ -6616,71 +6607,6 @@ internal class GlesMgcRawSpatialStacker(
* Resolves the small persistent alignment grids once after temporal completion. Exact bounds
* avoid replaying hundreds of unused RAW halo rows for every reconstruction band.
*/
private fun resolveRgbFlowBounds(frames: List<RgbMergeFrame>): List<RgbMergeFrame> {
val byteCount = bayerAlignmentWidth.toLong() * bayerAlignmentHeight * 4L * Float.SIZE_BYTES
require(byteCount in 1..Int.MAX_VALUE.toLong())
val readback = ByteBuffer.allocateDirect(byteCount.toInt()).order(ByteOrder.nativeOrder())
return frames.map { frame ->
if (frame.flowBounds == MgcSpatialRgbFlowBounds.Zero) {
frame
} else {
bindRenderTargets(
intArrayOf(frame.alignmentTexture),
"MGC RGB alignment bounds frame ${frame.imageIndex}",
)
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, Float.SIZE_BYTES)
GLES30.glPixelStorei(GLES30.GL_PACK_ROW_LENGTH, 0)
readback.clear()
GLES30.glReadPixels(
0,
0,
bayerAlignmentWidth,
bayerAlignmentHeight,
GLES30.GL_RGBA,
GLES30.GL_FLOAT,
readback,
)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
checkGlError("read MGC RGB alignment bounds frame ${frame.imageIndex}")
val values = readback.asFloatBuffer()
var minimumX = Float.POSITIVE_INFINITY
var minimumY = Float.POSITIVE_INFINITY
var maximumX = Float.NEGATIVE_INFINITY
var maximumY = Float.NEGATIVE_INFINITY
for (pixel in 0 until bayerAlignmentWidth * bayerAlignmentHeight) {
val x = values.get(pixel * 4)
val y = values.get(pixel * 4 + 1)
check(x.isFinite() && y.isFinite()) {
"MGC RGB alignment frame ${frame.imageIndex} contains non-finite flow"
}
minimumX = minOf(minimumX, x)
minimumY = minOf(minimumY, y)
maximumX = maxOf(maximumX, x)
maximumY = maxOf(maximumY, y)
}
val bounds = MgcSpatialRgbFlowBounds(
minX = minimumX,
minY = minimumY,
maxX = maximumX,
maxY = maximumY,
)
check(
bounds.minX >= conservativeRgbFlowBounds.minX &&
bounds.minY >= conservativeRgbFlowBounds.minY &&
bounds.maxX <= conservativeRgbFlowBounds.maxX &&
bounds.maxY <= conservativeRgbFlowBounds.maxY
) {
"MGC RGB alignment frame ${frame.imageIndex} exceeds analytical bounds: " +
"$bounds expected=$conservativeRgbFlowBounds"
}
PLog.d(TAG, "MGC RGB flow bounds frame=${frame.imageIndex} $bounds")
frame.copy(flowBounds = bounds)
}
}.also {
detachRenderTargets()
}
}
private fun detachRenderTargets() {
if (renderFbo == 0 || renderTargetAttachmentCount == 0) return
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, renderFbo)